text stringlengths 11 4.05M |
|---|
package main
import "os"
import "fmt"
import "log"
func create() {
println("creating stuff")
file, _ := os.Create("cheese.txt")
defer file.Close()
fmt.Fprint(file, "CHEESE BITCHES :P")
}
/*
func write() {
file, err := os.Open("cheese.txt")
if err != nil {
log.Fatal(err)
}
defer... |
package main
import (
"bufio"
"fmt"
"log"
"net/http"
)
func main() {
res, err := http.Get("http://www.gutenberg.org/files/2701/old/moby10b.txt")
if err != nil {
log.Fatal(err)
}
// scan the page
scanner := bufio.NewScanner(res.Body)
defer res.Body.Close()
// set the split function for the scanning op... |
package agent_test
import (
"context"
"fmt"
"math/rand"
"strings"
"testing"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/go-state-types/rt"
power2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/power"
states2 "git... |
package main
import (
"github.com/Shopify/sarama"
"log"
"os"
"os/signal"
)
func main() {
config := sarama.NewConfig()
config.Consumer.Return.Errors = true
client, err := sarama.NewClient([]string{"localhost:9192", "localhost:9292", "localhost:9392"}, config)
defer client.Close()
if err != nil {
panic(err)
... |
package util
import (
"fmt"
"reflect"
)
type Animal interface {
MakeSound() string
}
type Dog struct{}
func (d *Dog) MakeSound() string {
return "Bark"
}
type Cat struct {
}
func (c Cat) MakeSound() string {
return "Meow"
}
func IsNil(i interface{}) bool {
fmt.Println(i, i == nil, reflect.ValueOf(i).IsNil(... |
package Gophp
import (
"os"
"path/filepath"
)
// FileExists file_exists()
func FileExists(filename string) bool {
_, err := os.Stat(filename)
if err != nil && os.IsNotExist(err) {
return false
}
return true
}
// IsFile is_file()
func IsFile(filename string) bool {
_, err := os.Stat(filename)
if err != nil ... |
package util_test
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"opendev.org/airship/airshipctl/pkg/util"
)
func TestReadYAMLFile(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
var actual map[string]interface{}
err := util.ReadYAMLFile("tes... |
package versions
import (
"fmt"
"strings"
"github.com/blang/semver/v4"
"github.com/mmcdole/gofeed"
)
func LatestVersion(repo string, currentVersion semver.Version, upgradeMajor, includePreReleases bool) (string, error) {
fp := gofeed.NewParser()
feed, err := fp.ParseURL(repo + "/releases.atom")
if err != nil ... |
package util
import "fmt"
func BuildError(info string, err error) string {
return fmt.Sprintf("%s, 错误信息: [ %s ]", info, err)
} |
package mobile
import (
"fmt"
"net/http"
"os"
"strings"
"testing"
"github.com/golang/protobuf/proto"
icid "github.com/ipfs/go-cid"
"github.com/libp2p/go-libp2p-core/peerstore"
"github.com/segmentio/ksuid"
"github.com/textileio/go-textile/core"
"github.com/textileio/go-textile/ipfs"
"github.com/textileio/g... |
package main
import "syscall"
func getSyscall(r *syscall.PtraceRegs) int {
return int(r.Orig_eax)
}
func getArgAddr(r *syscall.PtraceRegs, argnum int) uintptr {
switch argnum {
case 0:
return uintptr(r.Ebx)
case 1:
return uintptr(r.Ecx)
case 2:
return uintptr(r.Edx)
}
return 0
}
func getArgInt(r *sysca... |
package kubeconfig
import (
"strconv"
"sync"
"github.com/pkg/errors"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/clientcmd/api"
)
var loadOnceMutext sync.Mutex
var loadOnce sync.Once
var loadedConfig clientcmd.ClientConfig
// AuthCommand is the name of the command used to get auth token for kube... |
// Based on text/template/parse/lex.go
package pydict
import (
"fmt"
"strings"
"unicode/utf8"
)
var _ = fmt.Println
const eof = -1
const (
itemError = iota
itemEOF
itemLeftBrace
itemRightBrace
itemLeftBracket
itemRightBracket
itemString
itemComma
itemColon
)
type itemType int
type item struct {
iTyp... |
package entity
// List struct (Model)
type List struct {
ID string `json:"ID"`
UID string `json:"UID"`
Name string `json:"Name"`
}
// Task struct (Model)
type Task struct {
ID string `json:"ID"`
ListID string `json:"ListID"`
UID string `json:"UID"`
Name string `json:"Name"`
}
|
package main
import (
"fmt"
"unicode"
"bufio"
"os"
)
func to_celsius(f float64) float64 { return (f - 32) * 5/9 }
func to_fahrenheit(c float64) float64 { return (c * 9/5) + 32 }
func main() {
fmt.Println("Press C to convert from Fahrenheit to Celsius.")
fmt.Println("Press F to convert from... |
package cli
import (
"context"
"fmt"
"github.com/evan-buss/openbooks/core"
"github.com/evan-buss/openbooks/irc"
)
type Config struct {
UserName string // Username to use when connecting to IRC
Log bool // True if IRC messages should be logged
Dir string
Server string
irc *irc.Conn
}
// S... |
package target
import (
"encoding/json"
"fmt"
)
type TargetResult struct {
Name string `json:"name"`
Options TargetResultOptions `json:"options"`
}
func newTargetResult(name string, options TargetResultOptions) *TargetResult {
return &TargetResult{
Name: name,
Options: options,
}
}
type... |
package database
type TbSchedule struct {
ID uint
IntervalForReading int `gorm:"column:intervalforreading"`
IntervalForEvent int `gorm:"column:intervalforevent"`
}
func (TbSchedule) TableName() string {
return "tb_schedule"
}
|
package log
import (
"io"
stdLog "log"
)
// Отключение логгирования
const NONE = 0
// Система находится в неработоспособном состоянии
const EMERGENCY = 1
// Требуется немедленное реагирование (например, база не доступна)
const ALERT = 2
// Критическая ошибка (что-то не работает, требует исправления)
const CRITIC... |
package main
import (
"fmt"
"log"
"net/http"
"sync"
)
var url = []string{
"https://google.com",
"https://www.twitter.com",
"https://facebook.com",
}
func fetchstatus(w http.ResponseWriter, r *http.Request) {
var wg sync.WaitGroup
// for _, urls := range url {
wg.Add(1)
func() {
resp, err := http.Get("ht... |
package movie
type Ne_Movie struct {
//Movie
Title string //片名
PriceCode int //价格代号
}
func (m Ne_Movie) GetCharge(daysRented int) float64 {
result := 0.0
result += float64(daysRented) * float64(3)
return result
}
func (m Ne_Movie) GetPoint(daysRented int) int {
if daysRented > 1 {
return 2
} e... |
package client
import (
"github.com/devopstoday11/tarian/pkg/tarianpb"
"google.golang.org/grpc"
)
func NewConfigClient(serverAddress string, opts ...grpc.DialOption) (tarianpb.ConfigClient, error) {
grpcConn, err := grpc.Dial(serverAddress, opts...)
return tarianpb.NewConfigClient(grpcConn), err
}
func NewEvent... |
package main
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// 迭代 + 队列 实现层序遍历
func levelOrder(root *TreeNode) [][]int {
if root == nil {
return [][]int{}
}
levelOrderSequence := make([][]int, 0)
queue := make([]*TreeNode, 0)
queue = append(queue, root)
for len(queue) != 0 {
size := le... |
package config
type channels struct {
Console string `yaml:"console,omitempty"`
Errors string `yaml:"errors,omitempty"`
Logs string `yaml:"logs,omitempty"`
}
type bot struct {
GuildID string `yaml:"guild_id,omitempty"`
Channels channels `yaml:"channels,omitempty"`
Templates string `yaml:"templates,om... |
package talkio
import (
"errors"
"io"
"unicode/utf8"
)
// A StringReader implements the io.StringReader, io.ReaderAt, io.Seeker, io.WriterTo,
// io.ByteScanner, and io.RuneScanner interfaces by reading
// from a string.
type StringReader struct {
s string
i int64 // current reading index
prevRune ... |
// Copyright 2018 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 database
import (
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
"encoding/json"
_ "log"
"math/rand"
"net/http"
"strconv"
"time"
)
type UserStore struct {
db *gorm.DB
}
type UserResource struct {
Store *UserStore
Ctl *Control
}
type MyUser struc... |
package main
import (
"encoding/json"
"flag"
"fmt"
"os"
"os/exec"
"strings"
)
type Library struct {
Genres map[string]map[string]Song `json:"genres"`
}
type Song struct {
Artists []string `json:"artists"`
Links []string `json:"links"`
}
func main() {
config := flag.String("f", "", "file containing your ... |
package common
const (
GUEST_LOGIN = uint32(1) // 游客登录
FYSDK_ONLINE = uint32(2) // FYSDK联网版本
FYSDK_OFFLINE = uint32(3) // FYSDK单机版本
)
|
package main
import (
"context"
"flag"
"log"
"os"
"time"
"github.com/hypoballad/toecutter/toecuttergrpc"
"google.golang.org/grpc"
)
var addr = flag.String("addr", "localhost:50051", "server address")
var name = flag.String("name", "", "hashes|reward|account/stats|account/site|account/payments|sitestats|paymen... |
package keys
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"github.com/bbucko/cli-iec/common/ini-repo"
"log"
)
type RSAKey struct {
KeyName string
PrivateKey string
PublicKey string
}
func FetchRSAKeyByName(name string) (key RSAKey, err error) {
log.Printf("Searching repositor... |
package main
import (
"bufio"
"flag"
"fmt"
"math/big"
"os"
"time"
)
// TimeEntry
type TimeEntry struct {
Project string `json:"project"`
Task string `json:"task"`
Duration int `json:"duration"`
Start time.Time `json:"start"`
End time.Time `json:"end"`
}
func NewTimer(project strin... |
package env
import (
"errors"
"github.com/andybar2/team/store"
"github.com/spf13/cobra"
)
var setParams struct {
Stage string
Name string
Value string
}
var setCmd = &cobra.Command{
Use: "set",
Short: "Set an environment variable",
RunE: runSetCmd,
}
func init() {
setCmd.Flags().StringVarP(&setParams... |
package cmd
import (
"fmt"
"os"
"strings"
"io/ioutil"
"path/filepath"
"code.cloudfoundry.org/cfdev/config"
"code.cloudfoundry.org/cfdev/env"
"code.cloudfoundry.org/cfdev/resource"
)
type Download struct {
Exit chan struct{}
UI UI
Config config.Config
}
func (d *Download) Run(args []string) error {... |
package disk
import (
"bytes"
"fmt"
"syscall"
"text/template"
"time"
"github.com/pelletier/go-toml"
"github.com/rumpelsepp/i3gostatus/lib/config"
"github.com/rumpelsepp/i3gostatus/lib/model"
"github.com/rumpelsepp/i3gostatus/lib/utils"
)
const (
name = "disk"
moduleName = "i3gostatus.modules."... |
// Copyright 2014 The Cockroach 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 ag... |
package main
import (
"flag"
"fmt"
"log"
"net"
"strconv"
"google.golang.org/grpc"
auth_rep "2019_2_IBAT/pkg/app/auth/repository"
"2019_2_IBAT/pkg/app/auth/service"
"2019_2_IBAT/pkg/app/auth/session"
"2019_2_IBAT/pkg/pkg/config"
)
func main() {
lis, err := net.Listen("tcp", ":"+strconv.Itoa(config.AuthSer... |
// BCM2835Bridge
// package BCM2835Bridge
// #cgo LDFLAGS: -l bcm2835 -static
package main
import (
"C"
"bcm2835"
"fmt"
"log"
)
func main() {
fmt.Println("SPI loop back!")
// Initialize the library
if err := bcm2835.Init(); err != nil {
log.Fatal(err)
}
// continues on the next slide
// SPLIT OMIT
bcm28... |
package cp
import (
"dappapi/models"
"dappapi/tools/app"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/sirupsen/logrus"
)
func Report(c *gin.Context) {
cCp := c.Copy()
go func() {
var report models.JsonBody
err := cCp.ShouldBindWith(&report, binding.JSON)
if err != nil {
... |
/*
* Copyright (C) 2016-Present Pivotal Software, Inc. All rights reserved.
*
* This program and the accompanying materials are made available under
* the terms of the 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 ... |
package handler
import (
"context"
"errors"
"fmt"
"time"
"github.com/jinmukeji/jiujiantang-services/subscription/mysqldb"
proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/subscription/v1"
)
// AddUsersIntoSubscription 将用户添加到订阅中
func (j *SubscriptionService) AddUsersIntoSubscription(ctx context.C... |
package _132_Palindrome_Partitioning_2
import (
"math"
)
func minCut(s string) int {
n := len(s)
judge := make([][]bool, n)
for idx := range judge {
judge[idx] = make([]bool, n)
}
dp := make([]int, n) // dp[i]为s中第i位到第n-1位的子字符串中,最小分割次数
for i := n - 1; i >= 0; i-- {
dp[i] = math.MaxInt32
for j := i; j < n;... |
package main
import (
"fmt"
"net/http"
"os"
)
func main() {
paths := os.Args[1:]
for _, path := range paths {
xx(path)
}
}
// Connect to an url by turning off wi-fi or not
func xx(url string) {
type expected struct{}
defer func() {
if p := recover(); p != nil {
switch p {
case nil:
fmt.Println(... |
package queue
import (
"testing"
"time"
. "github.com/smartystreets/goconvey/convey"
)
func TestArrayQueue(t *testing.T) {
Convey("array queue", t, func() {
q := &ArrayQueue{}
q.Push(1)
So(q.Len(), ShouldEqual, 1)
q.Push(2)
So(q.Len(), ShouldEqual, 2)
e := q.Pop()
So(e, ShouldEqual, 2)
So(q.Len(... |
package dockerfile
import (
"bytes"
"github.com/mitchellh/packer/builder/docker"
)
// MockDriver is a driver implementation that can be used for tests.
type MockDriver struct {
*docker.MockDriver
BuildImageCalled bool
BuildImageDockerfile *bytes.Buffer
BuildImageErr error
}
func (d *MockDriv... |
// 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 app
import (
"errors"
"fmt"
"math/rand"
"net/http"
"strconv"
"strings"
"text/template"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres" // cockroachdb
otp "github.com/pquerna/otp/totp"
"github.com/wader/gormstore"
"golang.org/x/crypto/bcrypt"
"gopkg.... |
/*
Бот создан в рамках проекта Bablofil, подробнее тут
https://bablofil.ru/vnutrenniy-arbitraj-chast-2/
или на форуме https://forum.bablofil.ru/
*/
package main
import (
"sync"
)
/* Структуры для деревьев хранения стаканов */
type leaf struct {
left *leaf
price float64 // Depth level price
vol float64 // D... |
package main
// 迭代 求 n! 尾部有多少个零
func trailingZeroes(n int) int {
ans := 0
for n != 0 {
ans += n / 5
n = n / 5
}
return ans
}
/*
题目链接: https://leetcode-cn.com/problems/factorial-trailing-zeroes/comments/
*/
/*
总结
1. 要求n!有多少个零,就是求n!由多少个10相乘。
那么由于10由质因子2和5组成,那么我们只需要求n!有多少个因子2和因子5就可以了,再取二者的最小值就可以了。
又由于... |
package auth
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document01800101 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:auth.018.001.01 Document"`
Message *ContractRegistrationRequestV01 `xml:"CtrctRegnReq"`
}
func (d *Document01... |
package jdsfapi
import (
"fmt"
"github.com/hashicorp/consul/api"
"math/rand"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"time"
)
const consulHostEnv = "CONSUL_HOST"
const consulPortEnv ="CONSUL_PORT"
type RegistryClient struct {
Address string
Port int
Scheme string
Client *api.Client
}
var(
JDSFR... |
package tsrv
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document00500101 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:tsrv.005.001.01 Document"`
Message *UndertakingAmendmentV01 `xml:"UdrtkgAmdmnt"`
}
func (d *Document00500101) AddMes... |
package terminal
import (
"fmt"
"strconv"
)
func CursorUp(n int) {
fmt.Print("\x1b[" + strconv.Itoa(n) + "A")
}
func CursorDown(n int) {
fmt.Print("\x1b[" + strconv.Itoa(n) + "B")
}
func CursorRight(n int) {
fmt.Print("\x1b[" + strconv.Itoa(n) + "C")
}
func CursorLeft(n int) {
fmt.Print("\x1b[" + strconv.Itoa... |
package controller
import (
"database/sql"
"github.com/go-redis/redis/v8"
)
type Controller struct {
Rds *redis.Client
DB *sql.DB
}
|
/*
Copyright The Helm 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, software
di... |
// Copyright 2015 The Go 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 format contains types for defining language-specific formatting of
// values.
//
// This package is internal now, but will eventually be exposed afte... |
//+build wireinject
package service
import (
"sync"
"github.com/google/wire"
)
// Container contains all the services of the api.
// If you create a new service, be sure to add it in the Container and add its provider to the ServiceProviderSet
type Container struct {
Connection *Connection
Logger *Logger
Migra... |
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"github.com/opentracing/opentracing-go"
openlog "github.com/opentracing/opentracing-go/log"
"gopkg.in/oauth2.v3/utils/uuid"
"log"
"net/http"
"sort"
"strconv"
)
// PingPong return a pong
func PingPong(c *gin.Context) {
c.JSON(... |
package cfg
import (
"strings"
)
func emptyGetter(keys ...string) interface{} {
return nil
}
var values = map[string]interface{}{
"Str": "foobar",
"Int": 1,
"Nested.Level2_Int": 2,
"str": "foobar",
"int": 1,
"int64": int64(1),
"uint16": ... |
/*
* @lc app=leetcode.cn id=842 lang=golang
*
* [842] 将数组拆分成斐波那契序列
*/
package main
import (
"math"
)
// @lc code=start
func splitIntoFibonacci(num string) []int {
ret := []int{}
var backtrack func(index, sum, pre int) bool
backtrack = func(index, sum, pre int) bool {
if index == len(num) {
return len(ret... |
package volume
import (
"errors"
"fmt"
"strconv"
"github.com/Huawei/eSDK_K8S_Plugin/src/storage/oceanstor/client"
"github.com/Huawei/eSDK_K8S_Plugin/src/storage/oceanstor/smartx"
"github.com/Huawei/eSDK_K8S_Plugin/src/utils/log"
)
const (
HYPERMETROPAIR_HEALTH_STATUS_FAULT = "2"
HYPERMETROPAIR_RUNNING_STA... |
package gateway
import (
"bytes"
"testing"
)
func TestMac_MarshalText(t *testing.T) {
m := Mac{1, 2, 3, 4, 5, 6, 7, 8}
text, err := m.MarshalText()
if err != nil {
t.Error(err)
}
if !bytes.Equal(text, []byte("0102030405060708")) {
t.Errorf("Expected text to be 12345678 but was %s", string(text))
}
}
f... |
package depth
import s "github.com/SimonRichardson/depth/selectors"
type transaction struct {
list *List
stash s.Iterator
}
func NewTransaction() s.Transaction {
return &transaction{
list: NewList(),
}
}
func (t *transaction) Undo() (s.Action, bool) {
if action, ok := t.list.Left(); ok {
return action, ac... |
package controller
import (
"encoding/json"
"time"
"github.com/therecipe/qt/core"
"github.com/therecipe/qt/internal/examples/showcases/wallet/files/model"
)
var FilesController *filesController
type filesController struct {
core.QObject
_ func() `constructor:"init"`
_ *model.FilesModel `... |
package main
import (
"encoding/json"
"fmt"
"os"
"time"
"go.uber.org/zap/zapcore"
"go.uber.org/zap"
)
func main() {
fmt.Printf("*** Build a logger from a json\n\n")
rawJSONConfig := []byte(`{
"level": "info",
"encoding": "console",
"outputPaths": ["stdout", "/tmp/logs"],
"errorOutputPaths": ["/tmp/erro... |
package main
import "fmt"
func multipicao(a, b int) int {
return a * b
}
func exec(funcao func(int, int) int, parametro1, parametro2 int) int {
return funcao(parametro1, parametro2)
}
func main() {
resultado := exec(multipicao, 4, 3)
fmt.Println("Resultado:", resultado)
}
|
package utils
import (
"errors"
"github.com/darkliquid/leader1/database"
"strings"
"time"
)
func LikeTrack(nick, track string) (bool, error) {
db, err := database.DB()
if err != nil {
return false, err
}
if strings.TrimSpace(nick) == "" {
return false, errors.New("Empty nick")
}
if strings.TrimSpace(t... |
package server
import (
"net/http"
"github.com/gorilla/mux"
)
type API2 struct {
Mux http.Handler
}
func NewAPI2() *API2 {
m := mux.NewRouter()
a := &API2{
Mux: m,
}
return a
}
|
package main
import (
"math/rand"
"os"
"time"
"k8s.io/component-base/logs"
"k8s.io/kubernetes/cmd/cloud-controller-manager/app"
_ "k8s.io/component-base/metrics/prometheus/clientgo" // load all the prometheus client-go plugins
_ "k8s.io/component-base/metrics/prometheus/version" // for version metric registr... |
/*
Copyright 2021 The KubeDiag 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, so... |
package services
import (
"crypto/rsa"
"fmt"
jwt "github.com/dgrijalva/jwt-go"
"github.com/RicardoCampos/goauth/oauth2"
)
type tokenPayload struct {
Issuer string `json:"iss"`
Scope string `json:"scope"`
}
func signToken(input jwt.StandardClaims, rsaKey *rsa.PrivateKey) (string, error) {
// get the signing ... |
package reset
import (
"os"
"github.com/devspace-cloud/devspace/pkg/devspace/dependency"
"github.com/devspace-cloud/devspace/pkg/util/factory"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
type dependenciesCmd struct {
}
func newDependenciesCmd(f factory.Factory) *cobra.Command {
cmd := &dependenciesCmd... |
package KMP
/*
字符串匹配。给你两个字符串,寻找其中一个字符串是否包含另一个字符串,如果包含,返回包含的起始位置。
字符串长度分别为n,m (n > m).
算法复杂度O(n + m).
充分利用了目标字符串ptr的性质(比如里面部分字符串的重复性,即使不存在重复字段,在比较时,实现最大的移动量)。
考察目标字符串ptr:
ababaca
这里我们要计算一个长度为m的转移函数next。
next数组的含义就是一个固定字符串的最长前缀和最长后缀相同的长度。
比如:abcjkdabc,那么这个数组的最长前缀和最长后缀相同必然是abc。
... |
/*
Description
Uniform Resource Identifiers (or URIs) are strings like http://icpc.baylor.edu/icpc/, mailto:foo@bar.org, ftp://127.0.0.1/pub/linux, or even just readme.txt that are used to identify a resource, usually on the Internet or a local computer. Certain characters are reserved within URIs, and if a reserved ... |
package models
type ToDo struct {
Id string `json:"Id" bson:"_id,omitempty"`
Title string `json:"Title"`
Description string `json:"Description"`
Completed bool `json:"Completed"`
}
|
package ibeplus
import (
"encoding/xml"
"github.com/otwdev/ibepluslib/models"
"github.com/otwdev/galaxylib"
)
const rtURL = "http://ibeplus.travelsky.com/ota/xml/AirResRet"
type RT struct {
PNR *models.PnrInfo
}
func NewRT(pnr *models.PnrInfo) *RT {
return &RT{pnr}
}
func (r *RT) RTPNR() (rs *RTRSOTA_AirRes... |
// Licensed to SolID under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. SolID licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compli... |
package command
import (
"fmt"
"strings"
"time"
"github.com/jixwanwang/jixbot/channel"
)
const (
commandFilePath = "data/textcommands/"
configFilePath = "data/config/"
globalChannel = "_global"
)
type Command interface {
ID() string
Init()
Response(username, message string, whisper bool)
}
var BadComm... |
package main
func Combination1(nums []int, n int) [][]int {
ps := Powerset2(nums)
result := make([][]int, CombinationCount(len(nums), n))
index := 0
for _, s := range ps {
if len(s) == n {
result[index] = s
index++
}
}
return result
}
func Combination2(nums []int, n int) [][]int {
size := len(nums)
... |
package protoform
import "fmt"
const (
message = iota
enum
)
// protobufType is one of message, or enum
type protobufType uint8
// Proto is a struct which contains the components of a protobuf file
type Proto struct {
FileName string
Type string
Syntax string
Package string
Properties []Messag... |
package main
import (
"fmt"
)
func twoSum(nums []int, target int) []int {
m := make(map[int]int)
for i, n := range nums {
fmt.Println(m[n])
fmt.Println(i)
_, prs := m[n]
fmt.Println(prs)
if prs {
return []int{m[n], i}
} else {
m[target-n] = i
}
}
... |
package publishtweet
import (
"io/ioutil"
"testing"
"github.com/TIBCOSoftware/flogo-lib/core/activity"
)
var activityMetadata *activity.Metadata
func getActivityMetadata() *activity.Metadata {
if activityMetadata == nil {
jsonMetadataBytes, err := ioutil.ReadFile("activity.json")
if err != nil {
panic("... |
package internal
import (
"testing"
"time"
)
const testApplicationNamespace = "test_diane"
var whois = NewWhoisClient(testApplicationNamespace)
type whoisTestData struct {
target string
domain string
hasExpiration bool
expiration time.Time
}
func TestWhoisClientAvailable(t *testing.T) {
va... |
package problem0206
// ListNode singly-linked list
type ListNode struct {
Val int
Next *ListNode
}
func reverseList(head *ListNode) *ListNode {
var newHead *ListNode
cur := head
for cur != nil {
// 要处理的下个指针
next := cur.Next
// 反转指针
cur.Next = newHead
// 新的队头
newHead = cur
// 更新指针
cur = next
}
... |
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0.
package trace
import (
"context"
"os"
"path"
"testing"
"time"
"github.com/opentracing/opentracing-go"
"github.com/stretchr/testify/require"
)
func jobA(ctx context.Context) {
if span := opentracing.SpanFromContext(ctx); span != nil && span.Tracer() ... |
package rediscookiestore
import (
"encoding/json"
"fmt"
"github.com/go-redis/redis"
"github.com/rmdashrf/go-misc/cookiejar2"
)
var (
// SETANDPUB <setkey> <pubkey> <val> <token>
// will set <setkey> to <val>, and then publish <token>
// to the pubsub key <pubkey>
scriptSetAndPublishSrc = `
local val = ARGV[1... |
package stash
import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"testing"
)
var (
branches string = `
{
"isLastPage" : true,
"filter" : null,
"values" : [
{
"displayId" : "develop",
"isDefault" : true,
"latestChangeset" : "e680a10f3e0afb5e3a5978dea02d37ac884da21",... |
// Copyright 2022 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 model
import (
"github.com/mongodb/mongo-go-driver/bson"
"github.com/mongodb/mongo-go-driver/bson/primitive"
)
// IPFS ...
type IPFS struct {
Model `bson:",inline"`
MediaID primitive.ObjectID `bson:"media_id"`
FileID string `bson:"file_id"`
IPFSAddress string `bson... |
package main
import (
"fmt"
)
func Hello() {
fmt.Println("Hello from: hello.go")
}
|
// Packge gdbm implements a wrapper around libgdbm, the GNU DataBase Manager
// library, for Go.
package gdbm
// #cgo CFLAGS: -std=gnu99
// #cgo LDFLAGS: -lgdbm
// #include <stdlib.h>
// #include <gdbm.h>
// #include <string.h>
// inline datum mk_datum(char * s) {
// datum d;
// d.dptr = s;
// d.dsize = st... |
// Copyright 2021 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 x
// GENERATED BY XO. DO NOT EDIT.
import (
"errors"
"strings"
//"time"
"ms/sun/shared/helper"
"strconv"
"github.com/jmoiron/sqlx"
)
// (shortname .TableNameGo "err" "res" "sqlstr" "db" "XOLog") -}}//(schema .Schema .Table.TableName) -}}// .TableNameGo}}// PostMedia represents a row from 'sun.post_medi... |
package model
import "strconv"
const (
// Black is one of the two chess colors
Black = Color(iota)
// White is one of the two chess colors
White = Color(iota)
)
type (
// Color of a piece or player
Color uint8
// Position is a struct representing a chess piece's position
Position struct {
File, Rank uint8... |
package goSolution
func longestConsecutive(nums []int) int {
set := make(map[int]bool)
for _, num := range nums {
set[num] = true
}
ret := 0
for _, num := range nums {
if set[num] {
t := 1
for l := num - 1; set[l]; l-- {
t += 1
set[l] = false
}
for r := num + 1; set[r]; r++ {
t += 1
... |
// Package compute contains the client for Dimension Data's cloud compute API.
package compute
import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"sync"
"time"
"github.com/DimensionDataResearch/go-dd-cloud-compute/compute/requests"
"github.com/pkg/errors"
)
// C... |
package service_example
import (
"fmt"
"github.com/muka/go-bluetooth/bluez/profile/gatt"
"github.com/muka/go-bluetooth/service"
log "github.com/sirupsen/logrus"
)
func registerApplication(adapterID string) (*service.Application, error) {
cfg := &service.ApplicationConfig{
AdapterID: adapterID,
UUIDSuffix:... |
package ackhandler
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Send Mode", func() {
It("has a string representation", func() {
Expect(SendNone.String()).To(Equal("none"))
Expect(SendAny.String()).To(Equal("any"))
Expect(SendAck.String()).To(Equal("ack"))
Expect(SendRT... |
package models
import (
"fmt"
"time"
"github.com/mmcdole/gofeed/extensions"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type User struct {
ID bson.ObjectId `bson:"_id"`
Username string `bson:"username"`
Lastname string `bson:"lastname"`
Firstname s... |
package api
import (
"bytes"
"fmt"
"github.com/gocarina/gocsv"
"os"
"regexp"
)
type Stop struct {
ID string `csv:"stop_id"`
Name string `csv:"stop_name"`
ParentID string `csv:"parent_station"`
stationID string
ChildIDs []string
}
type Station struct {
ID int
StopIDs []string
Name ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.