text
stringlengths
11
4.05M
package models type Input struct { Arguments interface{} `json:"arguments"` Files interface{} `json:"files"` }
package missingNumber func missingNumber(nums []int) int { var sum uint64 max := 0 exist_zero := false for _, v := range nums { sum += uint64(v) if v > max { max = v } if v == 0 { exist_zero = true } } value := max should := 0 if max%2 != 0 { should = max max-- } should += (max + 1) * (ma...
package statemachine import ( "github.com/stretchr/testify/assert" "testing" ) func TestNewTransition(t *testing.T) { state1 := NewState("State1") state2 := NewState("State2") transition := NewTransition(state1, state2) assert.Equal(t, transition.From, state1) assert.Equal(t, transition.To, state2) }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package cmd import ( "testing" "github.com/pkg/errors" "github.com/spf13/cobra" ) func TestNewUpdateCmd(t *testing.T) { command := newUpdateCmd() if command.Use != updateName || command.Short != updateShortDescripti...
package easypost func getCarrierAccountTypesWithCustomWorkflows() []string { return []string{"FedexAccount", "UpsAccount"} } var ApiDidNotReturnErrorDetails = "API did not return error details" var ApiErrorDetailsParsingError = "RESPONSE.PARSE_ERROR" var InvalidParameter = "Invalid parameter: " var JsonDeserializati...
package stun import ( "math/rand" "testing" ) func TestXORSafe(t *testing.T) { dst := make([]byte, 8) a := []byte{1, 2, 3, 4, 5, 6, 7, 8} b := []byte{8, 7, 7, 6, 6, 3, 4, 1} safeXORBytes(dst, a, b) safeXORBytes(dst, dst, a) for i, v := range dst { if b[i] != v { t.Error(b[i], "!=", v) } } } func Test...
// This must be package main package main import ( "fmt" linters "github.com/golangci/example-linter" "golang.org/x/tools/go/analysis" ) func New(conf any) ([]*analysis.Analyzer, error) { // TODO: This must be implemented fmt.Printf("My configuration (%[1]T): %#[1]v\n", conf) // The configuration type will b...
package stack import ( "fmt" "sync" "testing" "github.com/stretchr/testify/require" ) func TestStack(t *testing.T) { for idx, s := range []Stack{ &SliceStack{}, &LinkStack{}, } { t.Run(fmt.Sprintf("Stack#%d", idx), func(t *testing.T) { assert := require.New(t) assert.True(s.IsEmpty()) assert.Nil...
package script //String is a unicode string. type String struct { Type } func (a String) Join(b String) String { return a.Ctx.Language.Join(a, b) } //StringFromCtx implements AnyString. func (a String) StringFromCtx(AnyCtx) String { return a } //AnyString needs to return a String from this package. type AnyStrin...
package vo type TTodayDetailVO struct { //引入父级属性 TBaseVO DataList []SuggStubDetailVO }
/* ================== Arrays ============ 1. creating array is simple ===== declaration of array ========== anArray := [8]int array[0] := 9 for i:= 0 ; i < len(array) ; i++ { array[i] = len-1 } anArray := [4]int{1, 2, 3, 4} ============Multi Dimensional Array =========== twoD := [4][4]int{{1,2,3,4}, {1,2,3,4}} threeD...
package reporter import ( "bytes" "compress/gzip" "errors" "net/http" "net/url" "time" ) type Reporter interface { Report(reportPath string, buffer *bytes.Buffer) error ReportWithQueries(reportPath string, buffer *bytes.Buffer, queries map[string]string) (bool, error) } type HTTPReporter struct { httpClient...
package main import ( "encoding/json" "fmt" "os" "github.com/rahulkj/app-info/cmd" "code.cloudfoundry.org/cli/plugin" ) // AppInfo represents Buildpack Usage CLI interface type AppInfo struct{} // GetMetadata provides the Cloud Foundry CLI with metadata to provide user about how to use buildpack-usage command...
package main import ( "fmt" "strconv" ) type Wallet struct { Cash int } func (w *Wallet) Pay(amount int) error { if w.Cash < amount { return fmt.Errorf("Not enough money") } w.Cash -= amount return nil } func (w *Wallet) String() string { return "This wallet has " + strconv.Itoa...
package subrouter import ( "apimocker/host" "apimocker/mock" "encoding/json" "fmt" "io/ioutil" "log" "net/http" "strconv" "github.com/julienschmidt/httprouter" ) // AddHostsSubRouter adds handlers to the sub paths for "hosts" func AddHostsSubRouter(pathPrefix string, r *httprouter.Router) { path := "host" ...
package 排列组合问题 import "sort" // 回溯 + 外部变量 解决求数组组合问题 (数组中元素有重复且大于0, 不可重复选取) var combinationSequence [][]int func combinationSum2(candidates []int, target int) [][]int { combinationSequence = make([][]int, 0, 5) // 需要执行排序 // 目的是 防止这种情况: [1 7 1], target == 8时, 如果没排序,那么结果会有 [1 7] 和 [7 1]。(原因是7后又出现了1) // 如果执行了排序,那么数组...
// Licensed to Elasticsearch B.V. under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Elasticsearch B.V. licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use ...
package main import ( "encoding/json" "flag" "io" "log" "net/http" "strconv" "time" _ "net/http/pprof" "github.com/xDarkicex/playserver/neuron" "github.com/xDarkicex/playserver/render" "github.com/xDarkicex/playserver/server" "golang.org/x/net/websocket" ) var httpAddr = flag.String("http", ":8080", "Li...
package jsonv import ( "fmt" "regexp" ) type StringValidator interface { ValidateString(s string) error } type BytesValidator interface { ValidateBytes(b []byte) error } type StringValidatorFunc func(s string) error func (f StringValidatorFunc) ValidateString(s string) error { return f(s) } type BytesValidat...
// Copyright 2020-present Open Networking Foundation. // // 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 main import f "fmt" func main() { f.Println("지연 호출") name() array := []int{1, 2, 3, 4, 5} for _, value := range array { defer f.Println(value) } } func name() { defer func() { f.Println("lee") }() func() { f.Println("seongwon") }() }
package main import "fmt" /** * created: 2019/5/8 9:32 * By Will Fan */ func main() { var a uint8 = 0x82 var b uint8 = 0x02 fmt.Printf("%08b [A]\n", a) fmt.Printf("%08b [B]\n", b) fmt.Printf("%08b (NOT B)\n", ^b) fmt.Printf("%08b ^ %08b = %08b [B XOR 0xff]\n",b,0xff,b ^ 0xff) fmt.Printf("%08b ^ %08b = %08...
package tyme_test import ( "fmt" "time" "github.com/seiyab/tyme" ) func ExampleLocalYear() { year := tyme.NewLocalYear(2006) fmt.Println(year) // Output: // 2006 } func ExampleLocalMonth() { month := tyme.NewLocalMonth(2006, time.January) fmt.Println(month) // Output: // 2006-01 } func ExampleLocalDat...
package server import ( "encoding/json" "net/http" "net/http/httptest" "testing" restful "github.com/emicklei/go-restful" "github.com/stretchr/testify/suite" "go-gcs/src/config" "go-gcs/src/entity" "go-gcs/src/service" ) type PreviewSuite struct { suite.Suite wc *restful.Container sp *service.Container }...
package service import ( "strconv" "github.com/godbus/dbus" "github.com/muka/go-bluetooth/bluez" "github.com/muka/go-bluetooth/bluez/profile/gatt" ) //CreateService create a new GattService1 instance func (app *Application) CreateService(props *gatt.GattService1Properties, advertisedOptional ...bool) (*GattServi...
package btx import ( "bytes" "encoding/binary" "testing" "time" "cloud.google.com/go/bigtable" ) func TestNewRowMutation(t *testing.T) { src := A{ TString: "hello", TBool: false, TFloat32: 3.14, TRowKey: "rk", } bmu, err := NewRowMutation(&src, time.Now()) if err != nil { t.Fatalf("failed tes...
package common import ( "bytes" "compress/gzip" "fmt" "os" "strings" "syscall" "time" log "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" ) const ( containerShimPrefix = "://" ) // killGracePeriod is the time in seconds after sending SIGTERM before // forcefully killing the sidecar with SIGKILL (valu...
package plugins var EnabledPlugins = map[string]Creator{} type Creator func(config map[string]string) Plugin func Add(name string, creator Creator) { EnabledPlugins[name] = creator } type Plugin interface { // Description returns a one-sentence description on the Input Description() string Start() string End()...
package toolsutils import ( "fmt" "testing" ) func TestListDir(t *testing.T) { files, err := ListDir("e:\\goproject\\src\\github.com\\colefan\\gsgo\\gameprotocol", ".xml") if err != nil { fmt.Println("ListDir err,", err) } fmt.Println("ListDir,files:", files) } func TestWalkDir(t *testing.T) { files, err :=...
package problems func canJump(nums []int) bool { var maxIdx int lastIdx := len(nums) - 1 for idx, gap := range nums { if d := idx + gap; d > maxIdx { maxIdx = d } if idx >= maxIdx { break } if maxIdx >= lastIdx { return true } } return maxIdx >= lastIdx }
/***************************************************************** * Copyright©,2020-2022, email: 279197148@qq.com * Version: 1.0.0 * @Author: yangtxiang * @Date: 2020-07-21 15:04 * Description: *****************************************************************/ package xthrift import ( "errors" "github.com/apache/t...
package model import "github.com/jinlicode/jinli-panel/model/request" func InitDb() { db.AutoMigrate( &request.Database{}, &request.Task{}, &request.Site{}, &request.Domain{}, &request.User{}, &Config{}, ) }
package main import ( "fmt" "github.com/zmb3/spotify" "log" ) type Track struct { Name string ID spotify.ID AddedAt string } type Playlist struct { Name string ID spotify.ID } type TopArtist string type UserMusic struct { Playlists []Playlist TopArtists []TopArtist Tracks []Track } func ...
package events import ( "encoding/json" ) type ( // UserEvent represents the user related segment of an Event within Ion Channel. // Action is the specific type of User Event that occurred, // Data is information relevant to the type of event, defined by one of the other structs in this file. UserEvent struct { ...
package defragmentation import ( "fmt" "testing" "github.com/stretchr/testify/require" ) func TestCountUsedSquares(t *testing.T) { type args struct { key string } tests := []struct { name string args args want int64 }{ {"", args{"flqrgnkx"}, 8108}, {"", args{"stpzcrnm"}, 8250}, } for _, tt := ra...
// Copyright (c) 2013, Sean Treadway, SoundCloud Ltd. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Source code and contact info at http://github.com/streadway/zk package main import ( "fmt" "os" "strings" "text/scanner" ) func emit(format string, args...
package memberAdminControllers import ( "web/ant/controllers" "web/apps/configs" "web/apps/modules/member/models" "web/apps/modules/member/services" ) type IndexController struct { controllers.Controller } /** * 会员列表 */ func (this IndexController) MemberAdminIndex(condition map[string]string) (members string,...
package room import ( "fmt" "log" "net/http" "net/rpc" "time" ) type HttpApi struct { } var client *rpc.Client var err error func StartApiServer(address string) { client, err = rpc.Dial("tcp", address) if err != nil { log.Fatal(err) } go Ping() http.HandleFunc("/new_room", NewRoom) http.HandleFunc("/d...
package core import ( "encoding/binary" "encoding/json" "flag" "fmt" "goim/libs/bytes" "io" "math/rand" "net" "net/http" "strconv" ) const ( // 订阅所有cmd事件时使用 BILIBILI_CMD_All string = "" // 直播开始 BILIBILI_CMD_Live string = "LIVE" // 直播准备中 BILIBILI_CMD_Preparing string = "PREPARING" // 弹幕消息 BILIBILI_CM...
package locker import ( "context" "math" "math/rand" "os" "testing" "time" ) const ( defaultPostgresLockWaitTime = 5 * time.Second ) func TestPostgresPreemptiveLocker(t *testing.T) { if os.Getenv("POSTGRES_ALREADY_RUNNING") == "" { t.Skip() } ttc := &testTableCoordinator{} err := ttc.setup() if err !=...
package bench import ( "math/rand" "github.com/shenwei356/bio/seq" ) var benchSeqs []*seq.Seq var bit2base = [4]byte{'A', 'C', 'G', 'T'} func init() { rand.Seed(11) sizes := []int{1 << 10, 1 << 20} // ,10 << 20} benchSeqs = make([]*seq.Seq, len(sizes)) var err error for i, size := range sizes { sequence ...
// vim: ts=4 sts=4 sw=4 package main import ( "fmt" "time" "github.com/ofavre/calcgraph/executor" "github.com/ofavre/calcgraph/nodes" ) ////////// // Main // ////////// func main() { executor := executor.New() obsChan := nodes.GoPrintObs(executor) var v1 nodes.Node = nodes.LoopNode(executor, nodes.NewConsta...
package main import ( "bufio" "bytes" "fmt" "math" "os" "strconv" "strings" ) func main() { s := bufio.NewScanner(os.Stdin) buff := new(bytes.Buffer) max := int(math.Pow(10, 11)) buff.Grow(max) s.Buffer(buff.Bytes(), max) s.Scan() q, _ := strconv.Atoi(s.Text()) answer := make([]int, q) for i := 0; i <...
package tumblr import ( "bytes" "crypto/hmac" "crypto/sha1" "encoding/base64" "fmt" "io/ioutil" "log" "net/http" "net/url" "os" "strings" "time" ) const ( // APIURLBLOG Blog Method API URL. APIURLBLOG = "https://api.tumblr.com/v2/blog/%s" ) // Tumblr struct type Tumblr struct { Token string ...
package models //Request is a struct for received JSON type Request struct { Site []string `json:"site"` SearchText string `json:"searchText"` }
package log import ( "fmt" "io" stdlog "log" "strings" ) const ( Off = iota Trace Debug Info Warn Error Fatal ) type Logger struct { level int logger *stdlog.Logger } var loggers []*Logger var logLevel = Debug func NewLogger(out io.Writer) *Logger { ret := &Logger{level: logLevel, logger: stdlog.Ne...
package main import "fmt" func main(){ //var isfound bool //var name string //var age int //var result float32 /*fmt.Println(name) fmt.Println(age) fmt.Println(result) fmt.Println(isfound) fmt.Println(true && true) fmt.Println(true && false) fmt.Println(true || true) fmt.Println(true || false) fmt.Println(!true) */ ...
package main import ( "crud-product/config" "crud-product/delivery/rest" "crud-product/repository" "crud-product/usecase" "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" "github.com/labstack/echo/v4" echoSwagger "github.com/swaggo/echo-swagger" "log" "net/http" ) // @title Echo Swagger Example API...
package chi import ( // add chi adapter _ "github.com/GoAdminGroup/go-admin/adapter/chi" "github.com/GoAdminGroup/go-admin/modules/config" "github.com/GoAdminGroup/go-admin/modules/language" "github.com/GoAdminGroup/go-admin/plugins/admin/modules/table" // add mysql driver _ "github.com/GoAdminGroup/go-admin/m...
package nmsapi import ( "fmt" "github.com/Centny/gwf/routing/httptest" "github.com/Centny/gwf/util" "github.com/Centny/nms/nmsdb" "github.com/Centny/nms/nmsrc" _ "github.com/Centny/nms/test" "testing" "time" ) func init() { var fcfg = util.NewFcfg3() fcfg.InitWithFilePath("../nms_s.properties") LoadAlias(f...
/* 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 ( "bufio" "fmt" "os" "regexp" "strconv" ) const ( EAST = 0 NORTH = 90 WEST = 180 SOUTH = 270 ) type instruction struct { value int action string } type ship struct { NS, EW int direction int } type waypoint struct { NS, EW int } func newInstruction(line string) *instruction { i ...
/* Copyright (c) 2017 Jason Ish * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions...
package message type ParserInterface struct { } type Parser interface { GetInterfaceId(msg string) string IsSync(msg string) bool GetGID(msg string) string }
package main /* Is it necessary to put the Relay Peer's address in the message? Where else could the receiving peer obtain the relay peer's address from? - from the IP header? - but if a message is received from another peer and it has to be sent to other peers, how can the original address be preserved? */ ...
package server import ( "fmt" "go-gcs/src/entity" "go-gcs/src/googlecloud/storage" "go-gcs/src/net/context" response "go-gcs/src/net/http" ) func createGCSSignedUrlHandler(ctx *context.Context) { sp, req, resp := ctx.ServiceProvider, ctx.Request, ctx.Response userId, ok := req.Attribute("userId").(string) i...
// equal. package main import ( "bytes" "fmt" ) func main() { b := []byte(`hello world`) fmt.Println(bytes.Equal(b, b)) // true bb := []byte(`not`) fmt.Println(bytes.Equal(b, bb)) //false bbb := []byte(`hello world`) fmt.Println(bytes.Equal(b, bbb)) // true }
//Package webapp enables the web-app functionality for the dilletante package webapp import ( "encoding/json" "fmt" "html/template" "log" "net/http" "path/filepath" "strings" "github.com/paulidealiste/ErroneusDilletante/database" ) var dbhand dbaseHandler func init() { fs := http.FileServer(http.Dir("./web...
package main import ( "flag" "github.com/XC-/KaskasDaemon/SSE" "github.com/XC-/KaskasDaemon/ConfigParser" "github.com/XC-/KaskasDaemon/RuuviReader" ) func main() { conf := flag.String("c", "", "Path to the configuration file") flag.Parse() configuration := configparser.GetConfiguration(*conf) var devicesToLi...
package test import ( "utility" ) import "testing" func TestStringUtils(t *testing.T) { t.Run("string array contains", func(t *testing.T) { strArr := []string{"a", "b", "c"} if !utility.StringArrContains(strArr, "a") { t.Errorf("Expected the true got false") } if utility.StringArrContains(strArr, "d") ...
// 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 ag...
package main import ( "fmt" "log" "net/http" "os" "os/exec" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { var args []string args = append(args, "--version") out, err := exec.Command("gdalinfo", args...).CombinedOutput() fmt.Fprintf(w, string(out)) if err != nil { ...
package main import ( "encoding/json" "log" "net/http" "github.com/julienschmidt/httprouter" "github.com/satori/go.uuid" "github.com/yanpozka/checkers/game" "github.com/yanpozka/checkers/store" ) func createGame(w http.ResponseWriter, r *http.Request) { st, isStoreType := r.Context().Value(storeCtxKey).(stor...
package service import ( "strings" "tesou.io/platform/brush-parent/brush-api/common/base" "tesou.io/platform/brush-parent/brush-api/module/odds/pojo" "tesou.io/platform/brush-parent/brush-core/common/base/service/mysql" ) type AsiaHisService struct { mysql.BaseService } func (this *AsiaHisService) Exist(v *pojo...
package values import ( "context" "reflect" "testing" "github.com/giantswarm/apiextensions-application/api/v1alpha1" "github.com/giantswarm/micrologger/microloggertest" "github.com/google/go-cmp/cmp" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" ...
package receive import ( "bufio" "bytes" "errors" "github.com/HNB-ECO/HNB-Blockchain/HNB/logging" "github.com/HNB-ECO/HNB-Blockchain/HNB/p2pNetwork/common" "github.com/HNB-ECO/HNB-Blockchain/HNB/p2pNetwork/message/bean" "net" "time" ) type ConnInfo struct { id uint64 addr string conn net.Conn...
package racaty import ( "encoding/json" "errors" "fmt" "main/utils" ) const ( referer = "https://racaty.net/" uloadUrlRegexStr = `<form id="uploadfile" action="([^"]+)"` ) func getUploadUrl() (string, error) { match, err := utils.FindHtmlSubmatch(referer, uloadUrlRegexStr) if err != ...
package user import ( "time" validation "github.com/go-ozzo/ozzo-validation" ) type User struct { Id string `json:"id"` Username string `json:"username"` Password string `json:"password"` FullName string `json:"full_name"` CreatedAt time.Time `sql:"created_at"` UpdatedAt time.Time `sql:...
package adapter import "github.com/giantswarm/microerror" var emptyAmazonAccountIDError = &microerror.Error{ Kind: "emptyAmazonAccountIDError", } // IsEmptyAmazonAccountID asserts emptyAmazonAccountIDError. func IsEmptyAmazonAccountID(err error) bool { return microerror.Cause(err) == emptyAmazonAccountIDError } v...
package main import ( "bytes" "crypto/sha256" "fmt" "math" "math/big" ) const targetBits = 8 type ProofOfWork struct { block *Block targetBit *big.Int } func NewProofOfWork(block *Block) *ProofOfWork { // 设置64位全1 var IntTarget = big.NewInt(1) //00000000000000000000000000001 //1000000000000000000000000...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-09-16 07:02 # @File : lt_707_Design_Linked_List.go # @Description : # @Attention : */ package v0 /* 实现linkedlist 双向链表解决 */ type MyLinkedList struct { first *LinkedNode last *LinkedNode } type LinkedNode struct { val int next *LinkedNode prev *Link...
/* Copyright 2021 CodeNotary, Inc. 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 i...
// Package models provides models. package models
package 路径和问题 /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func pathSum(root *TreeNode, sum int) [][]int { return getPaths(root, sum, []int{}) } func getPaths(root *TreeNode, remainSum int, curPath []int) [][]int { if root =...
package cntest import ( "fmt" "testing" ) // ContainerTestFn implement your DB tests using this signature type ContainerTestFn func(t *testing.T) // ExecuteWithRunningContainer wraps a test function by creating a db func ExecuteWithRunningContainer(t *testing.T, c *Container, userTestFn ContainerTestFn) { isOk :=...
package arch /** * Datatype to describe the architecture of a simple emulator. */ type Arch interface { LoadGame(filepath string) Run() // Returns when game or user quits. Quit() }
// Copyright ©2012 The bíogo 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 cluster provides interfaces and types for data clustering in ℝⁿ. package cluster // Indices is a list of indexes into a array or slice of Values...
package kafka import ( "encoding/json" "fmt" "time" "github.com/TodoApp2021/gorestreact/pkg/models" "github.com/confluentinc/confluent-kafka-go/kafka" ) type TodoItemsProducer struct { producer *kafka.Producer topic *string } func NewTodoItemsProducer(producer *kafka.Producer) *TodoItemsProducer { topic ...
package semioctet import ( "bytes" "io" "strconv" ) func EncodeSemi(w io.Writer, chunks ...int) (n int64, err error) { digits := toDigits(chunks) var buf bytes.Buffer buf.Grow(len(digits) / 2) i, remain := 0, len(digits) for remain > 1 { buf.WriteByte(digits[i+1]<<4 | digits[i]) i += 2 remain -= 2 } i...
package main import "fmt" //先定义接口 一般以er结尾 根据接口实现功能 type Humaner1 interface { //方法 方法的声明 sayhi() } type student12 struct { name string age int score int } func (s *student12)sayhi() { fmt.Printf("大家好,我是%s,今年%d岁,我的成绩%d分\n",s.name,s.age,s.score) } type teacher12 struct { name string age int s...
package api import ( "errors" "strconv" "strings" "github.com/labstack/echo" "gitlab.wallstcn.com/matrix/xgbkb/business" "gitlab.wallstcn.com/matrix/xgbkb/g" "gitlab.wallstcn.com/matrix/xgbkb/types" ) func ApiListChains(ctx echo.Context) (interface{}, error) { page, _ := strconv.ParseInt(ctx.QueryParam("page...
package main import ( "time" "fmt" ) func main() { //日期格式化输出 now := time.Now() //必须得用这个字符串格式化 fmt.Println(now.Format("2006/01/02 15:04:05")) //统计程序耗时 start := time.Now().UnixNano() test() end := time.Now().UnixNano() fmt.Println("costTime:", (end - start) / 1000000) } func test() { time.Sleep(time.Mi...
package main import ( "os" "fmt" "time" "runtime" ) type ParamStruct struct { n, threads, rounds, warmup_rounds int n_buckets, oversample_stride, n_countblocks int } // func read_cmdline_input(args []string) (int, int, int) { // const expected_args int = 3 // if num_args := len(args) ; num_args != exp...
package main import ( "bytes" "fmt" "log" "os" "path/filepath" "runtime" "syscall" "sort" "strings" ) const ( EventFork = 1 EventVFork = 2 EventClone = 3 EventExec = 4 ) var ignore = []string{ "/tmp", "/proc", } func waitEvent(status syscall.WaitStatus) uint32 { return (uint32(status)>>16) & 0xff ...
/* * Tencent is pleased to support the open source community by making Blueking Container Service available. * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except * in compliance with the License. You may obta...
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func middleNode(head *ListNode) *ListNode { slow,fast:= head,head for (fast!=nil && fast.Next!=nil){ slow=slow.Next fast = fast.Next.Next } return slow }
package main import ( "errors" "fmt" "gopkg.in/src-d/go-git.v4" "io" "log" "os" "regexp" "strings" ) // GistID is an id of a gist. type GistID string var idPattern = regexp.MustCompile("^[0-9a-f]+$") // NewGistID validates id and creates GistID. func NewGistID(id string) (*GistID, error) { if !idPattern.Ma...
package poly_test import ( "math/rand" "testing" "github.com/renproject/secp256k1" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" . "github.com/renproject/shamir/poly" "github.com/renproject/shamir/poly/polyutil" "github.com/renproject/shamir/shamirutil" ) var _ = Describe("Polynomials", func() { va...
package test import ( "testing" // "portal/util" ) func TestIsNumber(t *testing.T) { // list := make([]interface{}, 0) // list = append(list, "1", 12, 2) // if code := util.IsNumberList(list); code != 0 { // t.Error("fail...") // } else { // t.Log("success...") // } }
package action import ( "fmt" ) type FmtPrintAction struct{} func (fpa * FmtPrintAction) TakeAction(msg string){ fmt.Println(msg) }
package portablemmap import ( "fmt" "os" "reflect" "sync" "syscall" "unsafe" ) var handleLock sync.Mutex var handleMap = map[uintptr]syscall.Handle{} func Prefault(mmapedData []byte) { // This is a no-op on Windows. } func Mmap(f *os.File) ([]byte, error) { // Stat the file so we can know its size. We alway...
package sqlite import ( "database/sql" "time" "github.com/Tanibox/tania-core/src/growth/domain" "github.com/Tanibox/tania-core/src/growth/query" "github.com/Tanibox/tania-core/src/growth/storage" "github.com/Tanibox/tania-core/src/helper/paginationhelper" "github.com/gofrs/uuid" ) type CropReadQueryMysql stru...
/* * @lc app=leetcode id=349 lang=golang * * [349] Intersection of Two Arrays */ // @lc code=start func intersection(nums1 []int, nums2 []int) []int { var count = map[int]bool{} var result = []int{} for _, num := range nums1 { count[num] = true } for _, num := range nums2 { if count[num] == true { res...
package main import ( "flag" "fmt" "github.com/danielfmelo/myhttphash/hash/md5" "github.com/danielfmelo/myhttphash/request" "github.com/danielfmelo/myhttphash/worker" ) const defaultMaxParallel = 10 func main() { maxParallelRequests := flag.Int("parallel", defaultMaxParallel, "the number of goroutines that ar...
package controllers import ( "github.com/labstack/echo" ) // Setup sets up all controllers. func Setup(router *echo.Router) { } // vi:syntax=go
package updater import ( "errors" "fmt" "github.com/BukkitAPI-Translation-Group/docsbox/conf" "github.com/BukkitAPI-Translation-Group/docsbox/util" "github.com/BukkitAPI-Translation-Group/docsbox/versions" "github.com/mholt/archiver" "os" "strings" ) var ErrorNotRepository = errors.New("not a git repository")...
package parameters import ( "github.com/gophergala2016/source/core/validator" "github.com/gophergala2016/source/internal/modules/parameters/accesstoken" ) type ( // RootRequest is a based request parameter. RootRequest struct { needAccessToken bool AccessToken accesstoken.AccessToken } ) func (p RootReq...
package vm import ( "fmt" "github.com/iotaledger/hive.go/logger" "github.com/iotaledger/wasp/packages/coretypes" "github.com/iotaledger/wasp/packages/publisher" ) type ContractEventPublisher struct { contractID coretypes.ContractID log *logger.Logger } func NewContractEventPublisher(contractID coretype...
package service import ( "image" "path" "path/filepath" "strings" "time" "github.com/iineva/ipa-server/pkg/uuid" ) type AppInfoType int type AppInfo struct { ID string `json:"id"` Name string `json:"name"` Version string `json:"version"` Identifier string `json:"identif...
package main import "testing" func TestGetJSON(t *testing.T) { jsonString := ` { "foo": "bar" } ` if _, err := getJSON(jsonString); err != nil { t.Errorf(`Expected JSON, got "%v"`, err) } }