text
stringlengths
11
4.05M
package workflows import ( "errors" "github.com/stretchr/testify/assert" "testing" ) func TestNewWorkflow(t *testing.T) { assert := assert.New(t) // empty emptyWorkflow := newWorkflow() assert.Nil(emptyWorkflow()) // error case errorWorkflow := newWorkflow(func() error { return errors.New("error occurred...
// Copyright The OpenTelemetry 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 agre...
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
package main import ( "bytes" "context" "encoding/json" "log" "os" "os/signal" "time" "github.com/kuba--/splunk" ) type jsonWriter struct { buf bytes.Buffer } func (w *jsonWriter) Write(data []byte) (int, error) { json.Indent(&w.buf, data, "", "\t") w.buf.WriteTo(os.Stdout) return w.buf.Len(), nil } f...
package main import ( "fmt" ) func nextGreaterElement(nums1 []int, nums2 []int) []int { stack := make([]int, 0, len(nums2)) findMap := make(map[int]int) for i := len(nums2) - 1; i >= 0; i-- { for len(stack) != 0 && nums2[i] > stack[len(stack)-1] { stack = stack[:len(stack)-1] } if len(stack)...
package main import "fmt" type Minute int type Hour int func main() { var m1 Minute = 10 m2 := Minute(20) // Notice the type conversion // Supports all operations of underlying types fmt.Println("Total Minutes: ", m1+m2) // Can be compared with same named type or same underlying type fmt.Println(m1 > m2) f...
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. // package model import ( "encoding/json" "io" "net/url" "github.com/pkg/errors" ) // GetClusterInstallationsRequest describes the parameters to request a list of cluster installations. type GetCluste...
package router import ( "editorApi/controller/editorapi" "editorApi/middleware" "github.com/gin-gonic/gin" ) func InitReportsRouter(Router *gin.RouterGroup) { ReportsRouter := Router.Group("editor").Use(middleware.CORSMiddleware(), middleware.JWTAuth()) { ReportsRouter.POST("reports/create", editorapi.ReportsC...
package copperhead import ( "reflect" "strings" "github.com/spf13/pflag" "github.com/spf13/viper" ) type ConfigOptions struct { EnvPrefix string } func Unmarshal(cfg interface{}, t reflect.Type, options ConfigOptions) (err error) { var cfgPath string pflag.StringVar(&cfgPath, "config", "config.yaml", "Path t...
package util import ( "fmt" neturl "net/url" "strconv" "strings" ) func StringMapGetDefault(m map[string]string, k string, def string) string { v, ok := m[k] if !ok { v = def } return v } func StringFromJson(m map[string]interface{}, k string) (string, error) { sInterface, ok := m[k] ...
/* * Created on Sat Dec 08 2018 20:8:58 * Author: WuLC * EMail: liangchaowu5@gmail.com */ // permutataion package main import "fmt" func largestTimeFromDigits(A []int) string { result := []string{""} permute(A, 0, len(A)-1, result) return result[0] } func permute(A []int, left int, right int, result []string...
package generate import ( "fmt" "github.com/wudiliujie/common/log" "github.com/wudiliujie/common/rpath" "github.com/wudiliujie/common/writer" ) type P struct { I int32 `xml:"i,attr"` N string `xml:"n,attr"` T string `xml:"t,attr"` Array bool `xml:"a,attr"` //是否是数组 D string `xml:"d,attr"` /...
package openrtb_ext import ( "encoding/json" "github.com/prebid/openrtb/v19/openrtb2" ) // DealTier defines the configuration of a deal tier. type DealTier struct { // Prefix specifies the beginning of the hb_pb_cat_dur targeting key value. Must be non-empty. Prefix string `json:"prefix"` // MinDealTier specif...
package regex func Plus(a int, b int, c int, d int, e int) int { return a + b + c + d + e }
package main import ( "fmt" "unicode" ) func main() { var input string fmt.Scanln(&input) if len(input) == 0 { fmt.Println(0) return } words := 1 for _, r := range input { if unicode.IsUpper(r) { words += 1 } } fmt.Println(words) }
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package setup import ( "chromiumos/tast/testing/hwdep" ) // PerfCUJBasicDevices returns list of DUT model in basic tier. // Allowed basic hardware models will be alowed-li...
package helpers import ( "io/ioutil" ) func ReadToBuff(p string) []byte { b, _ := ioutil.ReadFile(p) // TODO: uncomment // if err != nil { // panic(err) // } return b } func ContainsString(arr []string, elem string) bool { for i := range arr { if arr[i] == elem { return true } } return false } f...
package solutions func twoSum(nums []int, target int) []int { m := make(map[int]int) for index, num := range nums { pareValue := target - num if pareValueIndex, ok := m[pareValue]; ok { return []int{pareValueIndex, index} } else { m[num] = index } } return []int{} }
package models import ( "fmt" perm "github.com/picatic/go-permission-architect" ) // Permission represents a resolved Permission type Permission struct { name string //name of the permission granted bool //if the permission was granted or not role ...
package main func main() { name := "Earth" num := 25 status := true println(name) println(num) println(status) }
package storage import ( "database/sql" "fmt" "bitbucket.org/liamstask/goose/lib/goose" _ "github.com/mattn/go-sqlite3" "github.com/square/sharkey/pkg/server/config" "golang.org/x/crypto/ssh" ) // SqliteStorage implements the storage interface, using Sqlite for storage. type SqliteStorage struct { *sql.DB } ...
package models import ( "fmt" "sync" "github.com/jinzhu/gorm" ) type MyDb struct { sync.RWMutex *gorm.DB } type Article struct { ID int32 `gorm:"primary_key"` AId int32 `gorm:"index;unique"` // 对应文章生成页id Title string `gorm:"not null"` STitle string `gorm:"not null"` //...
package main import ( "strings" "github.com/1and1/oneandone-cloudserver-sdk-go" "github.com/codegangsta/cli" ) var monitorCenterOps []cli.Command func init() { statusFlags := []cli.Flag{ cli.BoolFlag{ Name: "cpu", Usage: "Set true to show CPU status.", }, cli.BoolFlag{ Name: "disk", Usage: "...
package transaction import ( "context" "github.com/ddouglas/ledger" "github.com/gofrs/uuid" "github.com/pkg/errors" ) func (s *service) CreateMerchant(ctx context.Context, merchant *ledger.Merchant) (*ledger.Merchant, error) { txn, err := s.starter.Begin() if err != nil { return nil, errors.Wrap(err, "faile...
// Copyright 2017 Baidu, 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...
package spudo type command struct { Name string // Name of the command Exec func(author string, args []string) interface{} // Function that will be executed when command is used Description string // Descriptio...
package block import ( "bytes" clock "github.com/filecoin-project/specs/systems/filecoin_nodes/clock" ) func (ts *Tipset_I) MinTicket() Ticket { var ret Ticket for _, currBlock := range ts.Blocks() { tix := currBlock.Ticket() if ret == nil { ret = tix } else { smaller := SmallerBytes(tix.Output(), r...
/* whoa za */ package main import ( "flag" "fmt" ) type myVertex struct { X int Y int } func structFunc() { v := myVertex{1, 2} v.X = 4 fmt.Println(v.X) schemaF := flag.String("schemaF", "../../types/schema.json", "Path to the file that specifies schema in json format") flag2 := flag.Bool("AAAAA", "../../...
package 二叉树 type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func leafSimilar(root1, root2 *TreeNode) bool { vals := []int{} var dfs func(*TreeNode) dfs = func(node *TreeNode) { if node == nil { return } if node.Left == nil && node.Right == nil { vals = append(vals, node.Val) re...
package generativerecursion import "testing" func TestThreatening(t *testing.T) { tests := []struct { a, b QP ok bool }{ {QP{0, 0}, QP{0, 3}, true}, {QP{0, 0}, QP{3, 0}, true}, {QP{0, 0}, QP{1, 1}, true}, {QP{0, 1}, QP{1, 0}, true}, {QP{0, 0}, QP{1, 3}, false}, } for i, tt := range tests { if o...
package models const ( CategoryTableName = "category" ) // 商品分类 type Category struct { BaseModel Name string Icon string ParentId uint } type CategorySerializer struct { ID uint `json:"id"` Name string `json:"name"` Icon string `json:"icon"` ParentId uint `json:"parentId"` ...
package mangadownloader import ( "net/url" "testing" ) var ( serviceMangaFoxTestUrlManga, _ = url.Parse("http://mangafox.me/manga/berserk/") serviceMangaFoxTestUrlChapter, _ = url.Parse("http://mangafox.me/manga/berserk/c134/1.html") ) func getTestMangaFoxService() *MangaFoxService { md := CreateDefaultMangeD...
// Copyright (C) 2017 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 t...
package main import ( "github.com/kataras/iris" //"github.com/kataras/iris/middleware/logger" //"github.com/kataras/iris/middleware/recover" "iris_test/router" "iris_test/config" ) func main() { app := iris.New() //app.Use(recover.New()) //app.Use(logger.New()) //设置视图目录 app.RegisterView(iris.HTML("./views"...
package debug import ( "fmt" "testing" ) func TestNewContext(t *testing.T) { callerContext := CallerStackTrace() closureContext := ClosureStackTrace(func() { fmt.Println(callerContext) }) fmt.Println(callerContext) fmt.Println(closureContext) }
package main import "fmt" func main() { fmt.Println("hello") var input string fmt.Scanf("%s", &input) fmt.Printf("%s\n", input) }
/* * Copyright 1999-2020 Alibaba Group Holding Ltd. * * 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 applicab...
package main import ( "encoding/json" "fmt" "log" "net/http" ) type config struct { App string `json:"app,omitempty"` } type appPostData struct { Name string `json:"name"` Command string `json:"command"` Repository string `json:"repository"` Folder string `json:"folder"` Variables ...
package stack import ( "github.com/stretchr/testify/assert" "testing" ) func TestStack(t *testing.T) { stk := New() for i := 0; i < 2; i++ { stk.Push(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) assert.Equal(t, 10, stk.Length()) val := stk.Peek() assert.Equal(t, val, 10) assert.False(t, stk.IsEmpty()) assert.Equal(...
package release type ReleaseMsgCode int const ( ReleasePending ReleaseMsgCode = 1000 ReleaseInstallFailed ReleaseMsgCode = 1001 ReleaseUpgradeFailed ReleaseMsgCode = 1002 ReleaseDeleteFailed ReleaseMsgCode = 1003 ReleasePauseOrRecoverFailed ReleaseMsgCode = 1004 ReleaseFailed ...
// // linkedlist.go // Copyright (C) 2021 forseason <me@forseason.vip> // // Distributed under terms of the MIT license. // // This package provides an implement of linkedlist. package linkedlist import ( "github.com/forseason/gossl/linkedlist/node" ) // Defination of struct Linkedlist. type LinkedList struct { he...
package main import ( "fmt" "strings" // "strconv" "encoding/json" ) type Payload struct { JobId int `json:"id"` Number int `json:"number"` Content string `json:"log"` Final bool `json:"final"` UUID string `json:"uuid"` } type LogPartsProcessor struct { db ...
package main import ( "fmt" "os/exec" "github.com/brewlin/net-protocol/config" "github.com/brewlin/net-protocol/protocol/link/tuntap" "github.com/brewlin/net-protocol/protocol/network/ipv4" ) func main() { //未配置, 则自动随机获取网卡ipv4地址 firstIp, firstNic := ipv4.InternalInterfaces() if config.HardwardIp == "" { c...
// Package pushwoosh provides functions and structs for accessing the Pushwoosh Remote API. package pushwoosh import ( "bytes" "context" "encoding/json" "errors" "net/http" "net/url" "path" "time" ) const ( apiV13 = "1.3" defaultHTTPTimeout = 120 * time.Second ) var ( httpClient = &http.Client...
package cache import ( "bytes" "errors" "strconv" "time" "github.com/peterbourgon/diskv" ) // Cache struct type Cache struct { storage *diskv.Diskv storageDir string } // New returns an initialized Cache instance func New(storageDir string) *Cache { c := new(Cache) c.storageDir = storageDir c.initCac...
package connector_test import ( "context" "testing" "time" "github.com/mylxsw/adanos-alert/pkg/connector" "github.com/stretchr/testify/assert" ) func TestSend(t *testing.T) { ctx, _ := context.WithTimeout(context.TODO(), 1*time.Second) assert.NoError(t, connector.NewConnector("", "http://localhost:19999").Sen...
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package arc import ( "context" "time" "chromiumos/tast/ctxutil" "chromiumos/tast/errors" "chromiumos/tast/local/arc" "chromiumos/tast/local/bundles/cros/arc/arcpipvid...
package vault const ( SecretSyncTargetNamepaceKey = "secretsync/target-namespace" SecretSyncTargetNameKey = "secretsync/target-name" SecretSyncTargetClusterKey = "secretsync/target-clusters" // VaultSourceKey is the key in the resulting kubernetes secret // that holds the vault path from which the user secr...
// main logic package generator import ( "log" "github.com/slonegd/structstringer/internal/declaration" "github.com/slonegd/structstringer/internal/extractor" "github.com/slonegd/structstringer/internal/packinfo" "github.com/slonegd/structstringer/internal/printer" "github.com/slonegd/structstringer/internal/sa...
package main func countStat(data string) (map[rune]uint64, uint64) { res := make(map[rune]uint64) tot := uint64(0) spli := []rune(data) for _, c := range spli { res[c]++ } for _, j := range res { tot += j } return res, tot } func genStat(data string) map[rune]float64 { stats, tot := countStat(data) res ...
package Utils import "fmt" // ArrayTools // @author liujun // @version 1.0 // @date 2020-02-11 15:11 // @author-Email ljfirst@mail.ustc.edu.cn // @description 数组工具类 // <p> // 1、判断相等 (不相等则打印) // 判断两个int[] 是否相等 : {@link ArrayUtilsImpl#IntArrayEquals} // 判断两个int[][] 是否相等 : {@link ArrayUtilsImpl#IntMatrixEquals} // ...
package pipeline import "spider/core/data" // 被用来处理条目的函数类型。 type ProcessItem func(item data.Item) (result data.Item, err error)
// Copyright (c) 2016-2019 Uber Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
package models import ( "fmt" "github.com/jinzhu/gorm" "xpool/database" ) // State 1 待审核 3 审核通过 5 审核拒绝 type LoanMining struct { gorm.Model State int Email string Loan float64 Reason string Deposit float64 UpdateUser uint } type LoanMiningLog struct { gorm.Model State int ...
// Write a program that is given a list of file names as arguments then prints // the sha256 sum for the contents of each file. Print the hashes as a hex string. package main import ( //"strings" "crypto/sha256" "fmt" "github.com/pkg/errors" "io/ioutil" "os" ) func main() { argsWithoutProg := os.Args[1:] var...
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package faillog provides helper functions for dumping UI data on test failures. package faillog import ( "context" "fmt" "os" "path/filepath" "strings" "chromiumos...
package util import ( "bufio" crypto_rand "crypto/rand" "flag" "fmt" "io" "math/big" math_rand "math/rand" "os" "time" ) var Login_info = make([]string, 0, 1000000) var TelFile string func init() { var loginFile string flag.StringVar(&loginFile, "loginfile", "data/login_info.txt", "login info file") flag....
// Copyright 2020 Comcast Cable Communications Management, LLC // // 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 ...
// Copyright 2019 - 2022 The Samply Community // // 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 ...
package tools import ( "errors" "net/url" "regexp" "strconv" "strings" ) //去除html标签 func TrimHtml(src string) string { //将HTML标签全转换成小写 re, _ := regexp.Compile("\\<[\\S\\s]+?\\>") src = re.ReplaceAllStringFunc(src, strings.ToLower) //去除STYLE re, _ = regexp.Compile("\\<style[\\S\\s]+?\\</style\\>") src = re....
// Copyright 2018 The gVisor 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 agree...
// SPDX-License-Identifier: MIT package protocol import ( "testing" "github.com/issue9/assert/v3" "github.com/caixw/apidoc/v7/core" ) func TestDidChangeTextDocumentParams_Blocks(t *testing.T) { a := assert.New(t, false) p := &DidChangeTextDocumentParams{} a.Empty(p.Blocks()) p = &DidChangeTextDocumentPara...
package avl import ( "testing" ) func TestStack(t *testing.T) { s := &Stack{} s.Push(&Node{Value: 11}) s.Push(&Node{Value: 15}) if v, _ := s.Pop(); v.Value != 15 { t.Errorf("s.Pop() should be %d, got: %d", 15, v.Value) } if v, _ := s.Peek(); v.Value != 11 { t.Errorf("s.Peek() should be %d, got: %d", 11,...
package rod import ( "reflect" "github.com/go-rod/rod/lib/proto" ) type stateKey struct { browserContextID proto.BrowserBrowserContextID sessionID proto.TargetSessionID methodName string } func (b *Browser) key(sessionID proto.TargetSessionID, methodName string) stateKey { return stateKey{ brow...
// Modify the `.shiftstatus` dotfile. package models import ( "bufio" "errors" "fmt" "os" "strings" "time" "github.com/JosephLai241/shift/utils" "github.com/fatih/color" "github.com/spf13/viper" ) var cwd = utils.GetCWD() var DotfileName = fmt.Sprintf("%s/.%s", cwd, "shiftstatus") // Format the string tha...
package main import ( "time" "fmt" ) /* You are given the following information, but you may prefer to do some research for yourself. 1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty...
package main import ( influxdb2 "github.com/influxdata/influxdb-client-go" "github.com/influxdata/influxdb-client-go/api" "github.com/influxdata/influxdb-client-go/api/write" "github.com/peterhellberg/ruuvitag" ) var dbClient influxdb2.Client var writeAPI api.WriteAPI func connectToInflux() { dbClient = influxd...
package volvo import ( "strings" "time" ) const ApiURI = "https://vocapi.wirelesscar.net/customerapi/rest/v3.0" type AccountResponse struct { ErrorLabel string `json:"errorLabel"` ErrorDescription string `json:"errorDescription"` FirstName string `json:"firstName"` LastName string ...
// Copyright 2018 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package config import ( "testing" ) func TestNewApiConfig(t *testing.T) { if NewApiConfig() == nil { t.Error("Failed to create config") } } func TestConfigValidate(t *testing.T) { config := NewApiConfig() err := config.Validate() if err == nil { t.Fatal("Expected config validation to fail") } if cve, o...
package main import ( "crypto/tls" "fmt" "io/ioutil" "net/http" "strconv" "strings" "time" ) func main() { /* var payloads = [...]string{"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9","!","@","#","$","%","^","&...
package main import ( "encoding/json" "flag" "fmt" "github.com/fiorix/go-redis/redis" "github.com/gdamore/mangos" "github.com/gdamore/mangos/protocol/rep" "github.com/gdamore/mangos/transport/ipc" "github.com/gdamore/mangos/transport/tcp" "github.com/ugorji/go/codec" "net/url" "reflect" "strconv" "strings...
package exchange import ( "fmt" "gopkg.in/yaml.v3" "strings" ) type CoinType byte const ( NoCoin CoinType = iota USD // Fiat BTC // Bitcoin ETH // Ethereum XRP // Ripple LTC // Litecoin BCH // Bitcoin Cash BNB // Binance C...
/* * @lc app=leetcode id=744 lang=golang * * [744] Find Smallest Letter Greater Than Target * * https://leetcode.com/problems/find-smallest-letter-greater-than-target/description/ * * algorithms * Easy (45.23%) * Likes: 394 * Dislikes: 507 * Total Accepted: 74.1K * Total Submissions: 163.5K * Testcas...
// Copyright (C) 2019-2020 Zilliz. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable l...
package main import ( "strconv" "github.com/Galdoba/utils" ) func (w *World) generateFleetPolicy() { desidionPool, _ := generateDesidionPool(7, "Civilian Ships", "Military Ships", "Stations") w.FleetPolicy = desidionPool } func shipYerlyBP(key string) int { sshipCost := make(map[string]int) sshipCost["Fighter...
package a import ( "fmt" "math/rand" "bytes" "time" "designPattern/AAG_prototype/a/adv" "sync" ) var MAXCOUNT = 6 func SendMail(m *adv.Mail) { fmt.Println("title: ", m.GetSubject(), "receiver: ", m.GetReceiver(), "...send successfully.") } func GetRandString(length int) string { s := "abcdefghhigklmnopqrstu...
package utils import ( "testing" "github.com/stretchr/testify/assert" ) func TestDoubleMapBoolSet(t *testing.T) { v := make(DoubleMapBool) assert.Nil(t, v["foo"]) assert.False(t, v["foo"]["bar"]) assert.Nil(t, v["foo"]) v.Set("foo", "bar", true) assert.NotNil(t, v["foo"]) assert.True(t, v["foo"]["bar"]) }
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. // package aws import ( "sync" "testing" "github.com/aws/aws-sdk-go-v2/aws" ec2Types "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/golang/mock/gomock" testlib "github.com/mattermost/m...
package printing import ( "fmt" "io" "os" "strings" "github.com/stephens2424/php/ast" ) // Walker is a walker implementation type Walker struct { tabLevel int ast.DefaultWalker W io.Writer } // NewWalker returns a new Walker func NewWalker() *Walker { return &Walker{W: os.Stdout} } func (w *Walker) Walk(n...
package main import ( "fmt" "testing" ) func TestShellSort(t *testing.T) { list := []int{2, 6, 8, 1, 9, 0, 3, 4, 7, 5} ShellSort(list) for i := 0; i < len(list); i++ { fmt.Println(list[i]) } } func ShellSort(list []int) { length := len(list) if length < 2 { return } for step := length / 2; step > 0; st...
package config import ( log2 "asyncMessageSystem/app/middleware/log" "fmt" "github.com/spf13/viper" "path/filepath" "time" ) type Config struct { Web Web Mysql Mysql Xorm Xorm RabbitMq RabbitMq Redis Redis } type Web struct { Debug bool ServerAddr string ReadTimeout time.Duration WriteTimeout time.Dura...
package main import ( "crypto/sha256" "encoding/json" "fmt" "github.com/gorilla/mux" "github.com/fatih/color" "io/ioutil" "log" "net/http" "net/http/httputil" "reflect" "sort" "strconv" ) const port string = ":8000" // Configurable localhost port type validData struct { DataHashOne string `json:"DataHas...
package getip import ( "errors" "io/ioutil" "log" "net/http" "strconv" "strings" "github.com/PuerkitoBio/goquery" "github.com/axgle/mahonia" "github.com/go-clog/clog" ) // ... func GetIP3306PaginationURL() []string { urlPath := "http://www.ip3366.net/free/?stype=1&page=1" resp, err := http.Get(urlPath) i...
/* * Copyright IBM Corporation 2021 * * 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 o...
package linkedlist import "testing" type ListNode struct { Val int Next *ListNode } // 递归解法 func mergeTwoListsRecursive(l1 *ListNode, l2 *ListNode) *ListNode { if l1 == nil { return l2 } if l2 == nil { return l1 } if l1.Val < l2.Val { l1.Next = mergeTwoLists(l1.Next, l2) return l1 } else { l2.Next...
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package loginapi import ( "context" "chromiumos/tast/common/fixture" "chromiumos/tast/common/policy" "chromiumos/tast/common/policy/fakedms" "chromiumos/tast/local/chr...
package main import ( "errors" "fmt" "strconv" ) type Stack struct { //最大存放的个数 MaxTop int //栈顶 Top int //模拟栈 arr [20]int } func (s *Stack) Push(val int) (err error) { if s.Top == s.MaxTop-1 { fmt.Println("stack full") return errors.New("stack full") } s.Top++ s.arr[s.Top] = val return } func (s...
package restapi import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" "path" "strings" "github.com/PhilippHeuer/in-toto-golang/in_toto/slsa_provenance/v1.0" "github.com/cidverse/cid/pkg/core/provenance" "github.com/cidverse/cid/pkg/core/state" "github.com/cidverse/cidverseutils/pkg/encoding" "githu...
package fibonacci_number import ( "testing" "github.com/stretchr/testify/assert" ) func Test_fib(t *testing.T) { tests := []struct { n int want int }{ { n: 2, want: 1, }, { n: 3, want: 2, }, { n: 4, want: 3, }, { n: 30, want: 832040, }, } for _, tt := range tests { t.Run(""...
package conversion import ( "fmt" "os" "log" "path/filepath" "image" _ "image/jpeg" "image/png" ) func assert(err error ,msg string){ if err != nil { // エラー時の処理 println(msg) log.Fatal(err) } } func Convert(srcPath string, output_fmt string){ //画像のフォーマットによって変換方法を変える //ファイル読み込み // ファイルオープン file, e...
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package portlist import ( "encoding/json" "testing" ) func TestParsePort(t *testing.T) { type InOut struct { in string expect int } t...
package apiversion import "context" type key int const contextKey key = 0 func NewContext(ctx context.Context, ver *Version) context.Context { return context.WithValue(ctx, contextKey, ver) } func FromContext(ctx context.Context) *Version { return ctx.Value(contextKey).(*Version) }
package starlarkfn_test import ( "testing" "github.com/golang/mock/gomock" "github.com/raba-jp/primus/pkg/operations/fish/handlers" mock_handlers "github.com/raba-jp/primus/pkg/operations/fish/handlers/mock" "github.com/raba-jp/primus/pkg/operations/fish/starlarkfn" "github.com/raba-jp/primus/pkg/starlark" "go...
/* Copyright 2015 All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, soft...
package image import ( "bufio" "fmt" "io" "io/ioutil" "net/http" "os" "github.com/jedib0t/go-pretty/v6/table" "github.com/michaelhenkel/gokvm/qemu" log "github.com/sirupsen/logrus" libvirt "libvirt.org/libvirt-go" libvirtxml "libvirt.org/libvirt-go-xml" ) type ImageLocationType string const ( URL Imag...
package main import ( "github.com/gin-gonic/gin" "net/http" ) func main() { engine := gin.Default() engine.GET("/test", func(context *gin.Context) { // get params firstName := context.Query("first_name") lastName := context.DefaultQuery("last_name", "libing") //output params context.String(http.Status...
package repositories //第一步,先开发对应的接口 //第二步,实现接口 import ( "database/sql" "fmt" "github.com/gomodule/redigo/redis" mysql2 "homework/common/mysql" redis2 "homework/common/redis" "homework/common/reflect" "homework/models/datamodels" "strconv" ) //第一步,先开发对应的接口 //第二步,实现定义的接口 type IProduct interface { //连接数据 Conn(...
package cmd import ( "encoding/json" "fmt" "github.com/spf13/cobra" "io/ioutil" "log" "strings" erp_clients "update-customer-image/erp-clients" ) func attachFileToCustomer(fileURL, customerName string) error { if !strings.Contains(fileURL, "private"){ return fmt.Errorf("file not private") } fileDetail, e...
package app import ( "github.com/life-assistant-go/article" "github.com/life-assistant-go/fund" "github.com/life-assistant-go/tag" "github.com/life-assistant-go/utils" ) // DBTable create table func DBTable() { // fund table if utils.DB.HasTable(&fund.Fund{}) { utils.DB.AutoMigrate(&fund.Fund{}) } else { u...