text stringlengths 11 4.05M |
|---|
package main
func fact(number int) int {
if number == 0 {
return (1)
}
return number * fact(number-1)
}
func main() {
println(fact(3))
} |
// This file was generated for SObject ProcessDefinition, API Version v43.0 at 2018-07-30 03:47:31.578458672 -0400 EDT m=+17.921737582
package sobjects
import (
"fmt"
"strings"
)
type ProcessDefinition struct {
BaseSObject
CreatedById string `force:",omitempty"`
CreatedDate string `force:",omitempty"`... |
package dbx
import (
"dapan/config"
"dapan/model"
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var DB *gorm.DB
func SetMysqlDB() {
database := config.NewDefaultConf()
con := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=Local", database.User, database.Password, database.Host, database.Port... |
package api
import (
"encoding/json"
"net/http"
"github.com/julienschmidt/httprouter"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/sirupsen/logrus"
)
type API struct {
Version string
ListenAddress string
log *logrus.Entry
}
type ResponseJSON struct {
Status int ... |
package main
import "fmt"
func main() {
//declaring a integer variable x
var x int
x=3 //assigning x the value 3
fmt.Println("x:", x) //prints 3
//declaring a integer variable y with value 20 in a single statement and prints it
var y int=20
fmt.Println("y:", y)
/... |
package main
import (
"context"
"flag"
"fmt"
"log"
"os"
"path/filepath"
"strconv"
"github.com/adhocteam/soapbox/buildinfo"
pb "github.com/adhocteam/soapbox/proto"
"google.golang.org/grpc"
)
func main() {
serverAddr := flag.String("server", "127.0.0.1:9090", "host:port of server")
printVersion := flag.Bo... |
package main
import "fmt"
func main() {
c :=pipe(7,8,56)
res :=square(c)
for r:=range res{
fmt.Println(r)
//fmt.Println(<-res)
//fmt.Println(<-res)
}
}
func pipe(nums ...int) chan int{
c1:=make(chan int)
go func(){
for _,r:=range nums{
c1<-r
}
close(c1)
}()
return c1
}
func squar... |
package main
/* Imports
* 4 utility libraries for formatting, handling bytes, reading and writing JSON, and string manipulation
* 2 specific Hyperledger Fabric specific libraries for Smart Contracts
*/
import (
"bytes"
"encoding/json"
"fmt"
"strconv"
"time"
"github.com/hyperledger/fabric/core/chaincode/shim"... |
package protos
import (
"math"
"testing"
"github.com/qlcchain/go-qlc/common/types"
)
var (
HeaderBlockHash = "D2F6F6A6422000C60C0CB2708B10C8CA664C874EB8501D2E109CB4830EA41D41"
OpenBlockHash = "D2F6F6A6422000C60C0CB2708B10C8CA664C874EB8501D2E109CB4830EA41D47"
)
func TestFrontierReq(t *testing.T) {
address :=... |
package main
import (
"fmt"
)
func main() {
mainloop:
for {
fmt.Println("Menu")
fmt.Println("====")
fmt.Printf("1. Add New Contact\n2. List Contacts\n3. Get Contact by ID\n4. Exit\n\n")
fmt.Print("Your choice: ")
var choice int
fmt.Scanf("%d", &choice)
switch choice {
case 1:
addcontact()
case... |
package ztimer
import (
"log"
"testing"
"time"
)
//定义一个超时函数
func myFunc(v ...interface{}) {
log.Println("No.", v[0].(int), " function called delay ", v[1].(int), " second")
}
//go test -v -run TestTimer
func TestTimer(t *testing.T) {
for i := 0; i < 5; i++ {
go func(i int) {
NewTimerAfter(NewDelayFunc(myFu... |
package lwwset
import (
"errors"
"time"
)
// package lwwset implements the LWWSet (Last Writer Wins Set) CRDT data type along with the functionality
// to append, remove, list & lookup values in a LWWSet. It also provides the functionality to merge multiple
// LWWSets together and a utility function to clear a LWWS... |
package model
import (
"database/sql"
"fmt"
"log"
"os"
_ "github.com/lib/pq"
)
var con *sql.DB
func Connect() *sql.DB {
dbUrl := os.Getenv("DATABASE_URL") ///"postgres://postgres@localhost:5432/test?sslmode=disable"
log.Println("DB_URL: " + dbUrl)
db, err := sql.Open("postgres", dbUrl)
if err != nil {
l... |
package helpers
import (
"encoding/json"
"encoding/xml"
"net/http"
)
func toJson(p interface{}) ([]byte, error) {
b, err := json.MarshalIndent(p, "", "\t")
if err != nil {
return nil, err
}
return b, nil
}
func toXML(p interface{}) ([]byte, error) {
b, err := xml.Marshal(p)
if err != nil {
return nil, e... |
package astutil
import (
"go/ast"
"testing"
)
func TestExprString(t *testing.T) {
exprs, err := Find(astFile, []interface{}{new(ast.Expr)})
if err != nil {
t.Error(err)
}
for _, exp := range exprs {
t.Log(SrcOf(exp), ExprString(exp.(ast.Expr)))
}
}
|
package LinkedList
import "fmt"
type CircularLinkedList struct {
tail *Node
length int
}
func NewCirurcularLinkedList() *CircularLinkedList {
return &CircularLinkedList{length: 0}
}
func (cll *CircularLinkedList) Front() *Node {
return cll.tail.next
}
func (cll *CircularLinkedList) Append(n *Node) {
if cll.... |
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
type password struct {
min int
max int
char rune
pwd []rune
}
// readLines reads a whole file into memory
// and returns a slice of its lines.
func readLines(path string) ([]password, error) {
file, err := os.Open(path)
if err != nil {
re... |
package controller
//
//import (
// "../basic"
// "math"
//)
//
//type face struct {
// p0 *basic.Point
// p1 *basic.Point
// depth float64
//}
//
//func (f *face) detectCollision(p *basic.Point) (*basic.Point, float64) {
// t := p.Sub(f.p0).Dot(f.p1.Sub(f.p0))/(f.p1.Sub(f.p0).Length2())
//
// if t < 0 || t > 1{
// re... |
package p2
import (
"bufio"
"fmt"
"os"
)
func checkIfTree(c rune) int {
if c == '#' {
return 1
}
return 0
}
func walkThroughGrid(grid [][]rune, x int, y int, xLimit int, yLimit int, xMovement int, yMovement int) int {
treesFound := 0
if y >= yLimit {
return treesFound
}
return treesFound + checkIfTree... |
package sheet_logic
import (
"hub/framework"
"hub/sheet_logic/sheet_logic_types"
)
type IntGreater IntComparator
func NewIntGreater(name string) *IntGreater {
tmp := NewIntComparator(
name,
sheet_logic_types.IntGreater,
func(a int64, b int64) bool { return a > b })
return (*IntGreater)(tmp)
}
type FloatGr... |
package swift
import (
corev1 "k8s.io/api/core/v1"
opapi "github.com/openshift/cluster-image-registry-operator/pkg/apis/imageregistry/v1alpha1"
)
type driver struct {
Name string
Namespace string
Config *opapi.ImageRegistryConfigStorageSwift
}
func NewDriver(crname string, crnamespace string, c *opapi.... |
package nsq
import (
"time"
n "github.com/nsqio/go-nsq"
"github.com/raintank/fakemetrics/out"
"github.com/raintank/met"
"gopkg.in/raintank/schema.v1"
"gopkg.in/raintank/schema.v1/msg"
)
const NSQMaxMpubSize = 5 * 1024 * 1024 // nsq errors if more. not sure if can be changed
const NSQMaxMetricPerMsg = 1000 ... |
package checkpoint
import (
"TruckMonitor-Backend/controller/authentication"
"TruckMonitor-Backend/model"
"errors"
"gopkg.in/gin-gonic/gin.v1"
"log"
"net/http"
"strconv"
"time"
)
func (c *controller) CreateFactTimestamp(context *gin.Context) {
checkPointId, err := strconv.Atoi(context.Param("checkpoint"))
i... |
package game
import (
"battleship/game"
"battleship/scoreboard"
"fmt"
"strconv"
"testing"
"github.com/corbym/gocrest/is"
"github.com/corbym/gocrest/then"
)
func TestGetScoreBoardWithOneCellLongShip(t *testing.T) {
// Given one 1 cell long ship
// on a 3x3 grid
ship := game.Ship{1, []game.Cell{}}
grid := g... |
package main
import (
"fmt"
"strings"
)
var s = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
var list = []int{1, 5, 6, 7, 8, 9, 15, 16, 19}
func contains(i []int, e int) bool {
for _, v := range i {
if e == v-1 {
return true
}
}... |
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"path/filepath"
"regexp"
)
var (
reName = regexp.MustCompile(`([a-zA-Z0-9_]+).json`)
)
type FileInfo struct {
Name string
Path string
Route string
}
func fileInfo(filepath string) (FileInfo, error) {
var fi Fil... |
package processor
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestScoreboard(t *testing.T) {
assert.False(t, IsInScoreboard(0, "1234"))
AddToScoreboard(0, "1234")
assert.True(t, IsInScoreboard(0, "1234"))
assert.False(t, IsInScoreboard(1, "1234"))
assert.False(t, IsInScoreboard(0, "5678"))
... |
package main
import (
"github.com/google/uuid"
"time"
)
type User struct {
_id uuid.UUID
name string
email string
password string
}
type Project struct {
_id uuid.UUID
user_id uuid.UUID
name string
dateCompleted time.Time
password string
}
type Task struct {
_id... |
package arb
import (
"finrgo/exhanges"
"testing"
)
type (
ExchangeTest struct {
oneExchange exhanges.IExhanged
exchanges *exhanges.Exchanges
}
)
func NewExhcnageTest() IExchange {
ex := &ExchangeTest{}
// ex.exchanges = exhanges.InitExhanges()
// exchanges.AddExhange(BittrexExchange, &bittrex.Bittrex{})... |
/*
* EVE Swagger Interface
*
* An OpenAPI for EVE Online
*
* OpenAPI spec version: 0.4.1.dev1
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package swagger
// dogma_attribute object
type GetUniverseTypesTypeIdDogmaAttribute struct {
// attribute_id integer
AttributeId int32 `jso... |
package services
// PeriodicSymbols is a map of the symbols of the available metals in the periodic table.
var PeriodicSymbols = map[string]string{
"au": "gold",
"ag": "silver",
"pt": "platinum",
"pd": "palladium",
"cu": "copper",
"rh": "rhodium",
}
|
package quacktorstreams
import "github.com/Azer0s/quacktors"
//NewConsumer creates a new ConsumerActor by a consumer implementation
//and returns both a pointer to the ConsumerActor itself and the PID
//of the consumer. The pointer to the ConsumerActor can be used to subscribe
//to topics of the stream.
func NewConsu... |
package aws
import "github.com/lann/builder"
type Options struct {
AccessKeyId string `config:"id"`
SecretAccessKey string `config:"key"`
DefaultRegion string `config:"region"`
SessionToken string `config:"token"`
}
type optionsBuilder builder.Builder
func (b optionsBuilder) AccessKeyId(value string) o... |
package crawl
import (
"sync"
"sync/atomic"
. "./base"
"./robot"
"./store"
"github.com/golang/glog"
)
func (p *Stock) Days_fix(store store.Store) {
c := Day_collection_name(p.Id)
p.Days.Data, _ = store.LoadTDatas(c, Market_begin_day)
l := len(p.Days.Data)
if l < 1 {
return
}
t := p.Days.Data[0].Time
i... |
package acmt
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document01300101 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:acmt.013.001.01 Document"`
Message *AccountReportRequestV01 `xml:"AcctRptReq"`
}
func (d *Document01300101) AddMessa... |
package main
import (
"fmt"
"time"
)
func main() {
// Classic for loop
for i := 0; i < 10; i++ {
if i == 0 {
continue
}
fmt.Println("Inside classic for loop, value of i is:", i)
}
fmt.Println("\n\n")
// Single condition for loop
j := -20
for j != 0 {
fmt.Println("Inside single condition loop,... |
package gosseract
import (
"errors"
"os"
)
func (o *options) init() *options {
o.UseFile = false
o.FilePath = ""
o.Digest = make(map[string]string)
return o
}
func (s *Servant) OptionWithFile(path string) error {
_, e := os.Open(path)
if e != nil {
return errors.New("No such option file `" + path + "` is f... |
package pkg
import (
"errors"
"testing"
"time"
"github.com/calvinmclean/automated-garden/garden-app/pkg/influxdb"
"github.com/stretchr/testify/mock"
)
func TestHealth(t *testing.T) {
tests := []struct {
name string
lastContactTime time.Time
err error
expectedStatus string
}{
... |
package share
const (
S2C_ERROR = 10000 + iota
S2C_LOGININFO
S2C_LOGINSUCCEED
S2C_ENTERBASEERR
S2C_ROLEINFO
S2C_RPC
)
const (
ERROR_SUCCESS = iota
ERROR_MSG_ILLEGAL
ERROR_NOBASE
ERROR_LOGIN_FAILED //登录失败
ERROR_LOGIN_TRY_MAX //登录失败超过最大次数
ERROR_SYSTEMERROR //系统错误
ERROR_BASE_KEY_EXPI... |
package cart
import (
"context"
"github.com/gingerxman/eel"
m_cart "github.com/gingerxman/ginger-product/models/cart"
)
type CartService struct {
eel.ServiceBase
}
func NewCartService(ctx context.Context) *CartService {
service := new(CartService)
service.Ctx = ctx
return service
}
func (this *CartService)... |
package buildah_test
import (
"context"
"io"
"io/ioutil"
"os"
"testing"
"github.com/werf/werf/pkg/util"
"github.com/werf/werf/pkg/docker"
"github.com/werf/werf/pkg/werf"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/werf/werf/pkg/buildah"
)
func TestBuildah(t *testing.T) {
Registe... |
package main
import (
"fmt"
"testing"
)
func TestIsGm(t *testing.T) {
command1 := "/help"
command2 := "help"
if !IsGm(command1) {
t.Fatal("error1")
}
if IsGm(command2) {
t.Fatal("error2")
}
}
func TestLoadSensitiveWords(t *testing.T) {
strList := LoadSensitiveWords()
if len(strList) != 451 {
t.Fatal(... |
package main
import (
"bufio"
"os"
"fmt"
"io/ioutil"
"path"
"strings"
"os/exec"
"io"
)
const ExtStrs string ="";
var ExtMaps map[string]interface{};
func init(){
GetExtLists()
}
func GetExtLists(){
ExtMaps=make(map[string] interface{})
if(ExtStrs !=""){
list:=strings.Split(ExtStrs,",");
for _,valu... |
package _316_Remove_Duplicate_Letters
import (
"strings"
"testing"
)
type testCase struct {
input string
output string
}
func TestRemoveDuplicateLetters(t *testing.T) {
cases := []testCase{
{
input: "bcabc",
output: "abc",
},
{
input: "cbacdcbc",
output: "acdb",
},
}
for _, c := range c... |
// +build cgo
/* Copyright (c) 2016 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 lis... |
/*
Write the shortest program that will attempt to connect to open ports on a remote computer and check if they are open. (It's called a Port Scanner)
Take input from command line arguments.
your-port-scanner host_ip startPort endPort
Assume, startPort < endPort (and endPort - startPort < 1000)
Output: All the ope... |
package main
type ListNode struct {
Val int
Next *ListNode
}
func mergeKLists(lists []*ListNode) *ListNode {
var res *ListNode
for i := 0; i < len(lists); i++ {
res = merge(res, lists[i])
}
return res
}
func merge(left, right *ListNode) *ListNode {
dummy := new(ListNode)
pre := dummy
for left != nil && ... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//100. Same Tree
//Given two binary trees, write a function to check if they are the same or not.
//Two binary trees are considered the same if they ar... |
package jarviscore
import (
"testing"
)
func TestIsValidNodeName(t *testing.T) {
arrOK := []string{
"zhs007",
"jarviscore",
"jarvis_dt",
"j123_456dt",
}
for _, v := range arrOK {
if !IsValidNodeName(v) {
t.Fatalf("IsValidNodeName(%v): got false", v)
}
}
arrFalse := []string{
"007zhs",
"",
... |
package events
type UserConnected struct {
ClientID int32
Name string
Key string
}
|
// Copyright 2015 The Chromium 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 swarming
import (
"errors"
"net/http"
"strings"
"time"
"github.com/luci/luci-go/client/internal/lhttp"
"github.com/luci/luci-go/client/int... |
package main
import (
"fmt"
)
func isUnique(s string) bool {
if len(s) > 128 {
return false
}
arr := [128]bool{}
for _, j := range s {
v := int(j)
if arr[v] == true {
return false
}
arr[v] = true
}
return true
}
func main() {
s := "abced"
r := isUnique(s)
fmt.Print(r)
}
|
// Copyright (c) 2016, David Url
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bufio"
"errors"
"io"
"math/rand"
"strings"
)
// lookback specifies how many words are used for a prefix.
const lookback = 2
const loopSize = 6
// Suff... |
package common
import (
"strings"
)
type firstPermission struct {
id string `json:"id"`
descrip string `json:"descrip"`
sep string `json:"sep"`
}
func NewFirstP(id, descrip string) *firstPermission {
return &firstPermission{id, descrip, FirstSep}
}
func (p *firstPermission) getDes() string {
return p... |
package main
import (
"fmt"
)
func main(){
mySlice := []int {10,11,12,13,14,15}
mySliceStr := []string {"hendrawan","sueng","maneh"}
fmt.Println(mySlice[0])
for i, v := range mySlice {
fmt.Println(i, v)
}
mySliceStr = append(mySliceStr, "ratih") //ADD DATA
for _,v := range mySliceStr{
... |
/*
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, so... |
package main
import (
"fmt"
"math"
"sort"
)
func main() {
//
//fmt.Println(successfulPairs([]int{
// 15, 8, 19,
//}, []int{
// 38, 36, 23,
//}, 328))
//
//fmt.Println(successfulPairs([]int{
// 5, 1, 3,
//}, []int{
// 1, 2, 3, 4, 5,
//}, 7))
fmt.Println(successfulPairs([]int{
4, 1, 3,
}, []int{
1... |
package main
import (
"flag"
"fmt"
"os/exec"
"regexp"
"strconv"
"strings"
"time"
)
type CmusStatus struct {
status string
artist string
album string
title string
duration int
position int
}
var api_key *string
var api_secret *string
var session_key *strin... |
package githubfetch
import (
"archive/tar"
"compress/gzip"
"context"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"path"
"strings"
"time"
"github.com/docker/docker/builder/dockerignore"
"github.com/docker/docker/pkg/fileutils"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
"gopkg.in... |
package controller
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"text/template"
"github.com/ksw95/GoIndustrialProject/Client/session"
"github.com/labstack/echo"
"github.com/stretchr/testify/assert"
)
var (
// GetDoFunc fetches th... |
package main
import "errors"
var errNotDir = errors.New("Not a directory")
var errNotGoFile = errors.New("Not a go file")
var errNotIsGoTestFile = errors.New("Is a go test file")
var errNotIsNotGoTestFile = errors.New("Is not a go test file")
var errNotImplemented = errors.New("Not implemented")
var errMalFormedFunct... |
package KMP
import (
"testing"
"fmt"
)
func TestCalNext(t *testing.T) {
s := "ababaca"
fmt.Println(calNext(s))
s = "abababa"
fmt.Println(calNext(s))
}
func TestGetNext(t *testing.T) {
s := "ababaca"
fmt.Println(getNext(s))
s = "abababa"
fmt.Println(getNext(s))
}
func TestKMP(... |
// Copyright 2018 The OpenSDS 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 (c) 2016, Ben Morgan. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
package stat
import (
"math"
"testing"
"github.com/stretchr/testify/assert"
)
func TestRunSeries(z *testing.T) {
assert := assert.New(z)
var assertFloat = f... |
package dependencies
import (
"sync"
"testing"
"github.com/Juniper/contrail/pkg/models"
"github.com/stretchr/testify/assert"
)
func TestReturnsRefs(t *testing.T) {
ObjsCache := make(map[string]map[string]interface{})
ObjsCache["virtual_network"] = make(map[string]interface{})
Vn1 := models.VirtualNetwork{}
... |
package main
import "fmt"
var quit chan int
func foo(id int) {
fmt.Println(id)
quit <- id
}
func main() {
count := 100
// quit = make(chan int)
quit = make(chan int, 1000)
for i := 0; i < count; i++ {
go foo(i)
}
for i := 0; i < count; i ++ {
fmt.Printf(">>> %d", <- quit)
}
} |
package camt
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document03000104 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:camt.030.001.04 Document"`
Message *NotificationOfCaseAssignmentV04 `xml:"NtfctnOfCaseAssgnmt"`
}
func (d *D... |
package client
import (
"context"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
k8scontrollerclient "sigs.k8s.io/controller-runtime/pkg/client"
fakecontrollerclient "sigs.k8s.io/controller-runtime/pkg/client/fake"
)
// FakeApplier provides a wrapper around the fake k8s controller client to c... |
package main
import "net/http"
// NewNpkgdServer returns an http.ServeMux that handles all the requests.
func NewNpkgdServer(upstream string) *http.ServeMux {
mux := http.NewServeMux()
proxy := NewUpstreamProxy(upstream)
mux.Handle("/", proxy)
return mux
}
|
package main
import (
"errors"
"regexp"
"strconv"
"strings"
)
// CustomSort is implementation of custom sort logic
type CustomSort struct {
reverse bool
ignoreCase bool
numerical bool
columnNum int
strings []string
}
func (c CustomSort) Len() int {
return len(c.strings)
}
func (c CustomSort) Swap(... |
package order
import (
"context"
"time"
"tpay_backend/merchantapi/internal/common"
"tpay_backend/model"
"tpay_backend/utils"
"tpay_backend/merchantapi/internal/svc"
"tpay_backend/merchantapi/internal/types"
"github.com/tal-tech/go-zero/core/logx"
)
type PayOrderNotifyLogic struct {
logx.Logger
ctx cont... |
package logic
import (
"context"
"github.com/just-coding-0/learn_example/micro_service/zero/rpc/history/internal/svc"
history "github.com/just-coding-0/learn_example/micro_service/zero/rpc/history/pb"
"github.com/tal-tech/go-zero/core/logx"
)
type GetLogic struct {
ctx context.Context
svcCtx *svc.ServiceCo... |
package vote
import "github.com/google/uuid"
type Vote struct {
ID uuid.UUID
Email string
TalkName string `json:"talk_name"`
Score int `json:"score,string"`
}
|
package account
import (
"time"
"github.com/jinzhu/gorm"
"mingchuan.me/api"
)
// NewService - new service
func NewService(db *gorm.DB, secret string) *AccountService {
jwtDuration, _ := time.ParseDuration("24h")
return &AccountService{
DB: db,
Version: AccountServiceVersion,
JWTConfig: &AccountJWTCon... |
package _125_Valid_Palindrome
import "strings"
func isPalindrome(s string) bool {
if len(s) == 0 || len(s) == 1 {
return true
}
var (
i, j = 0, len(s) - 1
)
for i <= j {
if !isWord(s[i]) {
i++
continue
}
if !isWord(s[j]) {
j--
continue
}
if strings.ToLower(string(s[i])) != strings.ToLow... |
// 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... |
/*
* Copyright 2017 StreamSets 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... |
////////////////////////////////////////////////////////////////////////////////
// //
// Copyright 2020 Broadcom. The term Broadcom refers to Broadcom Inc. and/or //
// its subsidiaries. ... |
package main
import (
"encoding/json"
"fmt"
"github.com/hyperledger/fabric-contract-api-go/contractapi"
)
// Read returns the value at id in the world state
func (rc *ResourceTypesContract) Read(ctx contractapi.TransactionContextInterface, id string) (ret *ResourceType, err error) {
resultsIterator, _, err := ct... |
package pg
import (
"github.com/kyleconroy/sqlc/internal/sql/ast"
)
type CollateExpr struct {
Xpr ast.Node
Arg ast.Node
CollOid Oid
Location int
}
func (n *CollateExpr) Pos() int {
return n.Location
}
|
package c2
import (
"fmt"
"x-tool/m"
)
var model m.M
func (mo *model) control() {
var z = m.get("c1")
z.control()
fmt.Print("c2 !")
}
func init() {
m.reject(model)
}
|
//Copyright (c) 2017 Phil
package apollo
import (
"io/ioutil"
"os"
"testing"
"github.com/stretchr/testify/suite"
)
type CacheTestSuite struct {
suite.Suite
}
func (s *CacheTestSuite) TestCache() {
cache := newCache()
cache.set("key", []byte("val"))
val, ok := cache.get("key")
s.True(ok)
s.Equal("val", s... |
package dialect
import (
"github.com/jdkato/prose/tokenize"
"github.com/c9s/inflect"
"regexp"
"strings"
"fmt"
)
// Dialect Detectors must implement a method which returns a corpus and another
// which implements the algorithm which categorizes a product into the
// appropriate dialect
type Detector interfac... |
package controller
import (
"net/http"
"github.com/go-chi/render"
)
type ErrorResponse struct {
Error string `json:"error"`
}
var UnableToParseJsonError = ErrorResponse{
Error: "Unable to parse json",
}
func ErrUnableToParseJson(w http.ResponseWriter, r *http.Request) {
render.Status(r, http.StatusBadRequest)... |
package model
import (
"net/http"
)
type ResponseEntity struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data"`
}
func SuccessResponse(message string, data interface{}) *ResponseEntity {
return &ResponseEntity{
Code: http.StatusOK,
Message: messag... |
package userModel
import (
"bytes"
"encoding/json"
"errors"
)
// User Registered User of Client
type User struct {
// List of client that user registered from
Clients []string `json:"clients,omitempty"`
// The email that user registered with
Email string `json:"email"`
// User's Name
Name string `json:"na... |
package main
import (
"flag"
"fmt"
"os"
)
func main() {
var (
cmd string = "website"
port int = 8000
log int = 1
)
fs := flag.NewFlagSet("default", flag.ExitOnError)
fs.StringVar(&cmd, "cmd", cmd, "the command to run")
fs.IntVar(&port, "p", port, "the port to run on")
fs.IntVar(&log, "l", log, "the ... |
// Copyright 2013 The Go 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 htmlx
import "testing"
type unescapeTest struct {
// A short description of the test case.
desc string
// The HTML text.
html string
// The unesc... |
package main
import (
"bytes"
"flag"
"io"
"net/http"
"sync"
quic "gx/ipfs/QmU44KWVkSHno7sNDTeUcL4FBgxgoidkFuTUyTXWJPXXFJ/quic-go"
"gx/ipfs/QmU44KWVkSHno7sNDTeUcL4FBgxgoidkFuTUyTXWJPXXFJ/quic-go/h2quic"
"gx/ipfs/QmU44KWVkSHno7sNDTeUcL4FBgxgoidkFuTUyTXWJPXXFJ/quic-go/internal/protocol"
"gx/ipfs/QmU44KWVkSHno7s... |
package main
import "fmt"
func main() {
p := person{
name: "James",
lastname: "Bond",
age: 33,
}
fmt.Println("Original:", p)
changeMe(&p, "Jason", "Bourne", 22)
fmt.Println("New:", p)
}
type person struct {
name string
lastname string
age int
}
func changeMe(p *person, name string, l... |
package as_test
import (
"fmt"
"github.com/lunemec/as"
)
func Example() {
for _, n := range []int{127, 128} {
num, err := as.Int8(n)
if err != nil {
fmt.Printf("Input invalid: %d, err: %s\n", num, err)
} else {
fmt.Printf("Input valid: %d\n", num)
}
}
// Output: Input valid: 127
// Input invalid:... |
package tag
import (
"github.com/go-jar/goerror"
"github.com/go-jar/gohttp/query"
"blog/entity"
"blog/errno"
)
func (tc *TagController) ModifyAction(context *TagContext) {
if err := tc.VerifyToken(context.ApiContext); err != nil {
context.ApiData.Err = goerror.New(errno.EUserUnauthorized, err.Error())
retur... |
package db
type Store interface {
Set(key string, value interface{})
Get(key string) interface{}
}
type keyValueStore struct {
store map[string]interface{}
locker RWLocker
}
func newKeyValueStore(locker RWLocker) *keyValueStore {
return &keyValueStore{make(map[string]interface{}), locker}
}
func (ks *keyValue... |
/*
Copyright 2021 The Knative 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, soft... |
package datetime
import (
"encoding/json"
"time"
)
type Date time.Time
func (dt Date) Time() time.Time {
return time.Time(dt)
}
func (dt Date) String() string {
return time.Time(dt).Format("2006-01-02")
}
func (dt *Date) parse(v string) error {
ts, err := time.ParseInLocation("2006-01-02", v, time.Local)
if ... |
package main
import "fmt"
// go 内置函数
func fb() {
defer func() {
err := recover()
fmt.Println(err)
fmt.Println("释放链接数据库")
}()
fmt.Println("b")
panic("出现严重错误!!!")
}
func main() {
fb()
}
|
package defaults
import (
"github.com/openshift/installer/pkg/types/ovirt"
)
// DefaultNetworkName is the default network name to use in a cluster.
const DefaultNetworkName = "ovirtmgmt"
// DefaultControlPlaneAffinityGroupName is the default affinity group name for the control plane VMs.
const DefaultControlPlaneAf... |
package bench
import "sync/atomic"
// AtomicCounter implements an atmoic lock
// using the atomic package
type AtomicCounter struct {
value int64
}
// Add increments the counter
func (c *AtomicCounter) Add(amount int64) {
atomic.AddInt64(&c.value, amount)
}
// Read returns the current counter amount
func (c *Atom... |
package main
import (
"flag"
"fmt"
"log"
"strings"
"github.com/dgryski/go-farm"
"github.com/dgryski/go-shardedkv/choosers/jump"
"github.com/pkg/errors"
)
func buildHostnames(siteCount int) []string {
var hostnames []string
for i := 0; i < siteCount; i++ {
hostnames = append(hostnames, fmt.Sprintf("%d.exam... |
package mongodb
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// Collection is an interface for the subset of *mongo.Collection functions that
// we actually use. Using this interface in our datastores, instead of using the
// *mongo.Collection type directly,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.