text stringlengths 11 4.05M |
|---|
/*
* @lc app=leetcode.cn id=807 lang=golang
*
* [807] 保持城市天际线
*/
package main
import (
"math"
)
// @lc code=start
func maxIncreaseKeepingSkyline(grid [][]int) int {
maxRow := make([]int, len(grid))
maxCol := make([]int, len(grid[0]))
for i := 0; i < len(grid); i++ {
maxRow[i] = grid[i][0]
for j := 1; j < ... |
/**
* Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
* The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
*/
func isValid(s string) bool {
var stack []int32 = make([]int32, 0, len(... |
package config
import (
env "github.com/mauhftw/genialo/helpers"
)
// TODO: Add a prefix env variable
// Define environment variables here
var (
GithubAccessToken = env.GetEnvVar("GITHUB_CHANGELOG_TOKEN", "github_token").(string)
)
|
package annotations
import (
"strings"
"time"
"github.com/haproxytech/config-parser/v3/types"
"github.com/haproxytech/kubernetes-ingress/controller/haproxy/api"
"github.com/haproxytech/kubernetes-ingress/controller/store"
)
type DefaultTimeout struct {
name string
data *types.SimpleTimeout
client api.HA... |
package commands
import (
"fmt"
"testing"
"reflect"
"encoding/json"
"github.com/JFrogDev/artifactory-cli-go/utils"
)
func TestConfig(t *testing.T){
inputDetails := utils.ArtifactoryDetails { "http://localhost:8080/artifactory", "admin", "password", "", nil }
Config(&inputDetails, false, fa... |
package main
import "fmt"
func sortColors(nums []int) {
zero := -1
two :=len(nums)
for i:=0;i<two;{
if nums[i] == 1{
i++
}else if nums[i] == 2{
two--
nums[i],nums[two] = nums[two],nums[i]
}else{
zero++
nums[zero],nums[i] = nums[i],nums[zero] //直接交换即可,因为nums[zero]一定是1
i++
}
}
}
//使用快排思路,... |
package services
import (
"finrgo/exhanges"
"fmt"
"sync"
"time"
)
type (
OpenOrdersBusy struct {
IsDebugRunService bool
isBusy bool
sync.RWMutex
Exchange *exhanges.Exchanges
Sleep time.Duration
}
)
func NewServiceOpenOrder(ex *exhanges.Exchanges) *OpenOrdersBusy {
return &OpenOrdersBus... |
package env
import (
"context"
"github.com/dollarshaveclub/acyl/pkg/models"
"github.com/dollarshaveclub/acyl/pkg/spawner"
)
var _ spawner.EnvironmentSpawner = &Manager{}
// Destroy is the same as Delete and is needed to satisfy the interface
func (m *Manager) Destroy(ctx context.Context, rd models.RepoRevisionDa... |
package main
import (
"encoding/json"
"log"
"net/http"
"fmt"
"net"
"github.com/gorilla/mux"
"sync"
"bufio"
)
type Contact struct {
Name string `json:"name"`
Phone string `json:"phone"`
Email string `json:"email"`
}
type Planta struct {
S_lenght float64 `json:"s_lenght"`
S_width float64 `json:"s_width"`
... |
/*
You are given an integer array arr. You can choose a set of integers and remove all the occurrences of these integers in the array.
Return the minimum size of the set so that at least half of the integers of the array are removed.
Example 1:
Input: arr = [3,3,3,3,5,5,5,2,2,7]
Output: 2
Explanation: Choosing {3,7... |
package web_dao
import (
"2021/yunsongcailu/yunsong_server/dial"
"2021/yunsongcailu/yunsong_server/web/web_model"
)
type CommentDao interface {
// 插入一条评论
InsertCommentOne(comment *web_model.CommentModel) (id int64,err error)
// 根据文章ID 获取评论
QueryCommentByArticleId(articleId int64,count,start int) (commentData []... |
package main
import (
"fmt"
"github.com/tylertreat/BoomFilters"
)
func main() {
sbf := boom.NewDefaultScalableBloomFilter(0.01)
if sbf.Add([]byte("a")).Test([]byte("a")) {
fmt.Println("contains a")
}
if !sbf.TestAndAdd([]byte("b")) {
fmt.Println("doesn't contain b")
}
if sbf.Test([]byte("b")) {
fmt.... |
package html
import (
"fmt"
"github.com/elliotchance/gedcom"
"github.com/elliotchance/gedcom/html/core"
"io"
"strings"
)
const symbolLetter = '#'
func write(w io.Writer, data []byte) (int64, error) {
n, err := w.Write(data)
return int64(n), err
}
func writeString(w io.Writer, data string) (int64, error) {
... |
package graph
// This file will be automatically regenerated based on the schema, any resolver implementations
// will be copied through when generating and any unknown code will be moved to the end.
import (
"context"
"errors"
"github.com/LFSCamargo/twitter-go/auth"
"github.com/LFSCamargo/twitter-go/constants"
... |
// Package sessions provides the interface and default session store for
// RiveScript.
package sessions
/*
Interface SessionManager describes a session manager for user variables
in RiveScript.
The session manager keeps track of getting and setting user variables,
for example when the `<set>` or `<get>` tags are use... |
package mylogger
import (
"fmt"
"path"
"runtime"
"strings"
"time"
)
type LogLevel uint16
const (
DEBUG LogLevel = iota
TRACE
INFO
WARNING
ERROR
FATAL
)
type Logger struct {
level LogLevel
}
func parseLogLevel(s string) LogLevel {
s = strings.ToLower(s)
switch s {
case "debug":
return DEBUG
case "... |
package main
import (
"net"
"fmt"
"os"
)
/*
·服务端在本机的8888端口建立UDP监听,得到广口连接
·循环接收客户端消息,不管客户端说什么,都自动回复“已阅xxx”
·如果客户端说的是“im off”,则回复“bye”
*/
func main() {
//解析得到UDP地址
udpAddr, err := net.ResolveUDPAddr("udp", "localhost:8888")
ServerHandleError(err, "net.ResolveUDPAddr")
//建立UDP监听,得到广口连接
udpConn, err := net.Liste... |
package middleware
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
_const "github.com/IcanFun/utils/const"
"github.com/IcanFun/utils/utils/log"
"github.com/gin-gonic/gin"
"github.com/IcanFun/utils/i18n"
"github.com/dgrijalva/jwt-go"
goi18n "github.com/nicksnyder/... |
package utils
import (
"archive/zip"
"bytes"
"crypto/md5"
"encoding/hex"
"errors"
"fmt"
"io"
"mime/multipart"
"os"
"reflect"
"strings"
"time"
)
// 返回当前时间
func GetDate() string {
timestamp := time.Now().Unix()
tm := time.Unix(timestamp, 0)
return tm.Format("2006-01-02 03:04:05")
}
// 获取当前系统环境
func GetR... |
package fibo
//Num вычисляет число Фибоначчи для неотрицательного n
func Num(n int) int {
if n == 0 {
return 0
}
x1, x2 := 0, 1
for i := 1; i < n; i++ {
x1, x2 = x2, x1 + x2
}
return x2
}
|
// go run gota_usage.go
package main
import (
"fmt"
"log"
"os"
"github.com/go-gota/gota/dataframe"
"github.com/go-gota/gota/series"
)
func main() {
csvfile, err := os.Open("test.csv")
if err != nil {
log.Fatal(err)
}
df := dataframe.ReadCSV(csvfile)
fmt.Println(df)
df = df.Filter(dataframe.F{"3", "=="... |
// 写出下面程序的输出及简要解释
package main
import (
"fmt"
)
func main() {
test1()
test2()
test3()
test4()
fmt.Println("test5: ", test5())
fmt.Println("test6: ", test6())
fmt.Println("test7: ", test7())
fmt.Println("test8: ", test8())
}
func test1() {
defer a()
defer b()
fmt.Println("test1")
}
// test1,b,a
func tes... |
package virtual_security
import (
"errors"
"reflect"
"testing"
"time"
)
type testPriceStore struct {
getBySymbolCode1 *symbolPrice
getBySymbolCode2 error
getBySymbolCodeHistory []string
set1 error
setHistory []*symbolPrice
}
func (t *testPriceStore) getBySymbolCode(... |
package dynamodb
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/dynamodb"
)
// GetUsersAttrDefs returns the definitions
func GetUsersAttrDefs() []*dynamodb.AttributeDefinition {
return []*dynamodb.AttributeDefinition{{
AttributeName: aws.String("Login"),
AttributeType: aws.String("... |
package main
import "fmt"
type S1 struct{}
func (s *S1) String() string {
return "S1.String"
}
type S2 struct{}
type S3 struct{}
func (s *S3) String(in string) string {
return "S3.String"
}
type I interface {
String() string
}
func main() {
s1 := new(S1)
// s2 := new(S2)
// s3 := new(S3)
var i I
i = s... |
package fmm
import "testing"
func TestVersion(t *testing.T) {
tests := []struct {
input string
output string
outputWithBuild string
p0, p1, p2, p3 uint16
}{
{"1.0", "1.0.0", "1.0.0.0", 1, 0, 0, 0},
{"1.1.15", "1.1.15", "1.1.15.0", 1, 1, 15, 0},
{"2.3.4.5", "2.3.4", "2.3.4.5", 2, 3,... |
package ppm
import (
"errors"
"fmt"
"os"
"strings"
)
//PpImage is an ppm image object
type PpImage struct {
name string
mode string
wdith, height int
maxPixel uint16
pixel [][]Vector
Colors
}
//Vector used for rgb color
type Vector struct {
X, Y, Z float64
}
type Colors int... |
package db
import (
"github.com/go-xorm/xorm"
"log"
)
const (
DB_HOST = "127.0.0.1:3306"
DB_USER = "root"
DB_PWD = "chendong"
DB_NAME = "test"
)
func GetEngine ()(*xorm.Engine){
engine, err := xorm.NewEngine("mysql", DB_USER+":"+DB_PWD+"@/"+DB_NAME+"?charset=utf8")
if err!=nil{
log.Println(err)
}
engine.... |
package utils
import (
"fmt"
"sync"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"github.com/samuel/go-zookeeper/zk"
)
//反解dubbo结构,ip:[func1,func2,...]
type FuncMap map[string][]string
//返回查询结果的结构体
type Result struct {
Weight int `json:"weight"`
Disable bool `json:"disable"`
}
//查询dubbo结构体
t... |
package lib
const (
// DefaultOAuth2URL is default OAuth2 server address.
DefaultOAuth2URL = "https://oauth.lycam.tv"
// DefaultAPIURL is default api server address.
DefaultAPIURL = "https://api.lycam.tv"
// DefaultTokenPath is default api path.
DefaultTokenPath = "/oauth2/token"
// DefaultAPIVersion is api ... |
package model
type SignedBlock struct {
Block Block `json:"block"`
Justification Bytes `json:"justification"`
}
|
package handlers_test
import (
"bytes"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"github.com/pivotal-cf-experimental/envoy/domain"
"github.com/pivotal-cf-experimental/envoy/internal/handlers"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
type Provisioner struct {
WasCall... |
package main
import (
"mysql_byroad/model"
"sync"
)
type TaskIdMap struct {
cmap map[int64]*model.Task
sync.RWMutex
}
func NewTaskIdMap(size int) *TaskIdMap {
cmap := new(TaskIdMap)
cmap.cmap = make(map[int64]*model.Task, size)
return cmap
}
func (this *TaskIdMap) Get(id int64) *model.Task {
this.RLock()
d... |
package models
import (
"go.mongodb.org/mongo-driver/bson/primitive"
"time"
)
type Post struct {
ID primitive.ObjectID `bson:"_id"`
Caption string `bson:"caption"`
Username string `bson:"username"`
Filename string `bson:"filename"`
Likes int `bson:"likes"`
DatePosted time.Time `bson:"dateposted"`
UserL... |
package model
import (
"github.com/lichunchengPG/go-pratice/goblog/pkg/logger"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
// DB gorm.DB 对象
var DB *gorm.DB
// 初始化模型
func ConnectDB() *gorm.DB {
var err error
config := mysql.New(mysql.Config{
DSN: "root:secret@tcp(127.0.0.1:3306)/goblog?charset=utf8&parseTime=True... |
// Copyright © 2017 NAME HERE <EMAIL ADDRESS>
//
// 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 response
import (
"github.com/gin-gonic/gin"
"net/http"
)
type RestErr struct {
Message gin.H
Status int `json:"status"`
}
func NewBadRequest(message gin.H) *RestErr {
return &RestErr{Message: message, Status: http.StatusBadRequest}
}
func NewPartialProcessError(message gin.H) *RestErr {
return &Rest... |
package line
import (
"context"
"net/http"
"time"
"github.com/otamoe/oauth-client"
)
type (
Client struct {
oauth.OAuth2
}
)
var Endpoint = oauth.Endpoint{
Name: "line",
AuthorizeURL: "https://access.line.me/oauth2/v2.1/authorize",
AccessTokenURL: "https://api.line.me/oauth2/v2.1/token",
Rev... |
package tts
import (
"log"
"regexp"
)
func matchConvertResult(r convertResult) (string, error) {
s := r.Result()
re, _ := regexp.Compile(`(?P<resultCode>[[:digit:]]+)&(?P<resultMsg>[\s[:alnum:]]+)&?(?P<covertID>[[:digit:]]+)?`)
if !re.MatchString(s) || re.FindStringSubmatch(s)[1] != "0" {
log.Fatalf("matchCon... |
package main
import (
"flag"
"log"
"os"
"os/signal"
"syscall"
"tesla_exporter/exporter"
"time"
"github.com/prometheus/client_golang/prometheus"
)
var s *exporter.Server
var (
email string
password string
)
func main() {
// var email = flag.String("email", "", "tesla email address.")
// var password =... |
package cmd
import (
"fmt"
"go/build"
"io/ioutil"
"os"
"strings"
"path/filepath"
"github.com/spf13/cobra"
tmversion "github.com/tendermint/tendermint/version"
"github.com/cosmos/cosmos-sdk/version"
)
var remoteBasecoinPath = "github.com/cosmos/cosmos-sdk/docs/examples/basecoin"
// Replacer to replace all... |
package objects
import (
"io"
"log"
"net/http"
"os"
"strings"
)
var storagePath string
func init() {
storagePath = os.Getenv("STORAGE_ROOT") + "/objects/"
}
// Handler handles http requests
func Handler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodPut:
// put method store ob... |
package leetcode
import "testing"
func TestMostCommonWord(t *testing.T) {
if mostCommonWord("Bob hit a ball, the hit BALL flew far after it was hit.", []string{"hit"}) != "ball" {
t.Fatal()
}
}
|
package pgtune
import (
"math"
"math/rand"
"testing"
"github.com/timescale/timescaledb-tune/internal/parse"
)
// defaultMemoryToBaseVals provides a memory from test memory levels to expected "base"
// memory settings. These "base" values are the values if there is only 1 CPU
// and 20 max connections to the data... |
// Package solver implements a general-purpose solver for boolean
// constraint satisfiability problems.
package solver
|
package git
/*
#include <git2.h>
extern int _go_git_index_add_all(git_index*, const git_strarray*, unsigned int, void*);
extern int _go_git_index_update_all(git_index*, const git_strarray*, void*);
extern int _go_git_index_remove_all(git_index*, const git_strarray*, void*);
*/
import "C"
import (
"fmt"
"runtime"
... |
package api
import (
"mingchuan.me/api/models"
"mingchuan.me/app/errors"
)
// models.go
// This file wraps some common swagger models
// ModelServiceError -
func ModelServiceError(err *errors.Error) *models.ServiceError {
errCode := int64(err.ErrorCode)
return &models.ServiceError{
Name: &(err.Name),
Code:... |
package main
var x = 100
func main(){
enum_const()
} |
package simplegfs
import (
"fmt"
"github.com/wweiw/simplegfs/pkg/cache"
log "github.com/Sirupsen/logrus"
"time"
sgfsErr "github.com/wweiw/simplegfs/error"
)
type Client struct {
masterAddr string
clientId uint64
locationCache *cache.Cache
leaseHolderCache *cache.Cache
}
func NewClient(masterAddr st... |
package unshare
import (
"github.com/criyle/go-sandbox/pkg/mount"
"github.com/criyle/go-sandbox/pkg/rlimit"
"github.com/criyle/go-sandbox/pkg/seccomp"
"github.com/criyle/go-sandbox/runner"
)
// Runner runs program in unshared namespaces
type Runner struct {
// argv and env for the child process
Args []string
E... |
package oidc_test
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/authelia/authelia/v4/internal/configuration/schema"
"github.com/authelia/authelia/v4/internal/oidc"
)
func TestNewOpenIDConnectWellKnownConfiguration(t *testing.T) {
tes... |
// This file was generated for SObject PicklistValueInfo, API Version v43.0 at 2018-07-30 03:47:33.116861558 -0400 EDT m=+19.460198196
package sobjects
import (
"fmt"
"strings"
)
type PicklistValueInfo struct {
BaseSObject
DurableId string `force:",omitempty"`
EntityParticleId string `force:",omitempty"`... |
package util
import (
"bufio"
)
func ReadWholeLine(conn *bufio.Reader) ([]byte, error) {
var (
result = []byte{}
isPrefex = true
err error
line []byte
)
for isPrefex {
line, isPrefex, err = conn.ReadLine()
result = append(result, line...)
if err != nil {
return result, err
}
}
re... |
package controllers
import (
"github.com/gorilla/websocket"
"net/http"
"github.com/astaxie/beego"
"fmt"
)
// WebSocketController handles WebSocket requests.
type WebSocketController struct {
beego.Controller
}
// Join method handles WebSocket requests for WebSocketController.
func (this *WebSocketController) Jo... |
package conf
var Num int = 10000 // 首字母大写
|
// 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 retry
import (
"io"
"time"
)
// Default defines the default retry parameters that should be used throughout
// the program. It is fine to upda... |
package main
import (
"strconv"
"github.com/freignat91/mlearning/api"
"github.com/spf13/cobra"
)
type trainSoluceOptions struct {
}
var (
trainSoluceOpts = trainSoluceOptions{}
)
// TrainSoluceCmd .
var TrainSoluceCmd = &cobra.Command{
Use: "trainSoluce",
Short: "train network right computed samples",
Run... |
package node
import (
"github.com/projecteru2/cli/cmd/utils"
"github.com/urfave/cli/v2"
)
const (
nodeArgsUsage = "nodename"
)
// Command exports node subommands
func Command() *cli.Command {
return &cli.Command{
Name: "node",
Usage: "node commands",
Subcommands: []*cli.Command{
{
Name: "get",
... |
package main
import (
"fmt"
"html/template"
"net/http"
)
func login(writer http.ResponseWriter, request *http.Request) {
request.ParseForm()
fmt.Println("method:", request.Method)
if request.Method == "GET" {
t, _ := template.ParseFiles("login.gtpl")
t.Execute(writer, nil)
} else if request.Method == "POST... |
package storage
import (
"github.com/biezhi/gorm-paginator/pagination"
md "github.com/ebikode/eLearning-core/model"
)
// DBApplicationStorage encapsulates DB Connection Model
type DBApplicationStorage struct {
*MDatabase
}
// NewDBApplicationStorage Initialize Application Storage
func NewDBApplicationStorage(db *... |
package handlers
import (
"bytes"
"html/template"
"strconv"
"time"
rice "github.com/GeertJohan/go.rice"
"github.com/labstack/echo/v4"
)
// HomeHandler is a default handler
// GET /
func HomeHandler(e echo.Context) error {
t, _ := template.New("index").Parse(
e.Get("TemplatesBox").(*rice.Box).MustString("ind... |
package sshconfig
import (
"errors"
"github.com/spencercjh/sshctx/internal/env"
"github.com/spencercjh/sshctx/internal/testutil"
"io/ioutil"
"os"
"path/filepath"
"testing"
)
func Test_getSSHCtxDataDir(t *testing.T) {
tests := []struct {
name string
want string
wantErr bool
}{
{name: "default", ... |
package main
// fixme : url https://blog.csdn.net/lazyboy_/article/details/103289750
import "fmt"
type Message struct {
id int
name string
address string
phone int
}
func (msg Message) String() {
fmt.Printf("ID:%d \n- Name:%s \n- Address:%s \n- phone:%d\n", msg.id, msg.name, msg.address, msg.phone)
... |
package vault
import (
"bytes"
"fmt"
"path/filepath"
"github.com/operator-framework/operator-sdk/pkg/sdk/action"
"github.com/operator-framework/operator-sdk/pkg/sdk/query"
api "github.com/operator-framework/operator-sdk-samples/vault-operator/pkg/apis/vault/v1alpha1"
"k8s.io/api/core/v1"
apierrors "k8s.io/api... |
package main
import (
"fmt"
"net/http"
_ "net/http/pprof"
"strings"
"time"
"github.com/grpc-ecosystem/go-grpc-prometheus"
"github.com/prometheus/client_golang/prometheus"
"gopkg.in/op/go-logging.v1"
"cli"
"tools/cache/cluster"
"tools/cache/server"
)
var log = logging.MustGetLogger("rpc_cache_server")
va... |
package gateway
import (
"context"
"log"
"net/http"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/grpc"
gw "github.com/Scarlet-Fairy/gateway/pb" // Update
)
type Endpoint struct {
Address string
}
type Options struct {
Address string
Endpoints struct {
Manager Endpoint
Lo... |
package test
import (
"crypto/sha256"
"encoding/hex"
"github.com/gruntwork-io/terratest/modules/aws"
"github.com/gruntwork-io/terratest/modules/files"
"github.com/gruntwork-io/terratest/modules/random"
"github.com/gruntwork-io/terratest/modules/terraform"
"os"
"strings"
"testing"
)
func TestS3BucketCreated(t... |
package main
import (
"fmt"
)
func main() {
arr := []string{"Alice", "Bob", "Cott"}
for i, e := range arr {
fmt.Printf("%v: %v\n", i, e)
}
}
|
package form
import (
"fmt"
"net/url"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
)
// PhoneRX represents phone number maching pattern
var PhoneRX = regexp.MustCompile("(^\\+[0-9]{2}|^\\+[0-9]{2}\\(0\\)|^\\(\\+[0-9]{2}\\)\\(0\\)|^00[0-9]{2}|^0)([0-9]{9}$|[0-9\\-\\s]{10}$)")
// EmailRX represents email ... |
package processors
import (
"errors"
"fmt"
"regexp"
"strings"
"github.com/vmware/kube-fluentd-operator/config-reloader/fluentd"
)
const (
tagRegex = `(?:[^\s{}()]*(?:(?:(?:{.*?})|(?:\(.*?\)))[^\s{}()]*)+)|(?:[^\s{}()]+(?:(?:(?:{.*?})|(?:\(.*?\)))[^\s{}()]*)*)`
)
type expandTagsState struct {
BaseProcessorSta... |
package game
import (
"time"
"github.com/UnnecessaryRain/ironway-core/pkg/mud/chat"
"github.com/UnnecessaryRain/ironway-core/pkg/network/protocol"
log "github.com/sirupsen/logrus"
)
type clientCommand struct {
client protocol.Sender
command Command
}
// Game defines the master game object and everything in t... |
package kuiperbelt
import (
"bytes"
)
type TestSession struct {
*bytes.Buffer
key string
isClosed bool
isNotifiedClose bool
}
func (s *TestSession) Key() string {
return s.key
}
func (s *TestSession) Close() error {
s.isClosed = true
return nil
}
func (s *TestSession) NotifiedClose(isNot... |
package service
import (
"context"
"fmt"
"log"
"strconv"
"sync"
"time"
"github.com/ChowRobin/fantim/constant"
"github.com/ChowRobin/fantim/constant/status"
"github.com/ChowRobin/fantim/manager"
"github.com/ChowRobin/fantim/model/bo"
"github.com/ChowRobin/fantim/model/po"
"github.com/ChowRobin/fantim/model... |
package main
import (
"log"
"net"
"xip/xip"
)
func main() {
conn, err := net.ListenUDP("udp", &net.UDPAddr{Port: 53})
if err != nil {
log.Fatal(err.Error())
}
for {
query := make([]byte, 512)
_, addr, err := conn.ReadFromUDP(query)
if err != nil {
log.Println(err.Error())
continue
}
go fun... |
package solutions
import (
"fmt"
"testing"
)
func TestLongestCommonPrefix(t *testing.T) {
t.Run("Test longestCommonPrefix", func(t *testing.T) {
var tests = []struct {
input []string
want string
}{
{[]string{"flower", "flow", "flight"}, "fl"},
{[]string{"dog", "racecar", "car"}, ""},
{[]string{... |
var Configobj map[string]map[string]interface{}
func init(){
Configobj = make(map[string]map[string]interface{})
f, err1 := os.OpenFile(path + "/config.json", os.O_RDONLY, 0666)
if err1 != nil {
utils.Log(err1)
}
err := json.NewDecoder(f).Decode(&Configobj)
if err != nil {
fmt.Println(err)
}
}
//获取对象值
fu... |
package main
type widget struct {
name string
data uint64
}
func main() {
ms := dummyStoreMap{
w: map[string]uint64{},
}
_ = ms
}
|
package notice_client
import (
"gocherry-api-gateway/admin/services"
"gopkg.in/gomail.v2"
"strconv"
)
/**
发送邮件告警
notice_client.EmailSend([]string{"9932851@qq.com"}, "333", "333")
*/
func EmailSend(mailTo []string, subject string, body string) bool {
config := services.GetAppConfig()
mailConn := map[string]string... |
package libreofficekit
/*
#cgo CFLAGS: -I ./ -D LOK_USE_UNSTABLE_API
#cgo LDFLAGS: -ldl
#include <lokbridge.h>
*/
import "C"
import (
"fmt"
"sync"
"unsafe"
)
type Office struct {
handle *C.struct__LibreOfficeKit
Mutex *sync.Mutex
}
// NewOffice returns new Office or error if LibreOfficeKit fails to load
// req... |
package main
import (
"bytes"
"compress/gzip"
"encoding/base64"
"fmt"
"github.com/liuzl/phonenumbers"
"io/ioutil"
)
func main() {
fmt.Println("vim-go")
fmt.Println(phonenumbers.CarriersPb)
data, err := base64.StdEncoding.DecodeString(phonenumbers.CarriersPb)
fmt.Println(data, err)
reader, err := gzip.NewRe... |
package utils
import (
"os"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
)
// AWSDebugEnv is the key used for the env variable that toggles debug logs
const AWSDebugEnv = "AWS_DEBUG"
// Logger defines a logger that can be configur... |
package dependency
import (
"fmt"
"strings"
"sync"
"github.com/andygrunwald/perseus/dependency/repository"
"github.com/andygrunwald/perseus/types/set"
)
// ComposerResolver is an implementation of Resolver for Composer (PHP)
type ComposerResolver struct {
// repository is the Client to talk to a specific endpo... |
package network
import (
"log"
msg "../messageTypes"
"../network/peers"
)
type Node struct {
id string
messageIDCounter int
networkChannels msg.NetworkChannels
peerUpdateChannelRx chan peers.PeerUpdate
peerTxEnable ... |
package lengthsafe
import (
"path/filepath"
"strings"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("splitPathOnSymlinkLimit()", func() {
BeforeEach(func() {
ensureSymlinkMaxSet()
})
Context("when path is shorter than symlinkMax", func() {
It("should return dir and remainder... |
package scoring
import (
"math/rand"
"net/http"
"net/url"
"strings"
"testing"
"github.com/luuphu25/data-sidecar/storage"
"github.com/luuphu25/data-sidecar/util"
)
func withJitter(n float64) float64 {
return n + 50*rand.Float64() - 5
}
func TestScore(t *testing.T) {
x := storage.NewStore()
for i := 0; i <... |
package env
import (
"fmt"
"os"
"strconv"
"strings"
)
// GetInt32Slice extracts slice of int32 value with the format "1,2,3" from env. if not set, returns default value.
func GetInt32Slice(key string, def []int32) []int32 {
s, ok := os.LookupEnv(key)
if !ok {
return def
}
if s == "" {
return []int32{}
}... |
// Rule parser using PyPy. To build this you need PyPy installed, but the stock one
// that comes with Ubuntu will not work since it doesn't include shared libraries.
// For now we suggest fetching the upstream packages from pypy.org. Other distros
// might work fine though.
// On OSX installing through Homebrew should... |
package service
import (
"go.uber.org/zap"
"mix/test/codes"
dto "mix/test/dto/core/transaction"
entity "mix/test/entity/core/transaction"
"mix/test/pb/core/transaction"
"mix/test/utils/status"
)
func (p *Transaction) createHotWithdraw(ctx *Context, in *transaction.CreateHotWithdrawInput, out *transaction.HotWit... |
package signer
import (
"strings"
"github.com/EscherAuth/escher/debug"
"github.com/EscherAuth/escher/request"
)
func (s *signer) CanonicalizeRequest(r request.Interface, headersToSign []string) string {
var u = parsePathQuery(r.RawURL())
parts := make([]string, 0, 6)
parts = append(parts, strings.ToUpper(r.Met... |
package poc
import (
"database/sql"
"fmt"
"log"
"time"
_ "github.com/go-sql-driver/mysql"
)
// Table
type Table struct {
Name string
TypeGroup string
SQL string
Fields []string
Constraints []Constraint
Triggers []Trigger
}
// Constraint
type Constraint struct {
Name ... |
package rizla
import (
"os"
"github.com/iris-contrib/color"
"github.com/mattn/go-colorable"
)
type Printer struct {
*color.Color
// stream is the output stream which the program will use
stream *os.File
}
// NewPrinter returns a new colorable printer
func NewPrinter(out *os.File) *Printer {
c := color.New(co... |
package main
import (
"encoding/json"
"fmt"
"github.com/hyperledger/fabric-contract-api-go/contractapi"
)
// Update changes the value with id in the world state
func (rc *ResourceTypesContract) Update(ctx contractapi.TransactionContextInterface, id string, name string) error {
existing, err := ctx.GetStub().GetS... |
package chunkserver
import (
"os"
"testing"
)
func testReadWrite(t *testing.T, s string) {
path := "/tmp/test"
os.Remove(path)
bytes := []byte(s)
WriteDataAt(path, 0, bytes)
got := make([]byte, 100)
n, err := ReadDataAt(path, 0, got)
if err != nil {
t.Error(err)
}
if string(got[:n]) != s {
... |
/*
Create a function that takes in an array of grass heights and a variable sequence of lawn mower cuts and outputs the array of successive grass heights.
If after a cut, any single element in the array reaches zero or negative, return "Done" instead of the array of new heights.
A demo:
cuttingGrass([3, 4, 4, 4], 1... |
// Copyright (C) 2018 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 ratelimiters
import (
"sync"
"time"
"github.com/corverroos/ratelimit"
)
func NewNoopLock(period time.Duration, limit int) *NoopLock {
return &NoopLock{
period: period,
limit: limit,
}
}
type NoopLock struct {
period time.Duration
limit int
mu sync.Mutex
}
func (n *NoopLock) Request(reso... |
package renter
import (
"bytes"
"context"
"time"
"gitlab.com/NebulousLabs/Sia/build"
"gitlab.com/NebulousLabs/Sia/crypto"
"gitlab.com/NebulousLabs/Sia/modules"
"gitlab.com/NebulousLabs/Sia/types"
"gitlab.com/NebulousLabs/errors"
)
// errNotEnoughPieces is returned when there are not enough pieces found to
/... |
package factories
import "github.com/giventocode/azure-blob-md5/internal"
//BlobReader TODO
type BlobReader struct {
readDepth int
az azUtil
blobName string
size int64
}
func newBlobReader(blobName string, size int64, az azUtil) *BlobReader {
return &BlobReader{
readDepth: defaultReadDepth,
blo... |
/**
*@Author: haoxiongxiao
*@Date: 2019/2/3
*@Description: CREATE GO FILE controller
*/
package admin
import (
"github.com/kataras/iris"
"math/rand"
"time"
)
type Common struct {
Ctx iris.Context
}
func (this *Common) ReturnJson(status int, message string, args ...interface{}) {
result := make(map[string]interf... |
package alicloud
import (
"github.com/hashicorp/terraform/helper/resource"
"testing"
)
func TestAccAlicloudDnsDomainsDataSource_ali_domain(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccPreCheck(t)
},
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.