text stringlengths 11 4.05M |
|---|
package main
import (
"flag"
"github.com/fanan/netease_download/netease"
"log"
"os"
)
var playlistID = flag.Int64("l", 22914865, "playlistID")
var downloadDir = flag.String("d", os.ExpandEnv("$HOME/Downloads/"), "download dir")
func main() {
flag.Parse()
var pl = netease.NewPlayList(*playlistID)
fi, err := os... |
// ReadAppsInfo
package main
import (
_ "bytes"
"encoding/json"
"fmt"
"internal/syscall/windows/registry"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"unsafe"
)
var (
kernel32 = syscall.NewLazyDLL("kernel32.dll")
GetModuleFileNameProc = kernel32.NewProc("GetModuleFi... |
// Package main implements a client for Greeter service.
package main
import (
"context"
"flag"
"fmt"
"log"
"time"
"google.golang.org/grpc"
pb "google.golang.org/grpc/examples/helloworld/helloworld"
"google.golang.org/grpc/peer"
_ "google.golang.org/grpc/xds/experimental"
)
var (
address = flag.String("ad... |
package objects
// NodeStatistics is the structure for node statistics
type NodeStatistics struct {
ID uint `json:"id"`
Type string `json:"type"`
Name string `json:"name"`
Status string `json:"status"`
ErrMsg string `json:"errMsg"`
St... |
package main
import (
"fmt"
)
func ReverseInt(n int) int {
// 出力する数値の変数を宣言
new_int := 0
// 引数が0より大きい間のforループを作成
for n > 0 {
// 引数を10で割った余りを変数reminderに格納
reminder := n % 10
// 出力用の変数を10倍にする
new_int *= 10
// 出力用の変数にreminderを足す
new_int += reminder
// 引数を10で割る
n /= 10
}
// 出力用の変数をreturnする
return ... |
package rp_kit
import (
"github.com/go-redis/redis"
"github.com/go-xorm/xorm"
"github.com/limitedlee/microservice/common/config"
"testing"
)
func Test_NewRedisEngine(t *testing.T) {
type args struct {
dsn string
}
tests := []struct {
name string
args args
}{
{
name: "创建redis连接",
args: args{dsn: ... |
package main
import (
goflag "flag"
"fmt"
"html/template"
"log"
"net/http"
"os"
"github.com/ricoberger/sealed-secrets-web/pkg/secrets"
"github.com/ricoberger/sealed-secrets-web/pkg/version"
"github.com/bitnami-labs/flagenv"
"github.com/bitnami-labs/pflagenv"
flag "github.com/spf13/pflag"
_ "k8s.io/client... |
package main
import (
// 如果需要用到不同目录的go方法,则需要导入相应包
"calc"
"fmt"
)
func init() {
fmt.Println("main init...")
}
func main() {
// 对于不同目录下的go方法,只能调用首字母为大写的方法
a := calc.Add(10, 20)
fmt.Println("a = ", a)
b := calc.Minus(20, 10)
fmt.Println("b = ", b)
// 对于同目录下的go方法,可以直接调用
test()
// 结果为:
// calc init...
//... |
package email
type Action struct {
Message string
Button Button
}
|
package namecheap
import (
"bytes"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"strconv"
"github.com/hashicorp/go-cleanhttp"
)
var (
debug = os.Getenv("DEBUG") != ""
)
const (
namecheapApiUrl = "https://api.namecheap.com/xml.response"
sandboxApiUrl = "https://api.sandbox.namecheap... |
package bstest
import (
. "gx/ipfs/QmbgbNxC1PMyS2gbx7nf2jKNG7bZAfYJJebdK4ptBBWCz1/go-blockservice"
mockrouting "gx/ipfs/QmRJvdmKJoDcQEhhTt5NYXJPQFnJYPo1kfapxtjZLfDDqH/go-ipfs-routing/mock"
delay "gx/ipfs/QmUe1WCHkQaz4UeNKiHDUBV2T6i9prc3DniqyHPXyfGaUq/go-ipfs-delay"
bitswap "gx/ipfs/QmYJ48z7NEzo3u2yCvUvNtBQ7wJWd5d... |
package poly
import (
"fmt"
"github.com/renproject/secp256k1"
"github.com/renproject/shamir/shamirutil"
)
// Poly represents a polynomial in the field defined by the elliptic curve
// secp256k1. That is, the field of integers modulo n where n is the order of
// the secp256k1 group.
//
// A Poly can be indexed int... |
/*
* Copyright (c) 2020 - present Kurtosis Technologies LLC.
* All Rights Reserved.
*/
package testsuite
/*
An interface which the user implements to register their tests.
*/
type TestSuite interface {
// Get all the tests in the test suite; this is where users will "register" their tests
GetTests() map[string]... |
/*
A word nest is created by taking a starting word, and generating a new string by placing the word inside itself. This process is then repeated.
Nesting 3 times with the word "incredible":
start = incredible
first = incre|incredible|dible
second = increin|incredible|credibledible
third = increinincr|incredible|... |
// Package robo is a set of utils for exploring unknown areas
package robo
|
// Package logutil contains functionality for working with logs.
package logutil
|
package utils
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test_Set(t *testing.T) {
set := NewStringSet()
assert.Equal(t, 0, len(set.Iter()))
assert.False(t, set.Contains("test"))
set.Add("test")
assert.True(t, set.Contains("test"))
set.Add("test")
assert.Equal(t, 1, len(set.Iter()))
s... |
package utils
import (
"fmt"
"github.com/fatih/color"
"os"
)
func PrintErrorAndExit(message string) {
color.Set(color.FgRed)
fmt.Println(message)
color.Unset()
os.Exit(1)
}
|
package golog
//发布日志类消息
// "errors"
type messageQueue struct {
// messagequeue.Base
}
type PushType struct {
Appid string
LogId string
LogTime string
LogText string
LogLevel LogLevel
}
func newMessageQueueInstance() *messageQueue {
messageQueue := &messageQueue{}
return messageQueue
}
func (this *... |
package cmd
import (
"fmt"
"github.com/spf13/cobra"
"iboxctl/pkg/root"
"iboxctl/pkg/tools"
"iboxctl/pkg/udpsend"
)
var(
stop = make(chan struct{})
ch string
ip string
ipCmd = &cobra.Command{
Use: "start",
Short: "start server",
RunE: func(c *cobra.Command, args []string) error {
tools.P... |
/*
* This file is part of impacca. Copyright (C) 2013 and above Shogun <shogun@cowtech.it>.
* Licensed under the MIT license, which can be found at https://choosealicense.com/licenses/mit.
*/
package utils
import (
"bufio"
"fmt"
"io"
"os"
"os/exec"
"regexp"
"strings"
"sync"
"syscall"
)
var debugMatcher =... |
/*
* Get the details of a specific network in a given data center for a given account.
*/
package main
import (
"flag"
"fmt"
"os"
"path"
"strings"
"github.com/grrtrr/clcv2"
"github.com/grrtrr/clcv2/clcv2cli"
"github.com/grrtrr/clcv2/utils"
"github.com/grrtrr/exit"
"github.com/olekukonko/tablewriter"
)
fu... |
package boltdb
import (
"github.com/coreos/bbolt"
. "github.com/smartystreets/goconvey/convey"
"io/ioutil"
"testing"
)
func init() {
Open("../db/test.db")
}
func TestKeys(t *testing.T) {
keys, err := Keys("test")
if err != nil {
t.Fatal("get keys err, ", err)
}
t.Log(keys)
}
func TestGet(t *testing.T) {
... |
package controllers
import (
"crypto/sha1"
"fmt"
"log"
"mick/models"
"net/http"
"text/template"
"github.com/jinzhu/gorm"
)
func CreateAdmin(db *gorm.DB) {
var admin models.Admin
if db.Find(&admin).RecordNotFound() {
var pseudo string
var password string
var result string
var shaPassword []byte
fm... |
package slice
// 数组类型的值(以下简称数组)的长度是固定的,而切片类型的值(以下简称切片)是可变长的。
import (
"strconv"
"reflect"
"fmt"
"testing"
)
// func GetArrayLen
func TestGetArrayLen(t* testing.T){
s1 := make([]int,5)
fmt.Printf("The length of s1:%d\n",len(s1))
fmt.Printf("The capacity of s1:%d\n",cap(s1))
fmt.Printf("The value of s1:%d\n",s... |
package p2p
import (
"fmt"
"github.com/hashicorp/memberlist"
"github.com/jlingohr/p2pvstream/fileutil"
"github.com/jlingohr/p2pvstream/hls"
"github.com/jlingohr/p2pvstream/message"
"github.com/jlingohr/p2pvstream/settings"
"github.com/jlingohr/p2pvstream/streaming"
"github.com/jlingohr/p2pvstream/stringutil"
... |
package main
import (
"flag"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"strconv"
)
type Flags struct {
dest *string
addr *string
id *int
seek *int
chunk *int
}
const Boundary = "DellvinBlackDellvinBlackDellvinBlackDellvinBlack"
func main() {
f := setupCLArgs()
if f.addr == nil || f.id == nil {
r... |
package main
import (
"context"
"crypto/rand"
"crypto/tls"
"encoding/binary"
"flag"
"fmt"
"io"
"os"
"github.com/hawkinsw/qperf/utils"
quic "github.com/lucas-clemente/quic-go"
)
const k = 1024
func transmit(done <-chan struct{}, bufferSize uint64, stream *quic.Stream) {
sendBuffer := make([]byte, bufferSi... |
package middleware
import (
"fmt"
log "proximity/pkg/utils/logger"
"github.com/gin-gonic/gin"
pkgErrors "github.com/pkg/errors"
)
// HandlePanic ... rest panic handler
func HandlePanic(c *gin.Context) {
defer func(c *gin.Context) {
r := recover()
var stackTrace string
if r != nil {
err, ok := r.(error)... |
package log
import (
"log"
"github.com/b2wdigital/goignite/pkg/config"
)
const (
ConsoleEnabled = "log.console.enabled"
ConsoleLevel = "log.console.level"
FileEnabled = "log.file.enabled"
FileLevel = "log.file.level"
FilePath = "log.file.path"
FileName = "log.file.name"
FileMaxSize ... |
package job
// The different states that a job can be in.
const (
StateNew = "new"
StateQueued = "queued"
StateInProgress = "in progress"
StateComplete = "complete"
StateError = "error"
StatePassed = "passed"
StateFailed = "failed"
)
// DoneStates represents states that a job doesn't transit... |
package utils
import (
"os"
"log"
)
var InfoLog *log.Logger
var ErrorLog *log.Logger
var DebugLog *log.Logger
var LogFile *os.File
func InitLogger() {
InfoLog = log.New(os.Stdout, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile)
ErrorLog = log.New(os.Stdout, "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile)
DebugL... |
package service
import (
"crypto/md5"
"errors"
"fmt"
"hash"
"math/big"
"net"
"strconv"
"strings"
"github.com/ms2008/poemoon/conf"
"github.com/ms2008/poemoon/utils"
)
const (
_codeIn = byte(0x03)
_codeOut = byte(0x06)
_type = byte(0x01)
_eof = byte(0x00)
_controlCheck = byte... |
package scanner
import (
"go/token"
"h12.io/gombi/experiment/gre/scan"
)
const (
tNewline = 1000 + iota
tWhitespace
tLineComment
tGeneralCommentSL
tGeneralCommentML
tRawStringLit
tInterpretedStringLit
tSkip
)
var (
c = scan.Char
s = scan.Str
con = scan.Con
or = scan.Or
merge = scan.Merge... |
package main
import (
"flag"
"fmt"
"io"
"net"
"os"
)
type Client struct {
ServerIP string
ServerPort int
Name string
conn net.Conn
flag int //当前client模式
}
func NewClient(serverIP string,serverPort int) *Client{
client := &Client{
ServerIP: serverIP,
ServerPort: serverPort,
flag: 999,
}
//连接服务器
... |
package match
import (
t "testing"
e "github.com/briancraig/game-server/match/entity"
)
//TestCanIAddSomePlayers assures that we can add players
func TestCanIAddSomePlayers(t *t.T) {
p1 := e.New()
p2 := e.New()
team := NewTeam()
team.Add(p1)
team.Add(p2)
if team.Size() != 2 {
t.Fatal("el tamaño del equipo ... |
package main
// Expects blockartlib.go to be in the ./blockartlib/ dir, relative to
// this art-app.go file
import "./blockartlib"
import "bufio"
import "fmt"
import "os"
import "crypto/ecdsa"
func main() {
minerAddr := "127.0.0.1:8081"
privKeyString := "3081a40201010430abb996d825e0a92b470d34f506eca5294a9198922ca4... |
package xclient
import (
"math"
"math/rand"
"sync"
"time"
)
type SelectMode int
const (
RandomSelect SelectMode = iota
RoundRobinSelect
)
// Refresh 从注册中心更新服务列表
// Update 手动更新服务列表
// Get 根据负载均衡策略,选择一个服务实例
type Discovery interface {
Refresh() error
Update(servers []string) error
Get(mod SelectMode) (string... |
package metadata
import (
"incognito-chain/common"
"incognito-chain/privacy"
)
type ReturnStakingMetadata struct {
MetadataBase
TxID string
StakerAddress privacy.PaymentAddress
SharedRandom []byte
}
func NewReturnStaking(txID string, producerAddress privacy.PaymentAddress, metaType int, ) *ReturnStaki... |
package main
import (
"fmt"
"github.com/hjcian/ds/stack"
)
func main() {
a := stack.NewItemStack()
fmt.Println(123)
a.Push(123)
a.Push(456)
a.Push(789)
fmt.Println("init: ", a)
b := a.Pull()
fmt.Println("pull: ", b)
c := a.Pull()
fmt.Println("pull: ", c)
d := a.Pull()
fmt.Println("pull: ", d)
e := a.Pu... |
package mocks
import (
"github.com/MagalixCorp/magalix-agent/v3/entities"
"github.com/MagalixCorp/magalix-agent/v3/kuber"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)
type EntitiesWatcherMock struct {
Entities map[kuber.GroupVersionResourceKind][]unstructured.Unstructured
Parents map[string]*kuber.Pare... |
// Copyright (C) 2015 Scaleway. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.md file.
package cli
import "fmt"
// CommandListOpts holds a list of parameters
type CommandListOpts struct {
Values *[]string
}
// NewListOpts create an empty Comm... |
package solutions
/*
* @lc app=leetcode id=204 lang=golang
*
* [204] Count Primes
*/
/*
Your runtime beats 65.27 % of golang submissions
Your memory usage beats 50.3 % of golang submissions (12.8 MB)
*/
// @lc code=start
func countPrimes(n int) int {
if n == 0 || n == 1 {
return 0
}
np := make([]bool, n+1)
... |
package tests
import (
"github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/balance"
"github.com/iotaledger/wasp/packages/coretypes"
"github.com/iotaledger/wasp/packages/kv/codec"
"github.com/iotaledger/wasp/packages/solo"
"github.com/stretchr/testify/require"
"testing"
)
var incFile = "wasm/inccounte... |
package profilopedia
import "fmt"
type Profile struct {
}
|
package utils
import (
"github.com/bwmarrin/discordgo"
"os"
"strings"
)
func IsCanUseOpCommand(user *discordgo.User) bool {
l := os.Getenv("DISCORD_BOT_OP_LIST")
list := strings.Split(l, ",")
for _, v := range list {
if v == user.ID {
return true
}
}
return false
}
|
package c26_ctr_bitflipping
import (
"math/rand"
"testing"
"time"
)
func TestExploitAdmin(t *testing.T) {
key := make([]byte, 16)
rand.Seed(time.Now().UnixNano())
rand.Read(key)
enc := DefaultEnc(key)
isAdmin, err := ExploitAdmin(enc)
if err != nil {
t.Fatalf("Exploit error: %s\n", err)
}
if !isAdmin {
... |
package pathfileops
import "testing"
func TestFileOpsCollection_InsertFileOpsAtIndex_01(t *testing.T) {
sf := make([]string, 5, 10)
sf[0] = "../../filesfortest/levelfilesfortest/level_0_0_test.txt"
sf[1] = "../../filesfortest/levelfilesfortest/level_0_1_test.txt"
sf[2] = "../../filesfortest/levelfilesfortest... |
package command
import (
"github.com/ross-weir/gort/pkg/config"
"github.com/spf13/cobra"
)
type Runner struct {
rootCmd *cobra.Command
version, commit, date string
cfg *config.Config
}
func NewRunner(version, commit, date string) *Runner {
r := &Runner{
version: version,
com... |
package crypto
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"math/big"
)
/**
See https://asecuritysite.com/encryption/goecdh
*/
var curve = elliptic.P256()
func GenECDHPrivKey() (*ecdsa.PrivateKey, error) {
// Todo: Generate ecdh key in the TPM or at least use randomness generated ... |
package main
import(
"fmt"
"strings"
"sort"
"strconv"
)
type sortRunes []rune
func (s sortRunes) Less(i, j int) bool {
return s[i] < s[j]
}
func (s sortRunes) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s sortRunes) Len() int {
return len(s)
}
func SortString(s string) string {
r := []run... |
package cdkey
import (
"math/rand"
"strconv"
"strings"
"time"
pkgBean "webapi/bean"
)
const letterBytes = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
const (
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterId... |
//go:build go1.18
package parquet_test
import (
"sort"
"testing"
"github.com/segmentio/parquet-go"
)
func TestDedupeRowReader(t *testing.T) {
type Row struct {
Value int32 `parquet:"value"`
}
rows := make([]Row, 1000)
for i := range rows {
rows[i].Value = int32(i / 3)
}
dedupeMap := make(map[Row]stru... |
package core
//go:generate string -type=ModeState
type ModeState uint8
type InputData struct {
Mode ModeState
PrivateKey string
PublicKey string
}
type RawInputData struct {
Mode string
State ModeState
PrivateKey string
PublicKey string
}
|
package main
import (
"fmt"
"git.code.oa.com/fip-team/fiorm"
"github.com/gin-gonic/gin"
"github.com/spf13/viper"
"os"
"xinxin/service/util"
log "github.com/sirupsen/logrus"
)
//go:generate db2struct.exe -host=119.29.87.223 -port=3306 -dbname=shichang -user=root -password=dceb66c7d2408b87f9cb5bcbd16316f59c1ddf0... |
package server
import (
"context"
golog "log"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/henglory/Demo_Golang_v0.0.1/config"
"github.com/henglory/Demo_Golang_v0.0.1/service"
)
type errorResponse struct {
StatusCode int64 `json:"statusCode"`
StatusDesc string `json:"statusDesc"`
Request st... |
package ch05
// Give a list of 0's, 1's and 2's, write a program to separate 0's, 1's and 2's.
func Separate_0_1_2(in []int) (zeros, ones, twos int) {
for _, val := range in {
if val == 0 {
zeros++
} else if val == 1 {
ones++
} else {
twos++
}
}
return zeros, ones, twos
}
|
package types
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
)
var _ paramtypes.ParamSet = &Params{}
// Parameter keys
var (
KeyOracleRelayers = []byte("OracleRelayers")
)
// ParamKeyTable returns the parameter key table.
func ParamKeyTable() par... |
package pgsql
import (
"database/sql"
"database/sql/driver"
"time"
)
// DateRangeArrayFromTimeArray2Slice returns a driver.Valuer that produces a PostgreSQL daterange[] from the given Go [][2]time.Time.
func DateRangeArrayFromTimeArray2Slice(val [][2]time.Time) driver.Valuer {
return dateRangeArrayFromTimeArray2S... |
package model
type Holder struct {
UserName string `json:"userName" bson:"userName"`
SerialNum string `json:"serialNum" bson:"serialNum"`
CertificateName string `json:"certificateName" bson:"certificateName"`
IssueTime string `json:"issueTime" bson:"issueTime"`
IssuingUnit string `json:"iss... |
package committer_test
import (
"fmt"
"github.com/TangoEnSkai/committer-go/committer"
"testing"
)
func TestCheckLength(t *testing.T) {
const (
minLength = 10
maxLength = 60
shortCommit = "short"
validLengthCommit = "the commit length is good enough"
longCommit = "this commit... |
package entity
type QueryLoanListItem struct {
// 贷款日期
XdCol4 int `db:"xd_col4" json:"xd_col4" field:"xd_col4"`
// 到期日期
XdCol5 int `db:"xd_col5" json:"xd_col5" field:"xd_col5"`
// 贷款金额
XdCol6 int `db:"xd_col6" json:"xd_col6" field:"xd_col6"`
// 结欠金额
XdCol7 int `db:"xd_col7" json:"xd_col7" field:"xd_col7"`
}
|
package provider
import (
"time"
res "github.com/lucasvmiguel/goauth/auth/resource"
)
var (
expireAccessDatetime = time.Now().Add(24 * time.Hour) //1 day
expireRefreshDatetime = time.Now().Add(8760 * time.Hour) //1 year
tokenType = "Bearer"
)
//Provider should be implement by any provider (map, db... |
package main
import (
"testing"
)
func TestShortestDistance(t *testing.T) {
var Neighborhood = []Street{
Street{From: "Kruthika's abode", To: "Mark's crib", Distance: 9},
Street{From: "Kruthika's abode", To: "Greg's casa", Distance: 4},
Street{From: "Kruthika's abode", To: "Matt's pad", Distance: 18},
Stree... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-08-07 09:41
# @File : lt_155_Min_Stack_test.go.go
# @Description :
# @Attention :
*/
package stack
import (
"fmt"
"testing"
)
func TestMinStack_GetMin(t *testing.T) {
stack := Constructor()
stack.Push(-2)
stack.Push(0)
stack.Push(-3)
fmt.Println(stack... |
// Copyright (c) 2020 Cisco and/or its affiliates.
//
// SPDX-License-Identifier: Apache-2.0
//
// 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/LICE... |
/*
Copyright 2020-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, ... |
package mutex_learn
import (
"fmt"
"math/rand"
"sync"
"sync/atomic"
"testing"
"time"
"unsafe"
)
// 复制Mutex定义的常量
const (
mutexLocked = 1 << iota // 加锁标识位置
mutexWoken // 唤醒标识位置
mutexStarving // 锁饥饿标识位置
mutexWaiterShift = iota // 标识waiter的起始bit位置
)
// 扩展一个Mutex结构
type Mutex struct {
s... |
package merrors
const (
ERR_OCT_SUCCESS = iota
ERR_DB_ERR
ERR_NOT_ENOUGH_PARAS
ERR_TOO_MANY_PARAS
ERR_UNACCP_PARAS
ERR_CMD_ERR
ERR_COMMON_ERR
ERR_SEGMENT_NOT_EXIST
ERR_SEGMENT_ALREADY_EXIST
ERR_TIMEOUT
ERR_SYSCALL_ERR
ERR_SYSTEM_ERR
ERR_NO_SUCH_API
ERR_NOT_IMPLEMENTED
// User
ERR_USER_NOT_EXIST
ERR_U... |
package controller
import (
"github.com/patrickeasters/ipa-cert-operator/pkg/controller/ipacert"
)
func init() {
// AddToManagerFuncs is a list of functions to create controllers and add them to a manager.
AddToManagerFuncs = append(AddToManagerFuncs, ipacert.Add)
}
|
package main
import (
"log"
"html/template"
"fmt"
"net/http"
)
func helloWorld(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello World")
}
func login(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method)
if r.Method == "GET" {
//template.ParseFiles("")創建模板回傳到t 並解析文本""
... |
package main
import "testing"
func BenchmarkFib(b *testing.B) {
for i := 0; i < b.N; i++ {
fib(30)
}
}
|
package endpoints
import (
"encoding/json"
"github.com/pquerna/ffjson/ffjson"
"github.com/valyala/fasthttp"
"log"
"technodb-final/app/dbhandlers"
"technodb-final/app/models"
)
func UserCreate(ctx *fasthttp.RequestCtx) {
var user models.User
nickname := ctx.UserValue("nickname").(string)
user.Nickname = &nick... |
package main
type Entity struct {
name string
glyph *Glyph
world *World
position *Point
}
func (entity *Entity) Move(point *Point) {
entity.position = point
}
// func (entity *Entity) MoveBy(offset ...int) {
// entity.position = entity.position.Add(offset...)
// }
func NewEntity(name string) *Entity {
re... |
package main
import "fmt"
func Demo() {
fmt.Println("HI")
}
|
/*
* @lc app=leetcode id=102 lang=golang
*
* [102] Binary Tree Level Order Traversal
*
* https://leetcode.com/problems/binary-tree-level-order-traversal/description/
*
* algorithms
* Medium (50.99%)
* Likes: 1966
* Dislikes: 54
* Total Accepted: 467.3K
* Total Submissions: 916.3K
* Testcase Example: ... |
/*
Take the code from the previous exercise, then store the values of type person in a map
with the key of last name. Access each value in the map. Print out the values, ranging over the slice.
*/
package main
import "fmt"
type person struct {
firstname string
lastname string
favorite... |
package webscraper
import (
"fmt"
"testing"
)
func TestGetLinksWithDivClass(t *testing.T) {
// GIVEN
pageStr := `
<html>
<head>
<title>THIS IS THE TITLE</title>
</head>
<body>
<div class="product ">
<div class="productInner">
<div class="productInfoWrapper">
<div class="productInfo">
<h3>
... |
// 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... |
package router
import (
"fmt"
"gopkg.in/macaron.v1"
"gopkg.in/mgo.v2/bson"
"qiniupkg.com/x/log.v7"
"tech/model"
"tech/modules/page"
)
// 首页的所有视频
func All(ctx *macaron.Context) {
var serieses []model.Series
var err error
err = page.Page(ctx, model.SERIES, &bson.M{}, &serieses)
if err != nil {
ctx.Data["mes... |
package utils
import (
"fmt"
"net/http"
)
func Render(w http.ResponseWriter, r *http.Request, filename string, props interface{}) {
tmpl := templates[filename]
if tmpl != nil {
data := r.Context().Value("data")
if data != nil {
for k, v := range *data.(*Props) {
(*props.(*Props))[k] = v
}
}
if... |
package main
import (
"bufio"
"encoding/json"
"flag"
"log"
"net/http"
"os"
"strings"
"sync"
"github.com/hpcloud/tail"
"github.com/miekg/dns"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/abh/geodns/countries"
"github.com/abh/geodn... |
package router
import (
"context"
"fmt"
"net/http"
"github.com/julienschmidt/httprouter"
)
// Make sure the Router conforms with the Router interface
var _ Router = newMuxHTTPRouter(context.Background())
type muxHTTPRouter struct {
ctx context.Context
mux *httprouter.Router
}
func newMuxHTTPRouter(ctx contex... |
package servers
type UpdatePublicIpAddressReq struct {
Ports []PortDef
SourceRestrictions []SourceRestrictionDef
}
type PortDef struct {
Protocol string
Port int
PortTo int
}
type SourceRestrictionDef struct {
Cidr string
}
|
package model
type Discards struct {
Cards
}
func (up *Discards) Put(c Card) {
up.Cards = append(up.Cards, c)
}
|
package udig
import (
"github.com/stretchr/testify/assert"
"testing"
)
func Test_DissectDomainsFrom_By_simple_domain(t *testing.T) {
// Execute.
domains := dissectDomainsFromString("example.com")
// Assert.
assert.Len(t, domains, 1)
assert.Equal(t, "example.com", domains[0])
}
func Test_DissectDomainsFrom_By... |
package node
import (
"github.com/sherifabdlnaby/prism/app/component"
"github.com/sherifabdlnaby/prism/pkg/job"
"go.uber.org/zap"
)
type core interface {
process(j job.Job)
processStream(j job.Job)
}
func newBase(id ID, core core, async bool, nexts []Next,
createAsync createAsyncFunc, jobChan <-chan job.Job, r... |
package carbon
import (
"testing"
"time"
"github.com/Kretech/xgo/test"
)
func TestUnixOf(t *testing.T) {
In(Shanghai)
test.AssertEqual(t, UnixOf(0, 0).Format("Y-m-d H:i:s"), "1970-01-01 08:00:00")
In(time.UTC)
test.AssertEqual(t, UnixOf(0, 0).In(Shanghai).Format("Y-m-d H:i:s"), "1970-01-01 08:00:00")
test.A... |
package pie_test
import (
"github.com/elliotchance/pie/v2"
"github.com/stretchr/testify/assert"
"testing"
)
func TestInts(t *testing.T) {
assert.Equal(t, []int(nil), pie.Ints([]int(nil)))
assert.Equal(t,
[]int{92, 823, 453},
pie.Ints([]float64{92.384, 823.324, 453}))
}
|
package gsysint
import (
"unsafe"
)
/*
* defined constants
*/
const (
// G status
//
// If you add to this list, add to the list
// of "okay during garbage collection" status
// in mgcmark.go too.
_Gidle = iota // 0
_Grunnable // 1 runnable and on a run queue
_Grunning ... |
package common
import (
"bytes"
"io"
"sync"
"github.com/sirupsen/logrus"
)
// LogTracer traces log output.
type LogTracer struct {
buffer *bytes.Buffer
writer io.Writer
mutex sync.Mutex
tracers []io.Writer
}
// NewLogTracer creates a LogTracer.
func NewLogTracer(id string, tracers ...io.Writer) *LogTrac... |
// Copyright 2018 The Netstack Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build linux,!amd64
package rawfile
import (
"syscall"
"unsafe"
)
func blockingPoll(fds *pollEvent, nfds int, timeout int64) (int, syscall.Errno) ... |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
package accounts
import (
"github.com/iotaledger/wasp/packages/coretypes/coreutil"
"github.com/iotaledger/wasp/packages/hashing"
)
const (
Name = "accounts"
description = "Chain account ledger contract"
)
var (
Interface = &coreutil.ContractInterface{
Name: Name,
Description: description,
Pr... |
package main
//region Usings
import "github.com/ravendb/ravendb-go-client"
//endregion
var globalDocumentStore *ravendb.DocumentStore
func main() {
createDocumentStore()
editDocument("newCompanyName")
globalDocumentStore.Close()
}
func createDocumentStore() (*ravendb.DocumentStore, error) {
if globa... |
package main
import (
"fmt"
"math/rand"
"time"
)
type Metric string
// BulkUploadMessages will batch up to 10 messages from ch and send
// them to upload(). Rather than block for all 10 messages, it will
// call upload() directly with any number of Metrics if ch is empty.
func BulkUploadMessages(ch <-chan Metric... |
// @Description rbac中间件
// @Author jiangyang
// @Created 2020/11/17 11:32 上午
package middlewares
import (
"net/http"
"github.com/gin-gonic/gin"
core "github.com/comeonjy/util/ctx"
"github.com/comeonjy/util/errno"
"github.com/comeonjy/util/jwt"
"github.com/comeonjy/util/tool"
)
func Rbac(checkFunc fun... |
//一个简单的web服务
package main
import (
"net/http"
)
//请求相应
func hello66(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Content-Type", "text/plain")
res.Write([]byte("Hello world\n"))
}
func main() {
//将hello66负责相应/路径的请求
http.HandleFunc("/", hello66)
//绑定端口5000
http.ListenAndServe(":... |
package bmc
import (
pb "github.com/stopa323/kimbap/api/bmc"
)
func ConvertGofishPowerStateToProto(status string) pb.PowerStatus {
switch status {
case "On":
return pb.PowerStatus_ON
case "Off":
return pb.PowerStatus_OFF
case "PoweringOn":
return pb.PowerStatus_POWERING_ON
case "PoweringOff":
return pb.... |
package linkedlist
func mergeTwoLists1(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
var newList, r *ListNode
if l1.Val <= l2.Val {
r = l1
l1 = l1.Next
} else {
r = l2
l2 = l2.Next
}
newList = r
for l1 != nil && l2 != nil {
if l1.Val <= l2.Val ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.