text stringlengths 11 4.05M |
|---|
package main
import (
"flag"
"fmt"
"strings"
)
// This is a struct declaration
type message struct {
text *string
}
// Add a method to your new struct -
func (m *message) UpperCaseIt() string {
return strings.ToUpper(*m.text)
}
func main() {
// Create your new variable
var msg message
// Set the commandlin... |
package common
import (
"container/list"
"errors"
"sync"
)
type ThreadSafeQueue struct {
lock sync.Mutex
vals *list.List
}
func NewThreadSafeQueue() Queue {
return ThreadSafeQueue{
lock: sync.Mutex{},
vals: list.New(),
}
}
func (tsq ThreadSafeQueue) IsEmpty() bool {
return tsq.vals.Len() == 0
}
func (t... |
package domain
type Service struct {
User int `json:"user,omitempty"`
Forum int `json:"forum,omitempty"`
Thread int `json:"thread,omitempty"`
Post int `json:"post,omitempty"`
}
type ServiceRepository interface {
Clear() error
Status() (Service, error)
}
type ServiceUsecase interface {
Clear() error
Sta... |
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/araddon/dateparse"
"github.com/mmcdole/gofeed"
)
var (
OutLog = "** Run Log\n"
)
type rss struct {
Site string
Limit int
}
type configuration struct {
OutputPath string
Rss []rss
}
func request(f *gof... |
package urkel
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"log"
)
func GenPemRSA(keyLength int) (string, string) {
privateKeyRaw, err := rsa.GenerateKey(rand.Reader, keyLength)
if err != nil {
log.Fatal("Error generating keys")
}
privateKeyDer := x509.MarshalPKCS1PrivateKey(privateK... |
package router
import (
"flea-market/controller/dialog"
"flea-market/controller/goods"
"flea-market/controller/star"
"flea-market/controller/upload"
"flea-market/controller/user"
"github.com/gin-gonic/gin"
)
func LoadApiRouter(r *gin.Engine) {
api := r.Group("/api")
{
// 用户相关
api.GET("/user/login", user.... |
package main
import (
"grpc-sse/protos"
"log"
"net"
"os"
"os/signal"
"sync"
"syscall"
"google.golang.org/grpc"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/reflection"
)
func main() {
gs := grpc.NewServer()
logger := grpclog.NewLoggerV2(os.Stdout, os.Stdout, os.Stdout)
eventsCh := make(chan... |
// Copyright 2019 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package sysutil
import (
"io/ioutil"
"math"
"path/filepath"
"strconv"
"strings"
"chromiumos/tast/errors"
)
// TemperatureInputMax returns the maximum currently obser... |
package main
// StatementRecord .
type StatementRecord struct {
LineNumber string
Location string
Label string
Opcode string
Operand string
ObjectCode string
IsPureCommentORBlank bool
}
|
//
// Copyright (c) SAS Institute 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 agre... |
package main
func main() {
mainTimerDriver()
}
// func main() {
// ck := fanin(counts("amy"), counts("rose"))
// // amychan := counts("amy")
// // rosechan := counts("rose")
// for i := 0; i < 10; i++ {
// fmt.Println(<-ck)
// }
// }
// func fanin(c, k <-chan string) <-chan string {
// ck := make(chan strin... |
package recaptcha
import (
// "fmt"
// "github.com/sirupsen/logrus"
// "io/ioutil"
// "net/http"
// "net/url"
"strings"
"testing"
// "time"
. "gopkg.in/check.v1"
)
func TestPackage(t *testing.T) { TestingT(t) }
type ReCaptchaSuite struct{}
var _ = Suite(&ReCaptchaSuite{})
func (s *ReCaptchaSuite) TestN... |
package plugins
import (
"encoding/json"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/klog"
"strings"
"WarpCloud/walm/pkg/models/k8s"
"WarpCloud/walm/pkg/util"
)
const (
NeedIsomateNameAnnoationKey = "NeedIsomateName"
NeedIsomateNameAnnoationValue = "true"
IsomateNamePluginName = "IsomateNa... |
// +build !windows
package findprocess
import (
"os"
"syscall"
)
func findProcess(pid int) (process *os.Process, err error) {
// On Unix systems, FindProcess always succeeds and returns a Process
// for the given pid, regardless of whether the process exists.
process, _ = os.FindProcess(pid)
err = process.Sign... |
package privacy
// NOTE: Reanme this package. Will eventually replace in its entirety with Activites.
// PolicyEnforcer determines if personally identifiable information (PII) should be removed or anonymized per the policy.
type PolicyEnforcer interface {
// CanEnforce returns true when policy information is specifi... |
package model
import "strconv"
// GithubUser is response object from github api
type GithubUser struct {
ID int `json:"id"`
UserName string `json:"login"`
Email string `json:"email"`
}
// UUID return string github user id
func (u *GithubUser) UUID() string {
return strconv.Itoa(u.ID)
}
|
//
// Copyright (c) SAS Institute 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 agre... |
package util
import (
"net/http"
"github.com/gin-gonic/gin"
)
// Contains function is to check item whether is exist or not in a list and will return bool
func Contains(d string, dl []string) bool {
for _, v := range dl {
if v == d {
return true
}
}
return false
}
// CallErrorNotFound is for return API ... |
package db
import (
"database/sql"
"fmt"
"github.com/yanchenm/photo-sync/models"
)
func (db Database) GetDetailForPhoto(id string) (models.Detail, error) {
detail := models.Detail{}
query := `SELECT * FROM details WHERE id = $1;`
row := db.Conn.QueryRow(query, id)
err := row.Scan(&detail.ID, &detail.FileType... |
package extract_test
import (
"fmt"
"os"
)
// LoggingFS is a disk that logs every operation, useful for unit-testing.
type LoggingFS struct {
Journal []*LoggedOp
}
// LoggedOp is an operation logged in a LoggingFS journal.
type LoggedOp struct {
Op string
Path string
OldPath string
Mode os.FileMode... |
package utils
func GetMessage() {
} |
package hrtree
import (
"fmt"
)
func assert(ok bool) {
assert2(ok, "assertion failed!")
}
func assert2(ok bool, msg string, args ...interface{}) {
if !ok {
panic(fmt.Sprintf(msg, args...))
}
}
|
package controllers
import(
"revel_postgresql/app/models"
"github.com/revel/revel"
"fmt"
)
type App struct {
ModelController
}
func (c App) New() revel.Result {
greeting := "Hello, Revel.!!"
return c.Render(greeting)
}
func (c App) Index(name string) revel.Result {
fmt.Println("Name------->", name)
u... |
package binstruct
type Marshaler interface {
MarshalBinary() ([]byte, error)
}
func Marshal(v interface{}) ([]byte, error) {
return nil, nil
}
|
package namespace
import "math"
// IDSize is the number of bytes a namespace uses.
// Valid values are in [0,255].
type IDSize uint8
// IDMaxSize defines the max. allowed namespace ID size in bytes.
const IDMaxSize = math.MaxUint8
|
package rcluster
import (
"strings"
"github.com/go-redis/redis"
)
var rcClient *redis.ClusterClient
func init() {
rcClient = redis.NewClusterClient(&redis.ClusterOptions{
Addrs: strings.Split(
redisConfig.String("redisClusterHosts"),
",",
),
PoolSize: 100,
})
}
func NewRedisClient() *redis.Cluster... |
package completers
import (
"strings"
prompt "github.com/c-bata/go-prompt"
"github.com/lflxp/showme/pkg/prompt/suggests"
)
// 解析函数 判断最新参数是否含有-字符
func getPreviousOption(d prompt.Document) (cmd, option string, found bool) {
args := strings.Split(d.TextBeforeCursor(), " ")
l := len(args)
if l >= 2 {
option = ar... |
package webca
import (
"encoding/gob"
"log"
"os"
"sync"
)
const (
WEBCA_CFG = ".webca.cfg"
)
// oneCfg ensures serialized access to configuration
var oneCfg sync.Mutex
// User contains the App's User details
type User struct {
Username, Fullname, Password, Email string
}
// config contains the App's Configu... |
package consumer
import (
"context"
"sync"
"time"
"github.com/pkg/errors"
"github.com/streadway/amqp"
"github.com/upfluence/pkg/closer"
"github.com/upfluence/pkg/log"
)
var ErrCancelled = errors.New("amqp/consumer: Consumer is cancelled")
type Consumer interface {
Open(context.Context) error
IsOpen() bool... |
package models
import(
"encoding/json"
)
/**
* Type definition for UpgradeStatusEnum enum
*/
type UpgradeStatusEnum int
/**
* Value collection for UpgradeStatusEnum enum
*/
const (
UpgradeStatus_KIDLE UpgradeStatusEnum = 1 + iota
UpgradeStatus_KACCEPTED
UpgradeStatus_KSTARTED
... |
// Copyright (c) 2018 Uber Technologies, Inc.
//
// 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... |
package space
//Planet custom string type for planet name
type Planet string
const earthYearInSec float64 = 31557600.0
var orbitalPeriods = map[Planet]float64{
"Mercury": 0.2408467,
"Venus": 0.61519726,
"Earth": 1.0,
"Mars": 1.8808158,
"Jupiter": 11.862615,
"Saturn": 29.447498,
"Uranus": 84.016846,
... |
package main
import (
"fmt"
"github.com/cloudflare/ahocorasick"
)
func main() {
dictionary := []string{"hello", "world", "世界", "google", "golang", "c++", "love"}
ac := ahocorasick.NewStringMatcher(dictionary)
ret := ac.Match([]byte("hello世界, hello google, i love golang!!!"))
for index, i := range ret {
fmt... |
/*
Copyright 2020 The KubeSphere 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, ... |
/*
This is the main entry of my chatroom project.
moduels:
SocketServer: basic wrapper for data transmission
SocketDataAdapter: binary/ json / ...
MessageDispatcher
ChatRoomManager: dispatch message to correct rooms
ChatRoom
PrivateChatRoom
PublicChatRoom
HistoryKeeper
*/
package main
import (NT "network")
con... |
package authentication
import "testing"
func TestComputeHmac256(t *testing.T) {
res := ComputeHmac256("message", "secret")
expectation := "i19IcCmVwVmMVz2x4hhmqbgl1KeU0WnXBgoDYFeWNgs="
if res != expectation {
t.Error("Expected", expectation, "got", res)
}
}
func TestComputeHmac1(t *testing.T) {
res := Comp... |
package main //comment |
package handler
import (
"log"
"net"
"github.com/glasnostic/example/router/packet"
"github.com/google/gopacket/layers"
)
// rewriter
type rewriter struct {
local *pod
client *pod
server *pod
table map[uint32]net.HardwareAddr
}
// NewRewriter create New Rewriter Handler
func NewRewriter(localMac, clientMa... |
package utils
import (
"encoding/json"
"reflect"
log "github.com/sirupsen/logrus"
"github.com/tidwall/pretty"
)
// PrettyPrint - output formatted json
func PrettyPrint(i interface{}) {
log.Debug(reflect.TypeOf(i))
s, _ := json.MarshalIndent(i, "", "\t")
colored := pretty.Color(s, nil)
log.Debug(string(color... |
package ch04
type UUIDCounter map[string]int
func NewUUIDCounter() *UUIDCounter {
return &UUIDCounter{}
}
func (c *UUIDCounter) Count(id []byte) {
(*c)[string(id)]++
}
|
package main
import "fmt"
// goではclassの代わりにstructを使う
type Person struct {
Name string // 大文字で始まるとpublic
age int // 小文字で始まるとprivate
}
// structにはメンバー変数のみ定義してメソッドは{this相当の変数 *struct名}をつけたfuncを書く
func (p *Person) SetPerson(name string, age int) {
p.Name = name
p.age = age
}
func (p *Person) GetAge() int {
ret... |
// Copyright © 2019. All rights reserved.
// Author: Ilya Yuryevich.
// Contacts: qioalice@gmail.com, https://github.com/qioalice
// License: https://opensource.org/licenses/MIT
package ekafield
import (
"fmt"
"math"
"time"
"github.com/qioalice/ekago/v2/internal/ekaclike"
"github.com/modern-go/reflect2"
)
// ... |
package test
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/gofiber/fiber"
"dwc.com/lumiere/account"
"dwc.com/lumiere/account/model"
)
func RunBalanceTest(endpoint string, authedAccount interface{}) *http.Response {
// Test fiber routing logic with
// https://docs.gofiber.io/a... |
package yeahmobi
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"text/template"
"github.com/prebid/openrtb/v19/openrtb2"
"github.com/prebid/prebid-server/adapters"
"github.com/prebid/prebid-server/config"
"github.com/prebid/prebid-server/errortypes"
"github.com/prebid/prebid-server/macros"
"github.com... |
package incus
import (
"fmt"
"os"
"github.com/spf13/viper"
)
func NewConfig(configFilePath string) {
viper.SetConfigName("config")
viper.AddConfigPath(configFilePath)
err := viper.ReadInConfig()
if err != nil {
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
ConfigOption("client_broadcasts", ... |
package storageos
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"time"
api "github.com/storageos/go-api/v2"
)
//go:generate mockgen -build_flags=--mod=vendor -destination=mocks/mock_control_plane.go -package=mocks github.com/storageos/cluster-operator/internal/pkg/storageos ControlPlane
/... |
package cosign
import (
"crypto"
"encoding/json"
"errors"
"fmt"
"github.com/opencontainers/go-digest"
oci "github.com/opencontainers/image-spec/specs-go/v1"
)
var algorithms = map[crypto.Hash]digest.Algorithm{
crypto.SHA256: digest.SHA256,
crypto.SHA384: digest.SHA384,
crypto.SHA512: digest.SHA512,
}
// di... |
package http_api // nolint: golint
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"sync"
"testing"
"github.com/uniqush/uniqush-push/push"
"github.com/uniqush/uniqush-push/srv/apns/common"
apns_mocks "github.com/uniqush/uniqush-push/srv/apns/http_api/mocks"
)
const (
bundleID = ... |
package main
import (
"fmt"
)
type Livro struct {
titulo string
preco float64
numeroPaginas int
}
func (l *Livro) Digitar(){
fmt.Print("Entre com o Titulo: ")
fmt.Scanf("%s", &l.titulo)
fmt.Print("Entre com o Preço: ")
fmt.Scanf("%f", &l.preco)
fmt.Print("Entre com o Numero de Páginas: ")
fmt.Scanf("%d... |
func inorderTraversal(root *TreeNode) []int {
arr := make([]int, 0)
helper(root, &arr)
return arr
}
func helper(root *TreeNode, arr *[]int) {
if root != nil {
helper(root.Left, arr)
(*arr) = append((*arr), root.Val)
helper(root.Right, arr)
}
} |
package requests
import (
"net/url"
"github.com/atomicjolt/canvasapi"
)
// ListEnvironmentFeatures Return a hash of global feature settings that pertain to the
// Canvas user interface. This is the same information supplied to the
// web interface as +ENV.FEATURES+.
// https://canvas.instructure.com/doc/api/featur... |
package agent
import (
"context"
"github.com/adevinta/vulcan-agent/check"
"github.com/adevinta/vulcan-agent/config"
"github.com/sirupsen/logrus"
)
// Constants defining environment variables that a check expects.
const (
CheckIDVar = "VULCAN_CHECK_ID"
ChecktypeNameVar = "VULCAN_CHECKTYPE_NAME"
Ch... |
// Copyright © 2019 Kerem Karatal
//
// 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... |
package models
import "go.mongodb.org/mongo-driver/mongo"
// 采购订单实例(供应商订单实例)
// 采购订单子订单
type SupplierSubOrder struct {
SubOrderId int64 `json:"order_sub_id" bson:"order_sub_id"` // 子订单id
SubOrderSn string `json:"order_sub_sn" bson:"order_sub_sn"` // 子订单号
ComID int6... |
package tiltfile
import (
"context"
"github.com/tilt-dev/tilt/internal/store"
"github.com/tilt-dev/tilt/pkg/model"
"github.com/tilt-dev/tilt/pkg/model/logstore"
)
// BuildEntry is vestigial, but currently used to help manage state about a tiltfile build.
type BuildEntry struct {
Name model.Mani... |
package request
import (
"bytes"
"context"
"io"
"net/http"
"sync"
"time"
"github.com/webnice/transport/v3/header"
"github.com/webnice/transport/v3/methods"
"github.com/webnice/transport/v3/response"
)
// Pool is an interface of package
type Pool interface {
// RequestGet Извлечение из pool нового элемента ... |
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
strfmt "github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/errors"
"github.com/go-openapi/validate"
)
/*Service service
swa... |
package ether_scan
import (
"errors"
"fmt"
"github.com/eager7/elog"
"github.com/BlockABC/eth-tokens/script/built"
"github.com/BlockABC/eth-tokens/script/erc20"
"github.com/ethereum/go-ethereum/ethclient"
"time"
)
var log = elog.NewLogger("spider", elog.DebugLevel)
type Spider struct {
url string
client *... |
package connector
import (
"common"
"logger"
"pockerclient"
"roomclient"
"rpc"
"strconv"
)
// conn:请求进入自建房间
func (self *CNServer) EnterCustomRoom(conn rpc.RpcConn, msg rpc.EnterCustomRoomREQ) error {
logger.Info("client call EnterCustomRoomREQ begin, gameType:%s", msg.GetGameType())
p, exist := self.getPlayer... |
package sherlockandarray
// https://www.hackerrank.com/challenges/sherlock-and-array
// BalancedSums - implements the solution to the problem
func BalancedSums(arr []int32) string {
left := make([]int32, len(arr))
right := make([]int32, len(arr))
for i := 1; i < len(arr); i++ {
left[i] = left[i-1] + arr[i-1]
r... |
package u8_test
import (
"fmt"
"time"
"github.com/shurcooL/go/u/u8"
)
func Example1() {
x := u8.AfterSecond(func() { fmt.Println("hi") })
time.Sleep(500 * time.Millisecond)
x.Cancel()
time.Sleep(1500 * time.Millisecond)
// Output:
}
func Example2() {
x := u8.AfterSecond(func() { fmt.Println("hi") })
... |
package game
import (
"math/rand"
"github.com/nsf/termbox-go"
)
//CFOOD Color of food
const CFood = termbox.ColorRed
// Food object in game
type Food struct {
Char rune
Pos Vec2i
}
// Creates a food randomly in bounds
func NewFood(width, height int) Food {
return Food{
Char: '@',
Pos: Vec2i{
X: rand.I... |
// Copyright (C) 2020 Storj Labs, Inc.
// See LICENSE for copying information.
package rpccache
import (
"sync"
"time"
"github.com/zeebo/errs"
)
// implementation note: the cache has some methods that could
// potentially be quadratic in the worst case. specifically
// when there are many stale entries in the li... |
//
// IMediator.go
// PureMVC Go Multicore
//
// Copyright(c) 2019 Saad Shams <saad.shams@puremvc.org>
// Your reuse is governed by the Creative Commons Attribution 3.0 License
//
package interfaces
/*
The interface definition for a PureMVC Mediator.
In PureMVC, IMediator implementors assume these responsibiliti... |
// Package grep implements a solution of the exercise titled `Grep'.
package grep
import (
"bufio"
"fmt"
"io"
"os"
"strings"
)
func index(slice []string, element string) int {
for i, member := range slice {
if member == element {
return i
}
}
return -1
}
// Search does text search like unix grep comma... |
package main
import (
"crypto"
"crypto/sha1"
"encoding/base64"
"fmt"
)
// 实现了SHA1哈希算法
func main() {
// 返回一个新的使用SHA1校验的hash.Hash
h := sha1.New()
// 写入
h.Write([]byte("Hello World"))
// 返回添加b到当前的hash值后的新切片,不会改变底层的hash状态
m := h.Sum(nil)
// 转base64字符串打印
fmt.Println(base64.StdEncoding.EncodeToString(m))
//... |
package cmd
import (
"fmt"
"github.com/bitmaelum/bitmaelum-server/core"
"github.com/bitmaelum/bitmaelum-server/core/container"
"github.com/spf13/cobra"
"time"
)
// allowRegistrationCmd represents the allowRegistration command
var allowRegistrationCmd = &cobra.Command{
Use: "allow-registration",
Short: "Allo... |
package annotation_api
import (
"encoding/json"
"fmt"
"github.com/samuel/go-zookeeper/zk"
"github.com/wndhydrnt/proxym/log"
"io/ioutil"
"net/http"
)
type AnnotationListItem struct {
Annotation *Annotation `json:"annotation"`
Link string `json:"link"`
}
type Http struct {
zkCon *zk.Conn
}
func (h... |
package filestore
import (
"errors"
)
var (
ErrFileAlreadyExists = errors.New("File already exists")
ErrFileNotFound = errors.New("File not found")
ErrFileTooLarge = errors.New("File is too large")
ErrFileCorrupted = errors.New("File is corrupted, try storing it again")
ErrChecksumFailed = erro... |
package geopoint
import "math"
// Point is the interface for any geopoints
type Point interface {
ToRadians() Radians
ToDegrees() Degrees
}
// Degrees is the point in degrees
type Degrees struct {
Latitude float64
Longitude float64
}
// ToRadians converts a Degrees point to Radians
func (p Degrees) ToRadians()... |
package intersect
// На вход подается два массива произвольной длинны
// Метод должен возвращать пересечение этих массивов (одинаковые элементы в обоих массивах)
// Есть ли способ сделать оптимальнее?
func SliceIntersect(a, b []int64) []int64 {
var result []int64
out:
for _, valA := range a {
for _, valB := range... |
//determine if a sentence contains at least 1 instance of each letter
package pangram
import "strings"
//identify each unique character and determine if the full string is a pangram
func IsPangram(s string) bool {
s = strings.ToLower(s)
encountered := map[byte]bool{}
for i := range s {
if s[i] >= 'a' && s[i] <=... |
package validation
import (
"bytes"
"fmt"
"io"
"testing"
"context"
"crypto/tls"
"crypto/x509"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"github.com/stretchr/testify/assert"
)
func TestValidateHostname(t *testing.T) {
var inputHostname string
hostname, err := ValidateHostname(inputHostn... |
package sink
import (
"testing"
"github.com/mongodb/amboy/queue"
"github.com/stretchr/testify/suite"
)
type ServiceCacheSuite struct {
cache *appServicesCache
suite.Suite
}
func TestServiceCacheSuite(t *testing.T) {
suite.Run(t, new(ServiceCacheSuite))
}
func (s *ServiceCacheSuite) SetupTest() {
s.cache = &... |
package tencent
func Code896() {
}
/**
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
示例 1:
输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。
示例 2:
输入: "cbbd"
输出: "bb"
*/
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func longestPalindrome(s string) str... |
package almanack
import (
"reflect"
"testing"
)
func TestToFromTOML(t *testing.T) {
cases := map[string]SpotlightPAArticle{
"empty": {},
"body": {Body: "\n ## subhead ! \n"},
"fm": {Hed: "Hello", Authors: []string{"john", "smith"}},
"body+fm": {Hed: "Hello", Authors: []string{"john", "smith"}, Bo... |
package gateway
import (
"errors"
"net"
"time"
"github.com/NebulousLabs/Sia/build"
"github.com/NebulousLabs/Sia/crypto"
"github.com/NebulousLabs/Sia/encoding"
"github.com/NebulousLabs/Sia/modules"
"github.com/inconshreveable/muxado"
)
const (
dialTimeout = 2 * time.Minute
// the gateway will not make outb... |
package main
import (
"fmt"
"math/big"
)
func main() {
lightSpeed := big.NewInt(299792) // km/s
secondPerDay := big.NewInt(86400)
dayPerYear := big.NewInt(365)
distance := new(big.Int)
distance.SetString("236000000000000000", 10) // km
seconds := new(big.Int)
seconds.Div(distance, lightSpeed)
days := new(... |
package intersections
import (
"github.com/gmacd/rays/core"
)
// Assumes the ray and triangle points are in the same space
func IntersectRayTriangle(r core.Ray, p1, p2, p3 core.Vec3, maxDist float64) (hit HitType, dist float64) {
e1 := p2.Sub(p1)
e2 := p3.Sub(p1)
s1 := r.Dir.Cross(e2)
divisor := s1.Dot(e1)
if d... |
package main
type snippet interface {
imports() []string
generate(p *printer)
}
type snippetTest interface {
testImports() []string
generateTest(p *printer)
}
func snippetTestOf(s snippet) snippetTest {
type tester interface {
test() snippetTest
}
if t, ok := s.(snippetTest); ok {
return t
}
if t, ok :... |
package server
import (
"net"
"strings"
"google.golang.org/grpc"
. "github.com/tendermint/go-common"
"github.com/anildukkipatty/tmsp/types"
)
// var maxNumberConnections = 2
type GRPCServer struct {
QuitService
proto string
addr string
listener net.Listener
server *grpc.Server
app types.TMSPA... |
package rpcclient
import (
"context"
"crypto/ed25519"
"encoding/hex"
"errors"
"fmt"
"kto/blockchain"
"kto/p2p/node"
"kto/rpcclient/message"
"kto/transaction"
"kto/txpool"
"kto/types"
"kto/until"
"kto/until/miscellaneous"
"net"
"os"
"strconv"
"golang.org/x/crypto/sha3"
"google.golang.org/grpc"
"goog... |
package version
import (
"fmt"
"strings"
)
// Env represents a Python environment.
type Env interface {
Get(k string) (string, error)
}
// Expr represents an expression that can be evaluated given an environment.
type Expr interface {
Evaluate(env Env) (bool, error)
}
// Evaluate returns true if the dependency ... |
package main
import "fmt"
func findMissingRanges(nums []int, start int, end int) []string {
ret := make([]string, 0)
prev := start - 1
cur := 0
for i := 0; i <= len(nums); i++ {
if i != len(nums) {
cur = nums[i]
} else {
cur = end + 1
}
if cur-prev >= 2 {
ret = append(ret, getRange(prev+1, cur-... |
// Copyright 2018, Shulhan <ms@kilabit.info>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package test
import (
"testing"
)
func TestAssert(t *testing.T) {
cases := []struct {
desc string
in interface{}
exp interface{}
}{
... |
package routers
import (
"net/http"
"strings"
"time"
"github.com/apulis/AIArtsBackend/configs"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
)
type Claim struct {
jwt.StandardClaims
Uid int `json:"uid"`
UserName string `json:"userName"`
}
var JwtSecret = configs.Config.Auth.Key
func pars... |
package rbac
import (
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"starter/pkg/database/mongo"
)
// Role 角色
type Role struct {
ID primitive.ObjectID `json:"_id" bson:"_id"`
Name string `json:"name" bson:"name" form:"name" binding:"max=12"` // ... |
package orders
import (
"encoding/json"
"fmt"
"github.com/gustavotero7/go-conekta/client"
"github.com/gustavotero7/go-conekta/models"
)
const basePath = "/orders"
// Create Creates a new Order
func Create(order models.Order) (*models.OrderResponse, error) {
response, err := client.Post(basePath, order)
if err... |
// Copyright 2020 The Moov Authors
// Use of this source code is governed by an Apache License
// license that can be found in the LICENSE file.
package wire
import (
"encoding/json"
"fmt"
"strings"
"unicode/utf8"
)
// Originator is the originator of the wire
type Originator struct {
// tag
tag string
// Pers... |
/*
Copyright 2019-2020 vChain, 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 in writing, software
... |
// Copyright 2019 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, ... |
package nodes
import (
"context"
"os"
"time"
dynatracev1beta1 "github.com/Dynatrace/dynatrace-operator/src/api/v1beta1"
"github.com/Dynatrace/dynatrace-operator/src/controllers/dynakube/dynatraceclient"
"github.com/Dynatrace/dynatrace-operator/src/controllers/dynakube/token"
"github.com/Dynatrace/dynatrace-ope... |
package main
import (
"fmt"
"math/rand"
"regexp"
"time"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
)
func handleIssueCommentEvent(event GithubIssueCommentPayload) error {
reviewersAskCommentRegexp := regexp.MustCompile(`^@` + BOT_NAME + `[\s]+assign[\s]+([a-z]+)[\s]+reviewers`)
matches := re... |
package main
import (
"coco_tools/DLFS"
"coco_tools/data"
"database/sql"
"fmt"
"image"
"image/draw"
"image/jpeg"
"io/ioutil"
"log"
"os"
"path"
"sync"
"time"
)
type dataset struct {
db *sql.DB
fbData *DLFS.Dataset
dataDir string
outputPath string
}
func (ds *dataset) Open(fbsFilename s... |
// Copyright 2021 Comcast Cable Communications Management, 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 ... |
package repository
import (
"belajar-golang-restful-api/model/domain"
"context"
"database/sql"
)
type CatagoryRepository interface {
Save(ctx context.Context, tx *sql.Tx, catagory domain.Catagory) domain.Catagory
Update(ctx context.Context, tx *sql.Tx, catagory domain.Catagory) domain.Catagory
Delete(ctx contex... |
package orb
// LineString represents a set of points to be thought of as a polyline.
type LineString []Point
// GeoJSONType returns the GeoJSON type for the object.
func (ls LineString) GeoJSONType() string {
return "LineString"
}
// Dimensions returns 1 because a LineString is a 1d object.
func (ls LineString) Dim... |
package main
import "learngo/book/conditionaljudgment/switchJudge/_switch"
func main() {
//_switch.SwitchBase()
_switch.TypeSwitch()
}
|
package handler
import (
"net/http"
"github.com/Lunchr/luncher-api/db"
"github.com/Lunchr/luncher-api/db/model"
"github.com/Lunchr/luncher-api/router"
)
func Tags(tagsCollection db.Tags) router.Handler {
return func(w http.ResponseWriter, r *http.Request) *router.HandlerError {
tagsIter := tagsCollection.GetA... |
package api
import (
"github.com/go-macaron/binding"
"github.com/ssok8s/ssok8s/pkg/api/dtos"
"github.com/ssok8s/ssok8s/pkg/api/routing"
"github.com/ssok8s/ssok8s/pkg/middleware"
)
func (hs *HTTPServer) registerRoutes() {
reqSignedIn := middleware.ReqSignedIn
reqAdmin := middleware.ReqAdmin
//reqTenant := middl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.