text stringlengths 11 4.05M |
|---|
package main
import (
"flag"
"fmt"
"github.com/simisimis/genrefinder/auth"
"github.com/simisimis/genrefinder/elastic"
"github.com/simisimis/genrefinder/spotify"
"github.com/sirupsen/logrus"
)
var log = logrus.WithField("pkg", "main")
type genreDesc struct {
Repeats int `json:"repeats"`
Artists []string... |
package store
type Store interface {
SetValue(path, value string) error
Value(path string) string
Values(path string) map[string]string
Delete(path string) error
}
|
// +build k3s
package k8s
import (
"context"
"fmt"
"os"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/kubernetes/cmd/server"
)
func getEmbedded(ctx context.Context) (bool, context.Context, *rest.Config, error) {
sc, ok := ctx.Value(serverConfig).(*server.ServerConfig)
if !ok {
return ... |
package main
import "fmt"
func main() {
fmt.Println("Welcome to fun game.")
fmt.Println("You think of a number and I'll try to guess it.")
for {
fmt.Print("Is it 7? ")
var answer string
fmt.Scanf("%s", &answer)
if answer == "yes" {
fmt.Println("Yay, I win!")
break
}
}
}
|
// Copyright 2021 BoCloud
//
// 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 wri... |
package main
import "math"
//dp 从右下角往上推,注意处理最后一行和最后一列,类似于64号问题
//dp[i][j]表示在i j位置需要的最小血量
func calculateMinimumHP(dungeon [][]int) int {
m := len(dungeon)
n := len(dungeon[0])
dp := make([][]int, m)
for i := 0; i < m; i++ {
dp[i] = make([]int, n)
}
for i := m - 1; i >= 0; i-- {
for j := n - 1; j >= 0; j-- {
... |
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agre... |
// Copyright © 2017 Will Demaine
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, di... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//78. Subsets
//Given a set of distinct integers, nums, return all possible subsets (the power set).
//Note: The solution set must not contain duplicat... |
package wsutils
import (
"fmt"
"io"
"log"
"net"
"net/http"
"net/url"
"strings"
)
//ReverseProxy implements http.HandlerFunc to reverse proxy websocket requests
type ReverseProxy struct {
Target string
}
//NewReverseProxy creates a new websocket reverse proxy
func NewReverseProxy(url *url.URL) *ReverseProxy {... |
package controllers
func (s *Server) initializeRoutes() {
//Users routes
s.Router.HandleFunc("/users", (s.CreateUser)).Methods("POST")
s.Router.HandleFunc("/usersSelect", (s.CreateUserSelect)).Methods("POST")
s.Router.HandleFunc("/users", (s.GetUsers)).Methods("GET")
s.Router.HandleFunc("/users/{id}", (s.GetUser)... |
package test
import (
"GoldenTimes-web/models"
"fmt"
"testing"
"time"
"github.com/astaxie/beego/orm"
)
//func TestAlbum(t *testing.T) {
// fmt.Println("TestAlbum()")
// album := new(models.Album)
// album.Name = "ABC"
// fmt.Println("album:", album)
// fmt.Println("album.Name:", album.Name)
// fmt.Println("a... |
package input
import (
"github.com/gilliek/go-opml/opml"
"github.com/jutkko/mindown/util"
)
func ParseOpml(filename string) (*util.Graph, error) {
doc, err := opml.NewOPMLFromFile(filename)
if err != nil {
return nil, err
}
result := &util.Graph{}
for _, outline := range doc.Body.Outlines {
result.AddNode... |
/*
Core components of the App. Used in many others components.
Can depend on Config, Helpers and external packages.
Often contain stores of some items like URL routes or CLI commands.
*/
package sys
|
/*
Copyright © 2020 Roj Vroemen <me@rojvroemen.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publis... |
package dto
import "Project/models"
type Questions struct {
Id int
Question string
Options []models.Options
}
|
package chain
import "time"
// MaxSyncWaitTime sets how long we'll wait after a new connection to receive new beacons
// from one peer
var MaxSyncWaitTime = 2 * time.Second
|
package routes
import (
"github.com/gofiber/fiber/v2"
"ocg.com/train/controller"
)
func ConfigBookRouter(router *fiber.Router) {
(*router).Get("/books", controller.GetAllBooks)
(*router).Post("/books", controller.CreateNewBook)
(*router).Get("/books/:id", controller.GetBookById)
(*router).Delete("/books/:id", c... |
package handler
import (
"net/url"
"fmt"
)
func UrlBuilderQuery(searchTerm string) string {
baseUrl, err := url.Parse("https://www.mercari.com/search/")
if err != nil {
fmt.Println("Malformed URL: ", err.Error())
}
q := baseUrl.Query()
q.Set("keyword", searchTerm)
baseUrl.RawQuery = q.Encode()
urlAsString... |
package testdata
type IpaddrRespStruct struct {
ID string
CreatedAt string
UpdatedAt string
DeletedAt *string
IPSegment string
IP string
Status int
Type int
Note string
}
var IpaddrResp = `{ id createdAt updatedAt deletedAt ip status type note }`
|
package sentinelm
import (
iconfig "github.com/colinrs/ffly-plus/internal/config"
sentinelAPI "github.com/alibaba/sentinel-golang/api"
"github.com/alibaba/sentinel-golang/core/config"
"github.com/alibaba/sentinel-golang/core/flow"
"github.com/alibaba/sentinel-golang/logging"
"github.com/colinrs/pkgx/logger"
)
... |
package inmemory
import (
"context"
"fmt"
"io/ioutil"
"log"
"github.com/imrenagi/go-payment"
"github.com/imrenagi/go-payment/config"
)
// NewPaymentConfigRepository creates payment configuration data source by reading
// a file located on `source`
func NewPaymentConfigRepository(source string) *PaymentConfigRe... |
package agent
import (
"context"
"time"
)
type RestartHandler func() error
type ChangeLogLevelHandler func(level *LogLevel) error
type ConstraintsHandler func(constraints []*Constraint) map[string]error
type AuditCommandHandler func() error
type Gateway interface {
Start(ctx context.Context) error
WaitAuthorizat... |
package writer
import (
//"fmt"
"github.com/goldeneggg/ipcl/lib/parser"
)
type defaultFormat struct {
source_cidr string
network string
mask string
min_address string
max_address string
board_cast string
}
var vals = []struct {
srcCIDR string
expected defaultFormat
}{
{"192.168.1.0/24", defau... |
// Copyright © 2018 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 createroom
// https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-createroom
type Reply struct {
RoomID string `json:"room_id"`
}
|
package leetcode
import "strings"
/**
偷懒法
*/
func strStr_lazy(haystack string, needle string) int {
return strings.Index(haystack, needle)
}
/**
sunday算法
*/
func StrStr_sunday(haystack string, needle string) int {
if needle == "" {
return 0
}
needleMap := map[int32]int{}
for i, c := range needle {
needleMap... |
package main
import (
"bb/cmd"
)
func main() {
cmd.Execute()
}
|
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-11-10 09:43
# @File : lt_532_K-diff_Pairs_in_an_Array.go
# @Description :
# @Attention :
*/
package two_points
|
package cloudflare
import "github.com/nitschmann/scdns/pkg/util/rest"
const (
BASE_URL = "https://api.cloudflare.com/client/v4/"
HTTP_CONTENT_TYPE = "application/json"
)
type Client struct {
*rest.Client
credentials *Credentials
DnsRecords DnsRecordsService
Zones ZonesService
}
func NewClient(... |
package response
import "encoding/json"
// Bool response struct
type Bool struct {
Value bool `json:"-"`
}
// MarshalJSON custom implementation
func (s *Bool) MarshalJSON() ([]byte, error) {
val := s.Value
return json.Marshal(&val)
}
|
package moveZeroes
import "testing"
func Test_moveZeroes(t *testing.T) {
type args struct {
nums []int
origin []int
}
tests := []struct {
name string
args args
}{
// TODO: Add test cases.
{
name: "first",
args: args{
nums: []int{1, 2, 3, 4, 5},
},
},
{
name: "second",
args: ar... |
package factories
import (
"database/sql"
"github.com/barrydev/api-3h-shop/src/common/connect"
"github.com/barrydev/api-3h-shop/src/connections"
)
func CountOrderItem(query *connect.QueryMySQL) (int, error) {
connection := connections.Mysql.GetConnection()
queryString := `
SELECT
COUNT(*)
FROM order_item... |
/*
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 topology // import "github.com/nathanaelle/wireguard-topology"
import (
"fmt"
"net"
"strconv"
"strings"
)
type (
Host struct {
Name string `json:"host"`
Templates []string `json:"templates"`
Iface string `json:"ifa... |
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use ... |
/*
* @lc app=leetcode.cn id=234 lang=golang
*
* [234] 回文链表
*/
// @lc code=start
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
package main
import "fmt"
type ListNode struct {
Val int
Next *ListNode
}
func isPalindrome(head *ListNode) bo... |
package endpoint
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/followedwind/slackbot/internal/util"
"github.com/slack-go/slack"
"github.com/slack-go/slack/slackevents"
"github.com/taketsuru-devel/gorilla-microserv... |
package main
import (
"fmt"
"os"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/dotabuff/yasha"
)
func getTickOffset(tick int, pretime float64, gametime float64) int {
var nowtime = gametime - pretime - 90
var tickoffset = float64(tick) - (nowtime * 30)
return int(tickoffset)
}
func timeToTick(time fl... |
package loadgen
import (
"bytes"
"context"
"fmt"
"github.com/facebookgo/httpdown"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"io/ioutil"
"log"
"net/http"
"path/filepath"
"sync"
"time"
)
type (
InstanceSum struct {
Instance string
Sum ... |
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... |
package informer
import (
"container/list"
"context"
"sync"
"time"
"github.com/QisFj/godry/run"
)
type ListAndWatch[ObjectContent any] interface {
List(ctx context.Context) ([]Object[ObjectContent], error)
Watch(ctx context.Context, cb Callback[ObjectContent], watchingNotifyCh chan<- struct{}) error
}
type C... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2021/12/16 9:41 上午
# @File : lt_24_两两交换链表中的节点.go
# @Description :
# @Attention :
*/
package hot100
// 关键: 使用dummy节点,用dummy来移动整个链表
// 每次交换都是交换dummy后的两个节点即可
func swapPairs(head *ListNode) *ListNode {
dummy := &ListNode{Next: head}
tmp := dummy
// tmp->1->2 => tm... |
package Framework
import (
. "framework/api/common"
"net/http"
)
//laser framework handler,inherit http.handler
type ILaserHandler interface {
http.Handler
ServerContext() *ServerContext
SetServerContext(*ServerContext)
}
//framework handler
type LaserHandler struct {
serverCtx *ServerContext
}
//implement th... |
package inventoryd
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/binary"
"errors"
"math/rand"
"time"
)
// DtlsHandshakeParams : Dtlsのハンドシェイクパラメータ
type DtlsHandshakeParams struct {
ServerSequence uint16
ClientSequence uint16
Identity []byte
Cookie []byte
Session []byt... |
package opencc
import (
"testing"
"io/ioutil"
"fmt"
"encoding/json"
"os"
"path/filepath"
"log"
"time"
)
//
func Test_config(t *testing.T){
fileName := `s2t.json`
body, err := ioutil.ReadFile(fileName)
if err != nil{
fmt.Println(err)
return
}
var conf *Config
err = json.Unmarshal(body, &conf)
if err ... |
package binance
import (
"github.com/stretchr/testify/suite"
"testing"
"time"
)
type convertTradeTestSuite struct {
baseTestSuite
}
func TestConvertTradeService(t *testing.T) {
suite.Run(t, new(convertTradeTestSuite))
}
func (s *convertTradeTestSuite) TestConvertTradeHistory() {
data := []byte(`{
"list": ... |
package otf
// Open Font Format Standard section 4.3
type (
BYTE uint8
CHAR int8
USHORT uint16
SHORT int16
UINT24 [3]uint8
ULONG uint32
LONG int32
FIXED int32
FWORD int16
UFWORD uint16
F2DOT14 int16
LONGDATETIME int64
TAG ... |
package main
import (
hybrid "github.com/joshgav/az-profiles/go/hybrid/cmd"
latest "github.com/joshgav/az-profiles/go/latest/cmd"
)
func main() {
hybrid.Execute()
latest.Execute()
}
|
package main
//Creating a custom type and declaring a variable 'x' of this type as done before
//Declaring a variable 'y' of type 'int' and assigning a value to it
//by conversion of variable 'x' into type 'int'
import "fmt"
type question int
var x question
var y int
func main() {
fmt.Println(x)
fmt.Printf("%T\n... |
package ch1
import (
"log"
"time"
)
func producer(factor int, out chan<- int) {
for i := 0; ; i++ {
time.Sleep(500 * time.Millisecond)
out <- i * factor
}
}
func consumer(in <-chan int) {
for data := range in {
log.Println(data)
}
}
func consumerAndProducer(bufferSize int, closeSign <-chan struct{}) {
... |
package common
import "fmt"
// APIError defines a standard format for API errors.
type APIError struct {
// The status code.
Status int `json:"status"`
// The description of the API error.
Description string `json:"description"`
// The token uniquely identifying the API error.
ErrorCode string `json:"errorCode"... |
/*
In almost every row nowadays, the people tends to order themselves as militaries would do.
Challenge
Suppose 4 people where:
person 1 has priority against person 2, 3 and 4,
person 2 has priority against person 3 and 4,
person 3 has priority against person 4,
person 4 has the lowest priority.
The... |
package handlers
import (
// "strings".
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"github.com/valyala/fasthttp"
"github.com/authelia/authelia/v4/internal/mocks"
)
type passwordPolicyResponseBody struct {
Status s... |
package main
import (
"fmt"
)
func si(slice []string, myStr string) bool {
for _, v := range slice {
if v == myStr {
return true
}
}
return false
}
func main() {
animals := []string{"cat", "bear", "horse", "lion", "snake"}
result := si(animals, "kitty") //false //"bear" == true
fmt.Println(result)
}
|
package cmd
import (
"github.com/spf13/cobra"
"github.com/Zenika/marcel/api/db/export"
"github.com/Zenika/marcel/config"
)
func init() {
var cfg = config.New()
var exportFile string
var pretty bool
var cmd = &cobra.Command{
Use: "export",
Short: "Exports data from marcel's database",
Args: cobra.N... |
package tmp
const MiddleWareWSTmp = `package {{printf "%v_handler" (index . 0)}}
import (
"net/http"
{{printf "\"%v/helper\"" (index . 1)}}
"time"
"github.com/gobwas/ws"
"github.com/gobwas/ws/wsutil"
)
func (h *handler) WS(w http.ResponseWriter, r *http.Request) {
conn, _, _, err := ws.UpgradeHTTP(r, w)
if e... |
package game
import (
"github.com/tanema/amore/gfx"
)
type Car struct {
*Sprite
percent float32
point Point
speed float32
segment *Segment
}
func newCar(segment *Segment, source *gfx.Quad, z, offset, speed float32) *Car {
new_car := &Car{
point: Point{
z: z,
w: source.GetWidth() * sprite_scale,
... |
package handler
import (
"fmt"
"html/template"
"net/http"
"strconv"
"time"
entity "github.com/Surafeljava/Court-Case-Management-System/Entity"
"github.com/Surafeljava/Court-Case-Management-System/notificationUse"
)
//NotificationHandler struct
type NotificationHandler struct {
tmpl *tem... |
//go:generate ../../bin/goversioninfo.exe -icon=image.ico -manifest=referentiel-sncf.exe.manifest -o=referentiel-sncf.syso
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"os"
"path/filepath"
"referentiel-sncf/icon"
"runtime"
"strings"
"time"
"github.com/cratonica/trayhost"
"github.com/teale... |
package main
import "fmt"
func main() {
// tree1 := TreeNode{8, nil, nil}
// tree2 := TreeNode{7, nil, &tree1}
// tree3 := TreeNode{11, nil, nil}
// tree4 := TreeNode{15, &tree2, nil}
// tree5 := TreeNode{120, &tree3, &tree4}
//var t TreeNode = nil
fmt.Println(preorderTraversal(nil))
}
//Definition for a bin... |
package libresponse
import (
"encoding/json"
"github.com/helloferdie/stdgo/libtime"
"github.com/golang-jwt/jwt"
)
// Default - Default response
type Default struct {
Success bool `json:"success"`
Code int64 `json:"code"`
Message string `json:"message"`
MessageLoca... |
package controllers
import (
"bbs/lib/types"
"bbs/util"
"fmt"
"time"
)
type UserController struct {
baseController
}
//配置信息
func (c *UserController) Index() {
c.TplName = c.controllerName + "/index.html"
}
//配置信息
func (c *UserController) Set() {
switch c.Ctx.Request.Method {
case "GET":
c.TplName = c.cont... |
// Copyright 2021 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
/*
* Copyright 2018-present Open Networking Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law ... |
package main
import "fmt"
func main(){
array := []int{1,2,3}
fmt.Printf("%T", array)
// fmt.Println(array)
// array = append(array, 4, 5)
// fmt.Println(array)
} |
package main
import "fmt"
// Constant
func main() {
const (
firstName = "Mahendra"
lastName = "Chevro"
value = 1000
)
fmt.Println(firstName)
fmt.Println(lastName)
fmt.Println(value)
}
|
/*
Package assert adds conditionally-compiled* asserts to your project.
The package is designed to be imported into your main scope for convenient access:
import . "github.com/iNamik/go_pkg/debug/assert"
Assert(true)
Assert(false) // generates panic
Assert is enabled by default. To disable them, build your code... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-09-07 08:20
# @File : lt_111_Minimum_Depth_of_Binary_Tree.go
# @Description :
# @Attention :
*/
package v0
import "math"
/*
树的最短深度: 递归法(分治法)
关键在于
1. 当left,right为nil代表的是到了叶子节点,返回1即可
2. 需要对左孩子比较最小值,也需要对右孩子比较最小值
*/
func minDepth(root *TreeNode) int {... |
// Copyright 2020 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
package controller
import (
"encoding/json"
"net/http"
"github.com/gin-gonic/gin"
"github.com/nurrizkyimani/pahamifybackend/database"
"github.com/nurrizkyimani/pahamifybackend/model"
)
//CORSMiddleware is middle ware for cors
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.H... |
package endpoints
import (
"context"
"github.com/giantswarm/microerror"
"github.com/giantswarm/operatorkit/controller/context/resourcecanceledcontext"
"k8s.io/api/core/v1"
apismetav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/giantswarm/aws-operator/service/controller/legacy/v29/key"
)
func (r *Resour... |
package main
import (
"bufio"
"crypto/tls"
"database/sql"
"flag"
"fmt"
"github.com/elazarl/goproxy"
"github.com/elazarl/goproxy/transport"
_ "github.com/mattn/go-sqlite3"
"log"
"net"
"net/http"
"regexp"
"strings"
"sync"
)
type HttpLogger struct {
db *sql.DB
}
func NewLogger(dbname string) (*HttpLogger... |
package main
import (
"fmt"
"github.com/soniakeys/meeus/base"
"github.com/soniakeys/meeus/julian"
"github.com/soniakeys/meeus/line"
"math"
"time"
)
func main() {
// Example 19.a, p. 121.
// convert degree data to radians
r1 := 113.56833 * math.Pi / 180
d1 := 31.89756 * math.Pi / 180
r2 := 116.25042 * math... |
// Copyright 2021 Clivern. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package definition
import (
"fmt"
"strings"
"testing"
"github.com/franela/goblin"
)
// TestUnitMinio test cases
func TestUnitMinio(t *testing.T) {
g := goblin.Gobl... |
package osbuild2
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestNewTruncateStage(t *testing.T) {
options := TruncateStageOptions{
Filename: "image.raw",
Size: "42G",
}
expectedStage := &Stage{
Type: "org.osbuild.truncate",
Options: &options,
}
actualStage := NewTruncateStage... |
// Copyright (c) 2020 Hirotsuna Mizuno. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
package speedio
import (
"time"
)
// LimiterConfig indicates the configuration parameter of bit rate limiting.
//
// Resolution is the period for totaling ... |
package zefir
import "regexp"
type Handler func(context Context)
type Route struct {
method string
name string
pattern *regexp.Regexp
handler Handler
}
func (r *Route) GetHandler() Handler {
return r.handler
}
|
package config
// key = errCode, string = errMsg
type ErrInfo struct {
ErrCode int32
ErrMsg string
}
var (
OK = ErrInfo{0, ""}
ErrMysql = ErrInfo{100, ""}
ErrMongo = ErrInfo{110, ""}
ErrRedis = ErrInfo{120, ""}
ErrParseToken = ErrInfo{200, "Parse token failed"}
Err... |
// +build !integration
package disgord
import "testing"
func TestCache_ChannelCreate(t *testing.T) {
t.Run("immutable", func(t *testing.T) {
cache, _ := newCache(&CacheConfig{
DisableGuildCaching: true,
DisableUserCaching: true,
DisableVoiceStateCaching: true,
})
c1 := NewChannel()
c1.I... |
package output
import (
"compress/gzip"
"io"
"os"
"time"
"github.com/golang/protobuf/proto"
pb "github.com/google/pprof/proto"
)
type Writer struct {
Out *pb.Profile
destName string
}
func NewWriter(dstName string, sampleTypes ...*pb.ValueType) *Writer {
return &Writer{
destName: dstName,
Out: &pb... |
package geom
import "math"
type Camera struct {
LowerLeftCorner, Horizontal, Vertical, Origin Vec3d
}
func (cam *Camera) GetRay(u float64, v float64) Ray {
direction := cam.LowerLeftCorner.Add(cam.Horizontal.Multiply(u))
direction = direction.Add(cam.Vertical.Multiply(v))
direction = direction.Substract(cam.Orig... |
package frontend
import (
"github.com/gin-gonic/gin"
"net/http"
"strconv"
"time"
"fmt"
)
func (s *Server) rpAddGet(ctx * gin.Context) {
ctx.HTML(http.StatusOK, "rpadd.tmpl", nil)
}
func (s *Server) rpAddPost(ctx * gin.Context) {
sessionToken := ctx.GetString("sessionToken")
amt := ctx.PostForm("amou... |
// +build connx
package onnx
/*
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "cbits.hpp"
*/
import "C"
import (
"io/ioutil"
"unsafe"
"github.com/Unknwon/com"
"github.com/gogo/protobuf/proto"
"github.com/pkg/errors"
)
func CheckModel(protoFileName string) (*ModelProto, error) {
if !com... |
package jarvisbot
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/tucnak/telebot"
)
const googleSearchAPI = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q="
func (j *JarvisBot) GoogleSearch(msg *message) {
if len(msg.Args) == 0 {
so := &telebot.SendOptio... |
package main
type Block struct {
Timestamp int64 // the time when the block was created
PreviousBlockHash []byte // the hash of previous block
BlockHash []byte // the hash of current block
BlockData []byte // transaction information [body of current block]
}
// Prepare blockchain data str... |
package cpmcontainerapi
import (
"bytes"
"encoding/json"
"github.com/crunchydata/crunchy-postgresql-manager-openshift/logit"
"io/ioutil"
"net/http"
)
const PORT = ":10001"
//
// example of calling one of these
//
// request := &cpmcontainerapi.RemovewritefileRequest{"something", "yes"}
// response, err := cpmco... |
package app
import (
"net/http"
"os"
"secure/database"
"strings"
"time"
"github.com/dgrijalva/jwt-go"
)
type Claims struct {
User database.User `json:"user"`
jwt.StandardClaims
}
func setupMiddleware(r Handler) Handler {
return logRequests(checkToken(r))
}
func logRequests(h Handler) Handler {
return Han... |
package handler
import (
"net/http"
"strconv"
"github.com/pluhe7/trueconftest/model"
"github.com/labstack/echo"
)
func (h *Handler) addUser(c echo.Context) error {
u := &model.User{
ID: h.Seq,
}
if err := c.Bind(u); err != nil {
return c.JSON(http.StatusInternalServerError, "Can't create user")
}
h.Use... |
package config
type MQConfiguration struct {
Dial string
}
|
package Problem0347
import (
"fmt"
"sort"
"testing"
"github.com/stretchr/testify/assert"
)
// tcs is testcase slice
var tcs = []struct {
nums []int
k int
ans []int
}{
{[]int{1, 1, 1, 2, 2, 3}, 2, []int{1, 2}},
// 可以有多个 testcase
}
func Test_topKFrequent(t *testing.T) {
ast := assert.New(t)
for _, t... |
package _606_Construct_String_from_Binary_Tree
import (
"strconv"
)
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func tree2str(root *TreeNode) string {
return tree2strPreR(root)
}
func tree2strPreR(root *TreeNode) string {
if root == nil {
return ""
}
x := strconv.Itoa(root.Val)
if ... |
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
type Client struct {
port int
stdout io.Writer
}
func NewClient(port int, stdout io.Writer) *Client {
return &Client{
port: port,
stdout: stdout,
}
}
func (c *Client) Order(cmd []string) error {
b, err := json.Marshal(&Request{C... |
package types
import (
"github.com/idena-network/idena-go/common/hexutil"
"github.com/shopspring/decimal"
"time"
)
type Entity struct {
Name string
Ref string
}
type EpochSummary struct {
Epoch uint64 `json:"epoch"`
ValidationTime time.Time `json:"validationTime"`
ValidatedCount uin... |
//main.go
package main
import (
"database/sql"
"flag"
"log"
//Driver para sqlite
_ "modernc.org/sqlite"
)
func main() {
server := NewServer(":3000")
migrate := flag.Bool("migrate", false, "create tables of db")
flag.Parse()
if *migrate {
if err := MakeMigrations(); err != nil {
log.Fatal(err)
}
}
... |
package apitest
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
nitrousServer "github.com/BoutiqaatREPO/nitrous/server"
"github.com/gin-gonic/gin"
)
type TestServer struct {
Engine *gin.Engine
}
func (this *TestServer) Initialize() {
this.Engine = nitrousServer.BootStrap()
}
func (this *Tes... |
// 火车票购买的思考
1、火车票是分段的
—— —— —— —— ——
【例】
(1)一个火车有6个站,那么他可选的票种类就是c62,共计15种
(2)同时每个票都有3种类型,共计15*3=45种类型
-----------------------------------------------
数据结构~
var long [6]int
var end int
需要不断的更新数据库
// 查询
// 遍历一下输出
func check(){
}
// 购票
func sellTicket(){
}
// 退票
func refundTicket()
main()
|
//source: https://doc.qt.io/qt-5/qtsql-querymodel-example.html
package main
import (
"os"
"github.com/therecipe/qt/core"
"github.com/therecipe/qt/sql"
"github.com/therecipe/qt/widgets"
)
func initializeModel(model *sql.QSqlQueryModel) {
model.SetQuery2("select * from person", db)
model.SetHeader... |
package solver
import (
"fmt"
"strings"
"github.com/go-air/gini/inter"
"github.com/go-air/gini/logic"
"github.com/go-air/gini/z"
)
type DuplicateIdentifier Identifier
func (e DuplicateIdentifier) Error() string {
return fmt.Sprintf("duplicate identifier %q in input", Identifier(e))
}
type inconsistentLitMapp... |
// Copyright 2018 Diego Bernardes. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package queue
import "context"
// Client that implements the queue interface.
type Client struct {
Content []byte
err error
}
// Push the content to t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.