text stringlengths 11 4.05M |
|---|
package services
import "github.com/cloudfoundry-incubator/notifications/models"
type PreferenceUpdaterInterface interface {
Execute(models.ConnectionInterface, []models.Preference, string) error
}
type PreferenceUpdater struct {
repo models.UnsubscribesRepoInterface
}
func NewPreferenceUpdater(repo models.... |
package sqrtandcube
import (
"fmt"
"math"
)
//digitPower returns -1 if error
//digit := number % 10
//for power>0 {
// result = digit*result
// power--
//}
//
func digitPowerSum(number int, power int) int {
resultSum := -1
if number > 0 && power > 0 {
resultSum = 0
for number > 0 {
digit := number % 1... |
package raft
import (
"bytes"
"encoding/gob"
"encoding/json"
"fmt"
zmq "github.com/pebbe/zmq4"
"io/ioutil"
"log"
"math/rand"
"os"
"sort"
"strconv"
"time"
)
//type appendEntriesResponse struct{}
//Server interface declares functions that will be used to provide APIs to comminicate with server.
type Serv... |
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan int)
go func() {
for i:=0; i< 3; i++ {
fmt.Printf("Sending value %d to channel\n",i)
ch <- i
time.Sleep(time.Second)
}
}()
for i:=0; i<3;i++ {
val := <-ch
fmt.Printf("Received value %d from channel\n",val)
}
}
|
package artifacts
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/argoproj/argo/persist/sqldb"
wfv1 "... |
package main
import (
"fmt"
cli "gopkg.in/urfave/cli.v2"
"github.com/johnwyles/vrddt-reboot/pkg/config"
"github.com/johnwyles/vrddt-reboot/pkg/reddit"
)
// GetRedditVideoInfo is the command to get simply the data about a Reddit
// video from a Reddit URL
func GetRedditVideoInfo(cfg *config.Config) *cli.Command ... |
package main
import (
"fmt"
"gopkg.in/urfave/cli.v1"
"os"
)
func main() {
app := cli.NewApp()
app.Name = "file-generator"
app.Usage = "File Generation Application"
app.Commands = []cli.Command{
{
Name: "generate", ShortName: "g",
Usage: "Generate files",
Flags: []cli.Flag{
cli.StringFlag{
N... |
/*
Copyright Digital Asset Holdings, LLC 2016 All Rights Reserved.
Copyright IBM Corp. 2017 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/lic... |
package field
import "github.com/graphql-go/graphql"
var args = graphql.FieldConfigArgument{
"name": &graphql.ArgumentConfig{
Type: graphql.String,
DefaultValue: "world",
Description: "Name to say hello",
},
}
func sayHello(p graphql.ResolveParams) (interface{}, error) {
return p.Args["name"], nil
... |
package main
import (
"fmt"
"github.com/d2r2/go-dht"
"io/ioutil"
"log"
)
type DHT11State struct {
temperature float32
humidity float32
}
func ReadDHT11() {
// Read DHT11 sensor data from pin 4, retrying 10 times in case of failure.
temperature, humidity, retried, err :=
dht.ReadDHTxxWithRetry(dht.DHT11... |
package rpc_service
type rpc_chat int
|
package toml_test
import (
"bytes"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
"testing"
"time"
"github.com/BurntSushi/toml"
tomltest "github.com/BurntSushi/toml/internal/toml-test"
)
func BenchmarkDecode(b *testing.B) {
files := make(map[string][]string)
fs.WalkDir(tomltest.EmbeddedTests(), ".", func(... |
package main
import "fmt"
type person struct { //Go’s structs are typed collections of fields. They’re useful for grouping data together to form records.
name string
age int
}
func newPerson(name string) *person { //newPerson constructs a new person struct with the given name
p := person{name: name}
... |
package main
import (
"fmt"
"sync"
"time"
)
// Wait for multiple goroutines to finish, use wait group
func workerW(id int, wg *sync.WaitGroup) { //wait group must be passed to functions by pointer
fmt.Printf("Worker %d starting\n", id)
time.Sleep(time.Second)
fmt.Printf("Worker %d done\n", id)
wg.Done() // n... |
package demofile_test
import (
"testing"
demofile "github.com/MobalyticsGG/csgo-demofile"
)
func TestDemofileOpen(t *testing.T) {
dem, err := demofile.NewDemofile("testdata/demos/cache_9-21_mm.dem", true)
if err != nil {
t.Error(err)
}
err = dem.Start()
if err != nil {
t.Error(err)
}
}
func BenchmarkDe... |
package hot100
// 关键: 有序 代表着双指针
// 推荐解法: https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array-ii/solution/gong-shui-san-xie-guan-yu-shan-chu-you-x-glnq/
// 关键:
func removeDuplicates2(nums []int) int {
var process func(k int) int
process = func(k int) int {
ret := 0
for _, v := range nums {
// ... |
package openinstrument
import (
"code.google.com/p/goprotobuf/proto"
openinstrument_proto "code.google.com/p/open-instrument/proto"
"code.google.com/p/open-instrument/variable"
"errors"
"fmt"
"os"
"sort"
"time"
)
func NewVariableFromString(textvar string) *variable.Variable {
return variable.NewFrom... |
// Copyright 2018 Amazon.com, Inc. or its affiliates. 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. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license"... |
package kafkasource
import (
"fmt"
"log"
"os"
"github.com/lfmexi/tcpgateway/events"
"github.com/confluentinc/confluent-kafka-go/kafka"
)
type kafkaEventsouce struct {
createConsumer CreateKafkaConsumer
producer KafkaProducer
consumersControlChan chan string
}
// CreateKafkaEventSource crea... |
package interfaces
import "server/src/dto"
type UserRepositoryProvider interface {
Create(user *dto.User) error
GetById(id string) (*dto.User, error)
GetByLogin(login string) (*dto.User, error)
GetByEmail(email string) (*dto.User, error)
GetByLoginAndHashedPassword(login string, hashedPassword string) (*dto.User... |
package main
import (
"context"
"time"
"fmt"
)
func main() {
//ctx, cancel := context.WithCancel(context.Background())
var t time.Time;
t=time.Now().Add(5*time.Second);
ctx,_:=context.WithDeadline(context.Background(),t);
//这里不是传地址
go watch(ctx,"【监控1】")
go watch(ctx,"【监控2】")
go watch(ctx,"【监控3】")
time.Sl... |
package txpool
import (
"fmt"
"github.com/HNB-ECO/HNB-Blockchain/HNB/common"
"github.com/HNB-ECO/HNB-Blockchain/HNB/logging"
"github.com/HNB-ECO/HNB-Blockchain/HNB/p2pNetwork"
"github.com/pkg/errors"
//"github.com/HNB-ECO/HNB-Blockchain/HNB/p2pNetwork/message/reqMsg"
//"encoding/json"
"encoding/json"
"github.... |
package main
import (
"encoding/json"
"time"
"github.com/tidusant/chadmin-repo/models"
"gopkg.in/mgo.v2/bson"
)
type Template struct {
ID bson.ObjectId `bson:"_id,omitempty"`
Code string `bson:"code"`
UserID string `bson:"userid"`
Status int ... |
package service
import (
"context"
"fmt"
"io"
"net/http"
"net/url"
"github.com/go-ocf/cloud/cloud2cloud-connector/events"
oapiStore "github.com/go-ocf/cloud/cloud2cloud-connector/store"
"github.com/go-ocf/cloud/cloud2cloud-gateway/store"
"github.com/go-ocf/kit/codec/json"
kitNetGrpc "github.com/go-ocf/kit/n... |
// Package activitystream provides an interface to implement an activitystream.
// Further it contains a default implementation using Redis.
//
// Definition ActivityStream
// An ActivityStream is a list of Activities sorted by time of insertion (LIFO)
//
// By this definition an ActivityStream is a list, not a set. ... |
package main
func combine(n int, k int) [][]int {
res := [][]int{}
cur := []int{}
combination(n, k, 1, cur, &res)
return res
}
func combination(n int, k int, start int, cur []int, res *[][]int) {
if k == len(cur) {
temp := make([]int, len(cur))
copy(temp, cur)
*res = append(*res, temp)
return
}
for i ... |
package script
import "reflect"
func GoTypeOf(value Value) reflect.Type {
return reflect.TypeOf(GoValueOf(value))
}
func GoValueOf(value Value) interface{} {
switch value.(type) {
case Int:
return int(0)
case String:
return string("")
case Bool:
return bool(false)
default:
return nil
}
}
|
package router
import "context"
type Handler interface {
ServeGRPC(ctx context.Context, request interface{}) (context.Context, interface{}, error)
}
type grpcHandler struct {
endpoint Endpoint
decode DecodeGrpcRequestFunc
encode EncodeGrpcResponseFunc
}
func NewGrpcHandler(endpoint Endpoint, decode DecodeGrpcRe... |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may ... |
package command
import (
"errors"
"github.com/opsgenie/opsgenie-go-sdk-v2/alert"
gcli "github.com/urfave/cli"
"io"
"net/http"
"os"
"strconv"
"strings"
"time"
)
func NewAlertClient(c *gcli.Context) (*alert.Client, error) {
alertCli, cliErr := alert.NewClient(getConfigurations(c))
if cliErr != nil {
messag... |
package ohdear
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"time"
)
type (
Sleeper interface {
Sleep(time.Duration)
}
StdLibSleeper struct{}
)
func (s StdLibSleeper) Sleep(seconds time.Duration) {
time.Sleep(seconds)
}
type Client struct {
BaseURL *url.URL
UserAgent... |
package main
// Remove main_wasm.go to update it in case of vugu upgrade.
//go:generate rm -f main_wasm.go
//go:generate gobin -m -run github.com/vugu/vugu/cmd/vugugen -skip-go-mod
|
package main
import "fmt"
func main() {
fmt.Println(findMaxAverage([]int{
0, 1, 1, 3, 3,
}, 4))
}
// 1,12,-5,-6,50,3
func findMaxAverage(nums []int, k int) float64 {
//win := make([]int, 0, k)
sum := 0
for i := 0; i < k; i++ {
sum += nums[i]
//win = append(win, nums[i])
}
mx := sum
for i := 1; i+k... |
package models
import (
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm"
)
type MvList struct {
Id int
Url string
ImgSrc string
Description string
DescriptionPoster string
OriginSrc string
Star string
Title string
... |
package main
import (
"encoding/json"
"fmt"
"github.com/confluentinc/confluent-kafka-go/kafka"
"github.com/rcrowley/go-metrics"
log "github.com/sirupsen/logrus"
"os"
"os/signal"
"strings"
"sync"
"syscall"
)
// Producer implements a High-level Apache Kafka Producer instance ZE 2018
// This allows Mocking pro... |
package main
import "fmt"
import _ "thorium-go/process"
func main(){
fmt.Println("hello world")
}
|
package greetingspackage
import "fmt"
// We indicate to Go that we want to export a function by upper casing the function's
// first letter.
func PrintGreetings() {
fmt.Println("I'm priting a message from the PrintGreetings() function!")
}
// This function is unexported (since it has a lowercase first letter in th... |
package infra
import (
"log"
"time"
"github.com/caarlos0/env/v6"
)
type Config struct {
WebConfig
DbConfig
OutboxHeartbeat time.Duration `env:"OUTBOX_HEARTBEAT" envDefault:"5s"`
}
type WebConfig struct {
Port string `env:"PORT" envDefault:":8080"`
}
type DbConfig struct {
DbName string `env:"DB_NAME" e... |
package v1
import (
"blog/app/models"
"blog/app/repositories"
"blog/app/web/responses/admin"
"blog/database"
"github.com/kataras/iris/v12"
"github.com/mlogclub/simple"
)
type TagController struct {
Ctx iris.Context
TagRepository *repositories.TagRepository
TagResponse admin.TagResponse
}
func Ne... |
package psql
import (
"testing"
)
func TestContractDaoFindById(t *testing.T) {
dao := ContractDao(db)
_, err := dao.FindById(1)
if err != nil {
t.Error(err)
}
}
func TestContractDaoFindDetails(t *testing.T) {
dao := ContractDao(db)
_, err := dao.FindDetails(1)
if err != nil {
t.Error(err)
}
}
|
package main
import (
"flag"
"fmt"
"log"
"os"
"runtime"
"sync"
)
// Overwrite flag
var _OW bool
// Mute flag
var _MUTE bool
func handleError(err error) {
if err != nil {
log.Fatalln(err)
}
}
func consoleOut(message string) {
if !_MUTE {
fmt.Println(message)
}
}
func findDumpJobs(path string, jobsCh ... |
package main
/*
#ctype Stmt *
*/
type stmtHandle uintptr
/*
#cmethod Open
#cmethod Close
*/
type dbIf struct {
handle stmtHandle
dbName string
}
/*
Enum type for operand
#ctype operKind
enum operKind: int32_t {
Get = 0,
Put = 1,
Delete = 2
};
*/
type OperKind int32
const (
Get = OperKind(0)
Put = Op... |
package services
import (
"github.com/spf13/viper"
jwt "github.com/dgrijalva/jwt-go"
)
type UserJWT struct {
ID uint `json:"id"`
UniqUserKey string `json:"uniq_user_key"`
jwt.StandardClaims
}
func CryptJWT(id uint, uKey string) (string, error) {
token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), &UserJW... |
// @Description mysql
// @Author jiangyang
// @Created 2020/10/30 3:44 下午
// Example Config:
// mysql:
// user: root
// password: 123456
// host: 127.0.0.1
// port: 3306
// dbname: demo
// max_idle_conn: 10
// max_open_conn: 100
// debug: true
package mysql
import (
"fmt"
"gorm.io/gorm/log... |
// test-multi-var project main.go
package main
import (
"fmt"
)
func myfunc(args ...int) {
for _, arg := range args {
fmt.Println(arg)
}
}
func rawPrint(rawList ...interface{}) {
for _, a := range rawList {
fmt.Println(a)
}
}
func print(slist ...interface{}) {
rawPrint(slist...)
}
func main() {
fmt.Print... |
package exasol
import (
"fmt"
"regexp"
"strconv"
"strings"
)
type DSNConfig struct {
host string
port int
user string
password string
autocommit *bool
encryption *bool
compression *bool
clientName string
clientVersion string
fetchSize int
useTLS *bo... |
package game
import (
"errors"
"github.com/golang/glog"
"github.com/noxue/utils/fsm"
"qipai/dao"
"qipai/utils"
"sync"
"zero"
)
const (
ReadyState = iota + 1 // 准备中
SelectBankerState // 抢庄中
SetScoreState // 下注中
ShowCardState // 看牌中
CompareCardState ... |
package main
import (
"db_analyze_pro"
"encoding/csv"
"fmt"
"io"
"os"
"strconv"
)
//var a = 12
// const A = 12
//var b = "string"
//var c interface{}
//
//type d interface {
//
//}
//type e int
var arr [10] int
var slice [6]int
var m map[int]string
type KK struct {
a int
b int
}
// 统计数据
type StData stru... |
package gocql
import (
"context"
"github.com/gocql/gocql"
)
type SessionChecker struct {
session *gocql.Session
}
func (c *SessionChecker) Check(ctx context.Context) error {
return c.session.Query("void").Exec()
}
func NewSessionChecker(session *gocql.Session) *SessionChecker {
return &SessionChecker{session:... |
// golang中没有构造模式~所以用工厂模式
// type student struct 这里student实例首字母是小写,但是要再其他包里用这个~~ 就用到了工厂模式
package main
import (
"fmt"
"go_project/9method/factory/student"
)
func main(){
// 第一种方法,因为Student 的首字母是大写的,所以再其他包可以直接使用,但是要是小写就会有报错`~~
// 报错内容如下,意思就是没有这个结构体~~~·
// 要想正常使用,那就要用到工厂模式
/* .\main.go:13:11: cannot refer to... |
package main
import (
"flag"
"fmt"
"math/rand"
"time"
_ "github.com/manishrjain/gocrud/drivers/elasticsearch"
"github.com/manishrjain/gocrud/search"
"github.com/manishrjain/gocrud/x"
)
var eip = flag.String("ipaddr", "", "IP address of Elastic Search")
var num = flag.Int("num", 1, "Number of results")
type A... |
package main
import (
"fmt"
"os"
"errors"
)
func warn(format string, a ...interface{}) (n int, err error) {
return fmt.Fprintf(os.Stderr, format, a...)
}
func croak(e error) {
warn("%s\n", e)
}
func die(e error) {
croak(e)
os.Exit(1)
}
var (
hashFunction HashValue
cwd string
dryRun bool
silent bool
)
v... |
package version
import (
"github.com/Masterminds/semver"
)
var (
v1 = mustVersion("1")
v2 = mustVersion("2")
v21 = mustVersion("2.1")
v22 = mustVersion("2.2")
v23 = mustVersion("2.3")
)
// IsV1 returns if is a given Taskfile version is version 1
func IsV1(v *semver.Constraints) bool {
return v.Check(v1)
}
... |
package main
import (
"fmt"
"log"
"net"
)
func main() {
udp, err := net.DialUDP("udp", nil, &net.UDPAddr{
IP: net.ParseIP("127.0.0.1"),
Port: 8080,
})
if err != nil {
log.Fatalf("DialUDP error:%v\n", err)
}
defer udp.Close()
// 发送数据
_, err = udp.Write([]byte("Hello Server"))
if err != nil {
log.... |
package authorize
import (
"context"
"sync/atomic"
"time"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/pomerium/pomerium/internal/log"
"github.com/pomerium/pomerium/internal/sets"
"github.com/pomerium/pomerium/pkg/grpc/databr... |
package oss
import (
"bytes"
"crypto/hmac"
"crypto/md5"
"crypto/sha1"
"encoding/base64"
"errors"
"io/ioutil"
"net/http"
"sort"
"strings"
)
type authorization struct {
req *http.Request
bucket string
object string
secret []byte
}
// ContentMD5 is the option for calculating and adding a Content-Md5 he... |
package telegram
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"github.com/spotify-bot/server/pkg/spotify"
"github.com/spotify-bot/telegram/internal/config"
)
func getRecentlyPlayed(userID string) (track *spotify.Track, err error) {
track, err = getCurrentlyPlayingSong(userID)
if err !... |
package model
import "fmt"
type ErrorMessage struct {
Code int `json:"code"`
Message string `json:"message"`
Details string `json:"detail"`
}
const (
ErrorCodeParameter = iota
ErrorCodeReadBody
ErrorCodeUnmarshalJSON
)
var ErrorCodes = map[int]string{
ErrorCodeParameter: "Parameter error",
ErrorCo... |
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
)
const (
host = "localhost"
port = 5432
user = "postgres"
password = "temppassword"
dbname = "priva_dev"
)
func main() {
// Creating the connection string.
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbna... |
// This file was generated for SObject ProcessInstanceHistory, API Version v43.0 at 2018-07-30 03:47:22.162998645 -0400 EDT m=+8.505924250
package sobjects
import (
"fmt"
"strings"
)
type ProcessInstanceHistory struct {
BaseSObject
ActorId string `force:",omitempty"`
Comments string `... |
package main
import (
"flag"
"fmt"
"github.com/justfallingup/gocore/hw03-gosearch01/pkg/crawler"
"github.com/justfallingup/gocore/hw03-gosearch01/pkg/crawler/spider"
"log"
"strings"
)
func main() {
token := flag.String("s", "", "a word you're searching for")
flag.Parse()
urls := []string{
"https://go.dev"... |
package admin
import (
"fmt"
"net/http"
)
func (s *Service) Status(writer http.ResponseWriter, request *http.Request) {
writer.WriteHeader(http.StatusOK)
fmt.Println("test")
_, _ = writer.Write([]byte("I am alive"))
}
|
package qzxing
/*
#cgo CPPFLAGS: -DQZXING_QML -I ${SRCDIR}/qzxing/src/zxing
#cgo darwin,amd64,!ios LDFLAGS: -L ${SRCDIR}/qzxing/src/darwin
#cgo linux,amd64 LDFLAGS: -L ${SRCDIR}/qzxing/src/linux
#cgo windows,amd64 LDFLAGS: -L ${SRCDIR}/qzxing/src/windows
#cgo ios LDFLAGS: -L ${SRCDIR}/qzxing/src/ios
#cgo... |
package main
import (
"fmt"
"io/ioutil"
"math/rand"
"os"
"strings"
"time"
)
//card struct
type Card struct {
suit, value string
}
//deck slice
type deck []Card
func newDeck() deck {
//create a list of playing cards
//essentially an array of strings
cards := deck{}
//we will use an unconvetional way to cr... |
package golden
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"strings"
"testing"
"github.com/fatih/color"
"github.com/pmezard/go-difflib/difflib"
)
var (
// Extension that is added to the name of the input file to identify the
// matching golden file.
Extension ... |
/*
Copyright 2016 The Rook Authors. 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 ... |
/*
Write a function that takes an IP address and returns the domain name using PTR DNS records.
Example
get_domain("8.8.8.8") ➞ "dns.google"
get_domain("8.8.4.4") ➞ "dns.google"
Notes
You may want to import socket.
Don't cheat and just print the domain name, you need to make a real DNS request.
Return... |
package main
import (
"fmt"
"time"
)
func main() {
// START OMIT
i := 0
for {
i++
fmt.Printf("%d\n", i)
time.Sleep(100 * time.Millisecond)
}
// END OMIT
}
|
package queue
import (
"context"
"encoding/base64"
"github.com/go-redis/redis"
"github.com/pkg/errors"
)
// Ensure RedisAdapter implements Queue.
var _ Queue = (*RedisAdapter)(nil)
// NewRedisAdapter creates a new RedisAdapter.
func NewRedisAdapter(c *redis.Client) *RedisAdapter {
if c == nil {
panic("nil qu... |
package main
import (
"bufio"
"fmt"
"log"
"os"
"strings"
)
func readdata(fname string) (lines []string) {
f, err := os.Open(fname)
if err != nil {
log.Fatalf("Error opening dataset '%s': %s", fname, err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
scanner.Split(bufio.ScanLines)
for scanner.Scan... |
package ilock
type IQueue interface {
/*
获取队列锁
timeSleep int 毫秒 设置每次获取队列的间隔时间
timeOut int64 毫秒 设置无法获取队列退出时间
成功返回nil
失败返回error
*/
Lock(timeSleep int, timeOut int64) error
/*
队列解锁
成功返回nil
失败返回error
*/
UnLock() error
/*
获取队列ID
返回值int64
*/
GetId() int64
/*
获取队列Key
返回值string
*/
GetKey() ... |
package dushengchen
/*
question:
https://leetcode.com/problems/reverse-integer/
Submission:
https://leetcode.com/submissions/detail/231980096/
*/
func reverse(x int) int {
if x == 0 {
return 0
} else if x < 0 {
return -reverse(-x)
}
max := 1<<31 - 1
res := 0
for {
res = res*10 + x%10
x = x / 1... |
package cinii
import (
"net/url"
"testing"
)
func TestSearchBooks(t *testing.T) {
q := url.Values{}
q.Set("q", "ソフトウェア")
q.Set("type", "0")
q.Set("sortorder", "3")
q.Set("count", "5")
resobj, err := client.SearchBooks(q)
if err != nil {
t.Error("Failed to get Response:", err)
return
}
if len(resobj.G... |
package utils
import (
"encoding/json"
"errors"
"fmt"
"github.com/shopspring/decimal"
"regexp"
"math"
"strconv"
"strings"
"time"
)
func ToString(x interface{}) string {
var v2 string
switch v := x.(type) {
case bool:
if true == x {
v2 = "1"
} else {
v2 = "0"
}
case int:
v2 = strconv.Itoa(... |
package enemy
// Enemy is an opponent to the player and will be fed
// into the battle manager after configuration.
type Enemy struct {
}
|
package bit_map
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestByte2String(t *testing.T) {
t.Log(byte2String(byte(21)))
}
func TestBitMap_Set(t *testing.T) {
bm := &BitMap{
Size: 20,
}
bm.Init()
t.Logf("start: [%s]", bm)
err := bm.Set(10)
assert.Nil(t, err)
err = bm.Set(13)
assert.Ni... |
package connector
import (
"errors"
"net/http"
"net/url"
"strings"
"github.com/mayflower/docker-ls/lib/auth"
)
type tokenAuthConnector struct {
cfg Config
httpClient *http.Client
authenticator auth.Authenticator
semaphore semaphore
tokenCache *tokenCache
stat *statistics
}
fu... |
package PDU
import "github.com/andrewz1/gosmpp/Data"
type BindTransmitterResp struct {
BindResponse
}
func NewBindTransmitterResp() *BindTransmitterResp {
a := &BindTransmitterResp{}
a.Construct()
return a
}
func (c *BindTransmitterResp) Construct() {
defer c.SetRealReference(c)
c.BindResponse.Construct()
... |
/*
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 writ... |
package ignite
import (
"fmt"
"net"
"path/filepath"
"github.com/weaveworks/footloose/pkg/config"
"github.com/weaveworks/footloose/pkg/exec"
)
const (
IgniteName = "ignite"
)
// This offset is incremented for each port so we avoid
// duplicate port bindings (and hopefully port collisions).
var portOffset uint1... |
/*
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 client
import (
"io/ioutil"
"net/http"
"github.com/devspace-cloud/devspace/pkg/devspace/cloud/token"
"github.com/pkg/errors"
)
// TokenEndpoint is the endpoint where to get a token from
const TokenEndpoint = "/auth/token"
// GetToken returns a valid access token to the provider
func (c *client) GetToken... |
/*
Copyright (c) 2014, Thomas Lingefelt <thomasrling@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUT... |
package ctree
import (
"fmt"
"strings"
"testing"
)
// Testing structure
type mys struct {
s string
}
func (m mys) String() string {
return m.s
}
func TestExample(t *testing.T) {
r := &mys{}
ct := NewTree("T", r)
a := mys{"a"}
ct.Add(r, &a)
b := mys{"b"}
c := mys{"c"}
ct.Add(&a, &b)
ct.Add(&a, &c)
ct.A... |
package model
type UserModel struct {
Id int
Email string
Name string
Value int
} |
package flow
import (
"encoding/json"
"testing"
)
func TestFlowJSON(t *testing.T) {
str1 := "code token"
flow, _ := JudgeByResponseType(str1)
b, _ := json.Marshal(flow)
actual := string(b)
expected := `{"type":"hybrid","require_access_token":true,"require_id_token":false}`
if actual != expected {
t.Errorf("... |
package client
import "fmt"
func wrapError(customMsg string, originalError error) error {
return fmt.Errorf("%s : %v", customMsg, originalError)
}
|
package sqls
// DelResults is SQL.
const DelResults = `
DELETE FROM results
WHERE
competition_id = ?
AND user_id = ?
`
|
package postal_test
import (
"encoding/json"
"errors"
"github.com/cloudfoundry-incubator/notifications/cf"
"github.com/cloudfoundry-incubator/notifications/fakes"
"github.com/cloudfoundry-incubator/notifications/postal"
"github.com/pivotal-cf/uaa-sso-golang/uaa"
. "github.com/onsi/ginkgo"... |
package main
import "fmt"
func changeFirst(slice []int) {
slice[0] = 1000
}
func main() {
var x []int = []int{3, 4, 5} //just create slice[]int on `mem-map`
fmt.Println(x) // pass that in to console
changeFirst(x) // dup `the value of` 1st x, pass to another `mem-map` bottom
fmt.Print... |
package types
import (
"fmt"
"strings"
codec "github.com/hashrs/blockchain/framework/chain-app/codec"
sdk "github.com/hashrs/blockchain/framework/chain-app/types"
)
const (
// ModuleName is the name of the module
ModuleName = "greeter"
// StoreKey is used to register the module's store
StoreKey = ModuleName... |
package main
import (
"fmt"
)
/*
Go语言中没有类的概念,也不支持类的继承等面向对象的概念,Go语言中通过
结构体的内嵌再配合接口比面向对象具有更高的扩展性和灵活性
自定义类型
type MyInt int //将MyInt定义为int类型
通过type关键字的定义,MyInt是一种新的类型,具有int的特性
类型别名
是Go1.9版本添加的新功能
type TypeAlias = Type //TypeAlias只是Type的别名,本质上TypeAlias与Type是同一个类型
比如系统的
type byte = int8
type rune =... |
/*
Copyright 2022 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 btrfs
/*
#include <stdlib.h>
#include <dirent.h>
*/
import "C"
import (
"fmt"
"unsafe"
)
func free(p *C.char) {
C.free(unsafe.Pointer(p))
}
func openDir(path string) (*C.DIR, error) {
Cpath := C.CString(path)
defer free(Cpath)
dir := C.opendir(Cpath)
if dir == nil {
return nil, fmt.Errorf("Can't o... |
package model
type Menu struct {
Info string `json:"info,omitempty"`
Restaurant string `json:"restaurant"`
Url string `json:"url"`
Soup MenuItem `json:"soup,omitempty"`
Menus []MenuItem `json:"menus,omitempty"`
SpecialMenus *[]MenuItem `json:"specialMenus,omit... |
package main
type Marker struct {
left int
len int
}
func getMaxLen(nums []int) int {
return mlps(nums, 0, len(nums)).len
}
func mlps(nums []int, j int, k int) Marker {
/** Helpers */
const IntMax = int(^uint(0) >> 1)
const IntMin = -int(^uint(0)>>1) - 1
MaxInt := func(args ...int) int {
if len(args) == 0 ... |
package webreg
import (
"bytes"
"errors"
"fmt"
"html/template"
"net/http"
"path"
"strings"
"time"
"github.com/alecthomas/chroma"
"github.com/alecthomas/chroma/formatters/html"
"github.com/alecthomas/chroma/lexers"
"github.com/alecthomas/chroma/styles"
"github.com/sirupsen/logrus"
"k8s.io/test-infra/prow... |
package solcast
import (
"os"
)
const BaseUrl = "https://api.solcast.com.au"
const Solcast_API_KeyName = "SOLCAST_API_KEY"
type Config struct {
Url string
APIKey string
}
func Read() Config {
return Config{
Url: BaseUrl,
APIKey: os.Getenv(Solcast_API_KeyName),
}
}
|
package main
import "fmt"
func main() {
const ft float64 = 0.3048 // это миллиметры
var m = 66.12 // это футы
{
fmt.Printf("%.3f", m*ft) // это вычисление кол-ва миллиметров в указанных футах
fmt.Println(" m")
//fmt.Println(" m") - для удобства)
}
}
|
package database
import (
"ewallet/models"
"github.com/jinzhu/gorm"
)
func Migrate(con *gorm.DB) {
con.DropTableIfExists(models.UserBalanceHistory{}, models.UserBalance{}, models.User{}, models.BankBalanceHistory{}, models.BankBalance{})
con.AutoMigrate(models.User{}, models.UserBalance{}, models.UserBalanceHisto... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.