text
stringlengths
11
4.05M
package main import ( "context" "fmt" "log" "net/http" "os" "cloud.google.com/go/pubsub" "google.golang.org/appengine" "github.com/sh0e1/translation-konjac/pkg/handler" "github.com/sh0e1/translation-konjac/pkg/language" "github.com/sh0e1/translation-konjac/pkg/middleware" ps "github.com/sh0e1/translation-...
package heartbeat import ( "bytes" "common/model" "config" "encoding/json" "io/ioutil" "net/http" "strconv" "time" "github.com/astaxie/beego/logs" ) const ( httpStatusOk = 200 ) //获取当前agent信息 func collectInfo() []byte { agent := model.HeartbeatRequest{ SystemTime: time.Now(), Ip: config.Conf...
package main import ( "fmt" ) // 207. 课程表 // 你这个学期必须选修 numCourse 门课程,记为 0 到 numCourse-1 。 // 在选修某些课程之前需要一些先修课程。 例如,想要学习课程 0 ,你需要先完成课程 1 ,我们用一个匹配来表示他们:[0,1] // 给定课程总量以及它们的先决条件,请你判断是否可能完成所有课程的学习? // 提示: // 输入的先决条件是由 边缘列表 表示的图形,而不是 邻接矩阵 。详情请参见图的表示法。 // 你可以假定输入的先决条件中没有重复的边。 // 1 <= numCourses <= 10^5 // http...
/* ====================BASIC GO DATA TYPE============================ Numeric Data type Go has a native support for integers,floating-point numbers and complex numbers. =====================Signed and unsigned integer================ Signed Integer(-127 to 127) unsigned integer(0 to 255) 1.int8 ...
package main import ( "encoding/json" "fmt" ) type TermType byte const ( EOF TermType = iota Nonterminal Terminal Any ) func main() { fmt.Println("vim-go", Any) b, err := json.Marshal(Any) if err != nil { fmt.Println(err) return } fmt.Println(string(b)) str := "\"Any\"" var t TermType fmt.Println...
/*** * * Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number. Return the decimal value of the number in the linked list. Example 1: Input: head = [1,0,1] Output: 5 Expla...
package schoolmeal import ( "testing" "time" ) func TestSchool_GetWeekMeal(t *testing.T) { school, err := Find(Jeonnam, "광양제철고등학교") if err != nil { t.Error("Unexpected", err) t.Failed() } meals, err := school.GetWeekMeal("2020.08.08", Lunch) if err != nil { t.Error("Unexpected", err) t.Failed() } m...
package wallet import ( "os" "strconv" "github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/transaction" "github.com/iotaledger/wasp/packages/txutil/vtxbuilder" "github.com/iotaledger/wasp/tools/wasp-cli/config" "github.com/iotaledger/wasp/tools/wasp-cli/log" "github.com/iotaledger/wasp/tools/wasp-cl...
/* Copyright 2020 Humio https://humio.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, ...
package main import ( "blockchains/RepoBlockChain/bolt" "fmt" "log" "os" ) const blockBucket = "blockBucket" const lastHashKey = "lastHashKey" type BlockChain struct { db *bolt.DB //数据库句柄 tail []byte //最后一个区块的hash } func CreateBlockChain()*BlockChain { //1.获得数据库句柄 打开数据库 读写数据 db ,err :=bolt.Open("...
package lib import ( "fmt" ) // StatusError define. type StatusError struct { fun string reason string } // Error override func (that *StatusError) Error() string { return fmt.Sprintf("function : %s, because %s", that.fun, that.reason) } // NewStatusError creates an Status code func NewStatusError(fun string...
package main import ( "io/ioutil" "os" ) // read 负责读取文件 // 这是一个通用的方法 func read(path string) []byte { file, err := os.Open(path) if err != nil { panic(err) } defer file.Close() data, err := ioutil.ReadAll(file) return data }
package server import ( "io" "github.com/asppj/cnbs/net-bridge/tunnel" "github.com/asppj/cnbs/log" "github.com/gogf/gf/net/gtcp" ) // 读取代理端口请求 func (s *Server) proxyHTTPHandle(conn *gtcp.Conn) { err := tunnel.SetDeadLine(conn) if err != nil { log.Error("设置超时时间失败") return } defer func() { if err != io....
package config // FileConfig holds configuration about standard files to backup type FileConfig struct { // Files to backup. Can include shell globs. Files []string `validate:"required"` // Exclude holds names of files / directories to exclude from backup. // Can include shell globs. Exclude []string }
package main import ( "net" "log" "fmt" "strings" ) func main() { listen, err := net.Listen("tcp", ":8088") //ch := make(chan interface{}) if err != nil { log.Fatal(err) return } fmt.Println("service start.....") for { conn, err := listen.Accept() if err != nil { log.Fatal(err) break } go...
package proxy import ( pb "logstream/pkg/proto" "logstream/pkg/utils" "net" "log" "google.golang.org/grpc" ) func NewProxy(laddr, raddr string) *proxy { return &proxy{ laddr: laddr, grpcSrv: grpc.NewServer(), upstreamReader: utils.NewReceiverSender(raddr), } } type proxy struct { ladd...
package main func subarraysDivByK(A []int, K int) int { m := map[int]int{0: 1} if len(A) == 0 { return 0 } tempSum := 0 res := 0 for _, v := range A { tempSum += v res += m[(tempSum%K+K)%K] m[(tempSum%K+K)%K]++ } return res }
package models type PNRStatus int64 const ( PNRBookingFailured PNRStatus = 1 PNRIssuing PNRStatus = 2 PNRIssued PNRStatus = 4 PNRCanceled PNRStatus = 8 ) type PnrInfo struct { PnrCode string BigPnr string ChdPolicyID string CommissionRate float64 PnrText stri...
package command import ( "fmt" "github.com/go-xorm/xorm" _ "github.com/jinzhu/gorm/dialects/mysql" "github.com/koyeo/tablewriter" "github.com/ttacon/chalk" "github.com/urfave/cli" "mix/core/logger" "os" "regexp" "strings" "xorm.io/core" ) func (p *Handler) DiffCommand(ctx *cli.Context) (err error) { p.lo...
// Copyright 2023 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applica...
package server import ( "fmt" "html/template" //"io" "net/http" "os" "path/filepath" ) func (h *httpInteractor) indexPage() http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { wd, err := os.Getwd() if err != nil { panic(err) } p := Page{ Title: "Index", }...
package main import "fmt" type MyReader struct{} func (m MyReader) Read(b []byte) (n int, err error) { for i := range b { b[i] = 'A' } return len(b), nil } func main() { r := MyReader{} b := make([]byte, 8) for { b, err := r.Read(b) fmt.Println(string(b)) if err != nil { break } } }
package components import ( "github.com/stretchr/testify/assert" "testing" ) func TestCalculateHash(t *testing.T) { title := "foo bar" desc := "foo bar baz" hash := CalculateHash(Block{ Index: 1, Timestamp: "2020-06-03 23:00:00 +0000 UTC m=+0.000000000", Hash: "", PrevHash: "", Msg: &Message{...
package reverse func Reverse(input string) string { var reversed string for _,ch := range input { reversed = string(ch) + reversed } return reversed }
// Copyright 2022 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...
func maxProfit(prices []int) int { max := 0 min := prices[0] for i := 1; i < len(prices); i++ { tmp := prices[i] - min if tmp > max { max = tmp } if prices[i] < min { min = prices[i] } } return max }
package http import ( "encoding/json" "fmt" "net/http" "path" logging "github.com/op/go-logging" "github.com/svenwltr/uplog/uptimed" ) var log *logging.Logger = logging.MustGetLogger("uplog.http") func loggedHandler(handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *...
package main import ( "github.com/astaxie/beego" "ConfCenter_web_Admin/initialization" _ "ConfCenter_web_Admin/route" ) func main(){ err := initialization.Init() if err != nil { return } beego.Run() }
package api_test import ( "context" "net/http" "reflect" "strings" "testing" "github.com/chanioxaris/go-datagovgr/datagovgrtest" "github.com/jarcoal/httpmock" ) func TestBusinessEconomy_NumberOfTravelAgencies_Success(t *testing.T) { ctx := context.Background() fixture := datagovgrtest.NewFixture(t) httpmo...
package config_test import ( "testing" "github.com/stewelarend/config" ) func Test1(t *testing.T) { values := config.NewValues("test", nil) val, ok := values.Get("") if ok || val != nil { t.Fatalf("get(\"\")->%v,%v", val, ok) } val, ok = values.Get("a") if ok || val != nil { t.Fatalf("get(\"a\")->%v,%v"...
package main import ( "fmt" "os" "strings" "github.com/therecipe/qt/core" "github.com/therecipe/qt/gui" "github.com/therecipe/qt/printsupport" "github.com/therecipe/qt/quick" ) type SlideView struct { quick.QQuickView _ func() `constructor:"init"` _ func(status quick.QQuickView__Status)...
package benchmark type node struct { data int next *node } type linkedList struct { head *node tail *node } func (l *linkedList) push(n *node) { if l.head == nil { l.head = n l.tail = n return } l.tail.next = n l.tail = n } func (l *linkedList) traverse(action func(int)) error { element := l.head f...
package stemsrepo import ( "encoding/json" "encoding/xml" "path/filepath" "time" bosherr "github.com/cloudfoundry/bosh-utils/errors" boshlog "github.com/cloudfoundry/bosh-utils/logger" boshsys "github.com/cloudfoundry/bosh-utils/system" bhnotesrepo "github.com/bosh-io/web/stemcell/notesrepo" "github.com/dp...
package sessions import ( "context" "database/sql" "errors" "fmt" "github.com/agui2200/GoMybatisV2/logger" "github.com/agui2200/GoMybatisV2/sessions/tx" "github.com/agui2200/GoMybatisV2/sqlbuilder" "github.com/agui2200/GoMybatisV2/utils" "github.com/go-sql-driver/mysql" "github.com/opentracing/opentracing-go...
package middleware import ( "2021/yunsongcailu/yunsong_server/backend/backend_service" "2021/yunsongcailu/yunsong_server/common" "2021/yunsongcailu/yunsong_server/param/backend_param" "2021/yunsongcailu/yunsong_server/param/web_param" "fmt" "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/binding" "strconv...
package apps import ( "fmt" ) func (app *App) Deploy() error { app.Pause() defer app.Unpause() var ( err error ) err = app.sync_collaborators() if err != nil { return err } fmt.Println("") err = app.sync_features() if err != nil { return err } fmt.Println("") err = app.sync_domains() if err !...
package mongodb import ( "server/libs/log" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" //. "logicdata/parser" //"os" "server" //"strings" "server/util" ) var ( ROLEINFO = "role_info" COUNTERS = "counters" db *MongoDB ) type MongoDB struct { session *mgo.Session DB *mgo.Database wg util.Wa...
package scene import "github.com/eriklupander/rt/internal/pkg/mat" type Scene struct { Camera mat.Camera Lights []mat.Light AreaLights []mat.AreaLight Objects []mat.Shape }
package subscription import ( "encoding/json" "testing" "github.com/dennor/go-paddle/events" "github.com/dennor/go-paddle/events/test" "github.com/dennor/go-paddle/events/types" "github.com/dennor/go-paddle/signature" "github.com/dennor/urldecode" "github.com/stretchr/testify/assert" ) func subscriptionCance...
package startgameusecase import "backend/internal/domain" type UseCase interface { Execute() (domain.GameId, error) } func New(gameRepository domain.GameRepository) UseCase { return &startGameUseCase{ gameRepository: gameRepository, } } type startGameUseCase struct { gameRepository domain.GameRepository } fu...
// Copyright 2016 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" // https://leetcode-cn.com/problems/permutations/ func permute(nums []int) [][]int { n := len(nums) if n == 0 { return [][]int{} } total := 1 for i := 2; i <= n; i++ { total *= i } mark := make([]bool, n) perm := make([]int, n) res, cnt := make([][]int, total), 0 add := fun...
package labels import ( "sync" "time" "github.com/square/p2/pkg/kp/consulutil" "github.com/square/p2/pkg/logging" "github.com/square/p2/Godeps/_workspace/src/github.com/Sirupsen/logrus" "github.com/square/p2/Godeps/_workspace/src/github.com/hashicorp/consul/api" "github.com/square/p2/Godeps/_workspace/src/k8s...
package middlewares import ( "fmt" "github.com/andrewesteves/taskee-api/entities" "github.com/andrewesteves/taskee-api/utils" "github.com/gofiber/fiber" "github.com/jinzhu/gorm" ) // ConfigAuth config for Auth type ConfigAuth struct { DB *gorm.DB } // NewAuth middleware func NewAuth(config ConfigAuth) func(*f...
package centurylink_sdk import ( "fmt" "io/ioutil" "time" "github.com/s-matyukevich/centurylink_sdk/models" "github.com/s-matyukevich/centurylink_sdk/models/account" "github.com/s-matyukevich/centurylink_sdk/models/datacenters" "github.com/s-matyukevich/centurylink_sdk/models/groups" "github.com/s-matyukevich...
/* Copyright 2021 The KubeVela Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, softw...
// Package app contains the app specific data structure. package app import ( "log" "github.com/asdine/storm" "github.com/spazbite187/sensornet" ) // Data contains all the global configuration data including the loggers. type Data struct { DIR, Assets, Version string DB *storm.DB Log, ErrLo...
package redis type SortedSet struct { } func (s *SortedSet) ZAdd(score float64, value string) int { return 1 } func (s *SortedSet) ZRange(from,to float64,withScores bool) { }
// // Copyright (C) 2019-2021 vdaas.org vald team <vald@vdaas.org> // // 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 requir...
package dict_data import ( "time" "yj-app/app/yjgframe/db" ) type Entity struct { DictCode int64 `json:"dict_code" xorm:"not null pk autoincr comment('字典编码') BIGINT(20)"` DictSort int `json:"dict_sort" xorm:"default 0 comment('字典排序') INT(4)"` DictLabel string `json:"dict_label" xorm:"default ''...
// Copyright 2021 BoCloud // // 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 wri...
package sqlc import ( "bytes" "fmt" "io" "strings" ) var predicateTypes = map[PredicateType]string{ EqPredicate: "=", GtPredicate: ">", GePredicate: ">=", LtPredicate: "<", LePredicate: "<=", } func (u *update) String(d Dialect) string { return toString(d, u) } func (u *update) Render(d Dialect, w io.Writ...
package main import ( "bytes" "encoding/xml" "fmt" "os" ) type RssFeed struct { XMLName xml.Name `xml:"rss"` Channel *RssChannel `xml:"channel"` } type RssChannel struct { XMLName xml.Name `xml:"channel"` Title string `xml:"title"` Description string `xml:"d...
package tick import ( "encoding/json" "fmt" "github.com/astaxie/beego/orm" "io/ioutil" "net/http" "time" "tokensky_bg_admin/models" "tokensky_bg_admin/utils" ) const souderCoinUrl = "https://pool.viabtc.com/res/pool/state/new" type spiderCoinResp struct { Code int `json:"code"` Da...
package tap import ( "fmt" "strings" "testing" ) func ExampleNewParser() { r := strings.NewReader(`1..3 ok 1 hogehoge not ok foobar # Doesn't wiggle not ok 3 foobar # TODO not implemented yet`) p, err := NewParser(r) if err != nil { panic(err) } suite, err := p.Suite() if err != nil { panic(err) } if ...
package uagent import ( "math/rand" ) var agents = []string{ "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36", "Mozilla/5.0 (X11; Linux x...
package main import ( "context" "encoding/binary" "encoding/json" "fmt" "net" "os" "os/exec" "path/filepath" "strings" "sync" "time" cbnet "github.com/cloud-barista/cb-larva/poc-cb-net/internal/cb-network" dataobjects "github.com/cloud-barista/cb-larva/poc-cb-net/internal/cb-network/data-objects" etcdke...
package app import ( "fmt" "log" "net/http" "time" handlers "github.com/chutommy/metal-price/api-server/app/handlers" services "github.com/chutommy/metal-price/api-server/app/services" config "github.com/chutommy/metal-price/api-server/config" currency "github.com/chutommy/metal-price/currency/service/protos/...
package pathfileops import ( "strings" "testing" ) func TestFileOperationCode_01(t *testing.T) { fopFirst := FileOpCode.None() if int(fopFirst) != 0 { t.Errorf("Error: Expected first File Operations Code = 0. Instead, first "+ "File Operation Code = '%v' ", int(fopFirst)) } if 0 != fopFirst....
// +build wireinject package di import ( "net/http" "github.com/google/wire" "github.com/inari111/layered-architecture-example-2020/handler/api" ) func InitializeAPIHandler() http.Handler { wire.Build( api.NewTaskService, api.NewHandler, ) return nil }
// Package mirror provides local mirroring and replica management /* * Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. */ package xaction import ( "github.com/NVIDIA/aistore/cluster" "github.com/NVIDIA/aistore/cmn" "github.com/NVIDIA/aistore/fs/mpather" ) type XactBckJog struct { XactBase t ...
package main import ( "fmt" "go-basic/hsp/encapeExe/model" ) func main() { // 创建一个account变量 account := model.NewAccount("jsa09876", "000000", 40) if account != nil { fmt.Println("创建成功=", account) account.WithDraw(20.0, "000000") account.Query("000000") } else { fmt.Println("创建失败") } }
package ibmcloud import ( "testing" "github.com/stretchr/testify/assert" ) func TestClusterResourceGroupName(t *testing.T) { infraID := "infra-id" platform := Platform{} platform.ResourceGroupName = "" assert.Equal(t, infraID, platform.ClusterResourceGroupName(infraID)) platform.ResourceGroupName = "test-clus...
package contribution import ( "reflect" "sort" "strings" "testing" "github.com/sirupsen/logrus" "github.com/ti-community-infra/tichi/internal/pkg/externalplugins" "k8s.io/test-infra/prow/config" "k8s.io/test-infra/prow/github" "k8s.io/test-infra/prow/github/fakegithub" ) func TestHandlePullRequest(t *testin...
// Package store provides a simple distributed key-value store. The keys and // associated values are changed via distributed consensus, meaning that the // values are changed only when a majority of nodes in the cluster agree on // the new value. // // Distributed consensus is provided via the Raft algorithm, specific...
package main import ( "github.com/bbcloudGroup/gothic/bootstrap" "gothic-app/boot" ) func main() { app := boot.NewApp(bootstrap.GetArgs()) app.Run() }
// Simple bittorrent client, created with duit. package main import ( "flag" "fmt" "image" "log" "os" "sort" "strconv" "time" "9fans.net/go/draw" "github.com/mjl-/duit" "github.com/anacrolix/torrent" "github.com/anacrolix/torrent/metainfo" "golang.org/x/time/rate" ) const ( colStatus = iota colName ...
// +build windows package ps import ( "fmt" "syscall" "time" "unsafe" ) // Windows API functions var ( modKernel32 = syscall.NewLazyDLL("kernel32.dll") procCloseHandle = modKernel32.NewProc("CloseHandle") procCreateToolhelp32Snapshot = modKernel32.NewProc("CreateToolhelp32Snapsho...
package main import ( "fmt" "log" ) func main() { defer func() { fmt.Println("halo dunia") }() log.Fatal("error fatal here") //if we use this, the defer function will not be executed after log.Fatal is executed // log.Panic("error panic here") //instead we should use other log methods, like log.Panic }
package auth_test import ( "context" "fmt" "testing" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider" "github.com/stretchr/testify/require" auth "github.com/gofor-little/aws-auth" ) func TestSignIn(t *testing.T) { setup(t) defer teardown(t) testCases := []...
package dictionary // import ( // "github.com/Evedel/fortify/src/say" // ) func typeString(ttail []Token) (resCode int, stopInd int, resToken TokenNode, errmsg string) { lentt := len(ttail) resCode = UndefinedError stopInd = 0 errmsg = "" childs := []TokenNode{} // errmsg = "Default string form is \"word word...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/11/18 9:02 上午 # @File : select.go # @Description : # @Attention : */ package sort // 选择排序 // 关键: // 双重for 循环遍历 // 第二重for循环用途在于:把最小的那个进行交换 func SelectionSort(arr []int) []int { if len(arr) == 0 { return nil } for i := 0; i < len(arr); i++ { minIndex := ...
package server import ( "fmt" "net/http" "strings" "github.com/openebs/mayaserver/lib/api/v1" "github.com/openebs/mayaserver/lib/volume/jiva" ) func (s *HTTPServer) VolumesRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) { switch req.Method { case "GET": return s.volumeListRequest(r...
// Copyright (c) 2019 VMware, Inc. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package archiver import ( "archive/tar" "compress/gzip" "io" "os" "path/filepath" "strings" "github.com/sirupsen/logrus" ) // Tar compresses the file sources specified by paths into a single // tarball specified by...
package model type BlockResponse struct { Height int64 `json:"height"` ParentHash string `json:"parent_hash"` BlockHash string `json:"block_hash"` Timestamp int64 `json:"timestamp"` Extrinsic []*ExtrinsicResponse `json:"extrinsic"` }
package main import "fmt" func Sample() func(a int, b int) int { f := func(a int, b int) int { return a + b } return f } func main() { f := Sample() fmt.Println(f(10, 20)) }
package messagequeue import ( "context" "testing" "time" "gx/ipfs/QmYJ48z7NEzo3u2yCvUvNtBQ7wJWd5dX2nxxc7FeA6nHq1/go-bitswap/testutil" peer "gx/ipfs/QmPJxxDsX2UbchSHobbYuvz7qnyJTFKvaKMzE2rZWJ4x5B/go-libp2p-peer" bsmsg "gx/ipfs/QmYJ48z7NEzo3u2yCvUvNtBQ7wJWd5dX2nxxc7FeA6nHq1/go-bitswap/message" bsnet "gx/ipfs/Qm...
package sqlstore import ( "database/sql" "fmt" "github.com/manishrjain/gocrud/store" "github.com/manishrjain/gocrud/x" ) var log = x.Log("sqlstore") type Sql struct { db *sql.DB } var sqlInsert *sql.Stmt var sqlIsNew, sqlSelect string func (s *Sql) Init(args ...string) { if len(args) != 3 { log.WithField(...
package main import ( "log" "net/http" "os/exec" "time" ) func checkResponse(c *http.Client, r *http.Request) bool { defer func() { if e := recover(); e != nil { log.Println("Error: ", e) } }() res, err := c.Do(r) if err != nil { panic(err) } if res.StatusCode == 200 { return true } return f...
package main import ( "bufio" "fmt" "math" "os" "strconv" "strings" ) //import "strings" //import "strconv" /** * Auto-generated code below aims at helping you parse * the standard input according to the problem statement. **/ func main() { scanner := bufio.NewScanner(os.Stdin) scanner.Buffer(make([]byte...
package parser import ( "regexp" "strings" ) // ParseOmegaResults parses omega results func ParseOmegaResults(lines []string) []string { var omegaLine string r := regexp.MustCompile("E[\\+|\\-]") for _, line := range lines { if r.MatchString(line) { // slice off the leading + from each line omegaLine += ...
package post import "strings" const ( // MaxCommentContent how long a comment it's allowed to be MaxCommentContent = 256 // RemovedComment a comment that has been removed RemovedComment = "REMOVED" // ActiveComment a comment in its by default state ActiveComment = "ACTIVE" ) // Comment . type Comment struct { ...
package LeetCode import ( "math" ) func IsPalindrome(x int) bool { if x < 0 { return false } fx := float64(x) r := 0 for { r = r *10 + int(math.Mod(fx,10)) fx /= 10 if fx < 1 { break } } return (r == x) }
package _5_datatype import ( "math" "math/cmplx" "testing" "unsafe" ) func TestComplexType(t *testing.T) { /** 复数 i = 根号 -1 则 i^2 = -1 i^3 = -i i^4 = 1... */ var c complex128 = 3 + 4i // 默认 complex128 t.Log(cmplx.Abs(c)) // 5 // 欧拉公式 : e^(iπ) + 1 = 0 t.Log(cmplx.Pow(math.E, 1i*math.Pi) + 1) // (0+1...
package main import "strings" func lengthOfLastWord(s string) int { if len(s) == 0 { return 0 } s = strings.Trim(s, " ") ss := strings.Split(s, " ") return len(ss[len(ss)-1]) }
package v1alpha1 import ( "encoding/json" "fmt" "strings" "testing" "github.com/stretchr/testify/assert" ) func TestItem(t *testing.T) { for data, expectedType := range map[string]Type{ "0": Number, "3.141": Number, "true": ...
package goemetry import ( "os" "runtime" "strings" "testing" svg "github.com/ajstarks/svgo" "github.com/stretchr/testify/assert" ) func TestIsAboveishSuperSimpleBaseCase(t *testing.T) { one := BoundingBox{ BottomLeft: Point{ X: 100, Y: 100, }, Height: 10, Width: 10, } two := BoundingBox{ ...
package main import ( "fmt" ) func main() { // like async await in nodejs ??? done := make(chan bool) go helloGo(done) // uncoment this if not using channel // time.Sleep(1 * time.Second) <-done fmt.Println("ini fungsi main") } func helloGo(done chan bool) { fmt.Println("Hello Go") done <- true }
package main import "fmt" type grade float64 func (g grade) between(start, end float64) bool { return float64(g) >= start && float64(g) <= end } func gradeConcept(g grade) string { if g.between(9.0, 10.0) { return "A" } else if g.between(7.0, 8.99) { return "B" } else if g.between(5.0, 7.99) { return "C" ...
package identity import ( "net/http" "os" "testing" "github.com/databrickslabs/databricks-terraform/common" "github.com/databrickslabs/databricks-terraform/internal/qa" "github.com/stretchr/testify/assert" ) func TestResourceInstanceProfileCreate(t *testing.T) { d, err := qa.ResourceFixture{ Fixtures: []qa....
package view import ( "fmt" "github.com/merisho/snakegame/presenter" "os" "os/exec" "runtime" ) func NewCLIView(s *presenter.Snake, mapWidth, mapHeight int) *CLIView { return &CLIView{ s: s, mapWidth: mapWidth, mapHeight: mapHeight, } } type CLIView struct { s *presenter.Snake mapWidt...
package cli import ( "github.com/HNB-ECO/HNB-Blockchain/HNB/cli/common" "github.com/HNB-ECO/HNB-Blockchain/HNB/cli/utils" "github.com/HNB-ECO/HNB-Blockchain/HNB/msp" "bufio" "fmt" "github.com/urfave/cli" "strings" ) type curveInfo struct { name string code byte } type schemeInfo struct { name string code ...
package financial_project type FinancialProject struct { id string name string startDate string endDate string amountGoal int }
package door import ( "sync" ) var defaultDirectory Directory var once sync.Once func DefaultDirectory() Directory { once.Do(func() { defaultDirectory = NewDirectory() }) return defaultDirectory }
/* store the params in path */ package param type PathParams struct { Params map[string][]string } //get param value by name func (pathParams *PathParams) GetByName(key string) interface{} { if len(pathParams.Params[key]) > 1 { return pathParams.Params[key] } else if len(pathParams.Params[key]) == 1 { return p...
package controllers import ( "context" "fmt" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "log" ) // DB connection string // const connectionString = "mongodb://localhost:27017" or Atlas Connection String const connectionString = "mongodb://l...
package main import ( "flag" "logstream/pkg/server" "time" ) func main() { addr := flag.String("addr", ":8000", "address on which to listen") writeFx := flag.Duration("freq", 1*time.Second, "frequency of writes") flag.Parse() s := server.NewServer(*addr, *writeFx) s.Start() }
// ˅ package main // ˄ type Data struct { // ˅ // ˄ name string items []Item // ˅ // ˄ } func NewData(name string) *Data { // ˅ data := &Data{} data.name = name return data // ˄ } func (self *Data) Add(item Item) { // ˅ self.items = append(self.items, item) // ˄ } // ˅ // ˄
package main import ( "engine/api" "engine/config" "engine/service" "flag" "github.com/gin-gonic/gin" ) var configPath string func init() { flag.StringVar(&configPath, "c", "", "config path") } func main() { flag.Parse() config.InitSysConfig(configPath) gin.SetMode(gin.ReleaseMode) // new service servic...
package week12 import ( . "algorithm-go/utils" ) /* 单调递增的[]nums (栈底)1, 2, 3, 5(栈顶) s := stack<int> for _, n := range nums{ while len(s) != 0 && s.top() >= n{ s.pop() } s.push(n) } 1. 栈顶元素 -> 右边第一个比自己小的数字 2. 栈顶元素 -> 从自己往左第一个比自己小的数字 3. 栈顶元素 -> 包含自己,且自己是最大的一个子数组 (r-l) 4. 新数字 -> 从自己往左,第一个比自己大的数 5. 新数字 -> 左边最接近...