text stringlengths 11 4.05M |
|---|
package main
import (
"container/list"
"encoding/json"
"github.com/gorilla/websocket"
"log"
"sync"
"time"
)
//Constant
const (
FIELD_SIZE = 50
STEP_SIZE = 3
CANVAS_SIZE = 1000
STANDARD_BOMB_RADIUS = 2
STANDARD_BOMB_TIME = 3
STANDARD_STEP_M... |
// Copyright (C) 2015 Nippon Telegraph and Telephone Corporation.
//
// 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 egressipam
import (
"encoding/binary"
"errors"
"net"
"sort"
"strings"
"github.com/jpillora/ipmath"
"github.com/redhat-cop/egressip-ipam-operator/controllers/egressipam/reconcilecontext"
"github.com/scylladb/go-set/strset"
"github.com/scylladb/go-set/u32set"
corev1 "k8s.io/api/core/v1"
"sigs.k8s.io/... |
package proxy
import (
"crypto/tls"
"fmt"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/context"
"net/http"
"net/http/httputil"
"net/url"
)
func KubernetesClientProxy(ctx context.Context) {
clusterName := ctx.Params().Get("cluster_name")
proxyPath := ctx.Params().Get("p")
endpoint, err := clust... |
//
// Copyright (C) 2019-2021 vdaas.org vald team <vald@vdaas.org>
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless requir... |
package signup
import (
"fmt"
"github.com/rs/zerolog/log"
"github.com/saucelabs/saucectl/internal/sentry"
"github.com/spf13/cobra"
"os"
)
var (
runUse = "signup"
runShort = "Signup for Sauce Labs"
runLong = "Provide a web link for free trial signup"
runExample = "saucectl signup"
defaultLogFir = "... |
package sqlite
import (
"context"
"database/sql"
"log"
"github.com/hezbymuhammad/payment-gateway/domain"
)
type sqliteMerchantRepo struct {
DB *sql.DB
}
func NewMerchantRepository(db *sql.DB) domain.MerchantRepository {
return &sqliteMerchantRepo{
DB: db,
}
}
func (mr *sqliteMerchantR... |
package service
import (
"bytes"
"github.com/gorilla/mux"
"github.com/koind/shortener-servis/mystats"
"go.uber.org/zap"
"net/http"
)
// Shortener implements business logic for the shortener service
type Shortener interface {
Shorten(url string) string
Resolve(url string) string
}
type ShortenerService struct ... |
// 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 ... |
package cbor
import (
"testing"
"github.com/polydawn/refmt/tok/fixtures"
)
func testComposite(t *testing.T) {
t.Run("array nested in map as non-first and final entry, all indefinite length", func(t *testing.T) {
seq := fixtures.SequenceMap["array nested in map as non-first and final entry"].SansLengthInfo()
c... |
package max
import (
"github.com/maprost/application/example/max/jobposition/bunny"
"github.com/maprost/application/example/max/jobposition/santa"
"github.com/maprost/application/example/max/profile"
"github.com/maprost/application/generator/genmodel"
)
func Application(company string) genmodel.Application {
app... |
package handlers
import (
"coffeebeans-people-backend/auth"
"coffeebeans-people-backend/models"
"coffeebeans-people-backend/utility"
"context"
"encoding/json"
"net/http"
)
func Login(svc models.ApiSvc, authSvc auth.AuthSvc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var body mod... |
package game_map
import (
"fmt"
"github.com/faiface/pixel"
"github.com/faiface/pixel/imdraw"
"github.com/faiface/pixel/pixelgl"
"github.com/faiface/pixel/text"
"github.com/sirupsen/logrus"
"github.com/steelx/go-rpg-cgm/combat"
"github.com/steelx/go-rpg-cgm/gui"
"github.com/steelx/go-rpg-cgm/state_machine"
"g... |
package ratelimiter_test
import (
"crypto/rand"
"encoding/hex"
"errors"
"sort"
"sync"
"testing"
"time"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/teambition/ratelimiter-go"
"gopkg.in/redis.v5"
)
// Implements RedisClient for redis.Client
type redisClient struct {
*redis.Client
}
f... |
package game
// FarseerOperation view people role
func FarseerOperation(players []Player) Player {
votes := CollectVote(players, players)
result := GetVoteResult(votes)
return result.target[0]
}
|
package main
/*
读取config.yaml 文件
对yaml里面的site进行http检查
huangmingyou@gmail.com
2021.07
*/
import (
"github.com/robfig/cron/v3"
"crypto/tls"
"flag"
"fmt"
"gopkg.in/yaml.v2"
"io/ioutil"
"log"
"net"
"net/http"
"net/http/httptrace"
"os"
"regexp"
"strconv"
"strings"
"time"
)
var cfgfile string
var metrics str... |
// +build small
/*
http://www.apache.org/licenses/LICENSE-2.0.txt
Copyright 2016 Intel Corporation
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
... |
package myheap
import (
"fmt"
)
type IndexMaxHeap struct {
data []int // 最大索引堆中的数据,类型可以变
indexes []int // 最大索引堆中的索引, indexes[x] = i 表示索引i在x的位置
reverse []int // 最大索引堆中的反向索引, reverse[i] = x 表示索引i在x的位置
count int // 当前堆容量
capacity int //初始化容量
}
// 构造函数, 构造一个空堆, 可容纳capacity个元素
func NewIndexMaxHeap(cap ... |
// +build mage
package main
import (
"errors"
"fmt"
"image"
"image/jpeg"
"os"
"path"
"github.com/nfnt/resize"
"github.com/magefile/mage/mg"
)
// Optimize images to web
func Optimize() error {
mg.Deps(OptimizeImages)
return nil
}
func loadImage(path string) (image.Image, error) {
f, err := os.Open(pa... |
// 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... |
package main
import (
"fmt"
"github.com/therecipe/qt/core"
"github.com/therecipe/qt/widgets"
)
func containers() {
//Group Box
groupBox := widgets.NewQGroupBox2("Group Box", nil)
groupBox.SetWindowTitle("Group Box")
groupBoxLayout := widgets.NewQVBoxLayout2(groupBox)
for i := 0; i < 3; i++ ... |
// Copyright 2017 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 main
import (
"io"
"log"
"net"
"time"
)
func main() {
ln, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatalf("Something went wrong while creating to Listener : %v", err)
}
for {
conn, err := ln.Accept()
if err != nil {
log.Printf("Something went wrong while accepting to conn : %v", ... |
package resolvers
import (
"context"
"github.com/syncromatics/kafmesh/internal/graph/generated"
"github.com/syncromatics/kafmesh/internal/graph/model"
"github.com/pkg/errors"
)
//go:generate mockgen -source=./query.go -destination=./query_mock_test.go -package=resolvers_test
// QueryLoader is the loader for qu... |
package day1
import "testing"
var testInput = []int{1721,979,366, 299, 675, 1456}
func Test_calc(t *testing.T) {
type args struct {
lines *[]int
}
tests := []struct {
name string
args args
want int
wantErr bool
}{
{"Expect 514579", args{&testInput}, 514579, false},
}
for _, tt := range tes... |
// Copyright © 2017 Heptio
// 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 writin... |
// Package driver is an sqlite driver.
package driver
import (
"database/sql"
"embed"
"encoding/base64"
"fmt"
"io/fs"
"strings"
_ "modernc.org/sqlite"
"github.com/volatiletech/sqlboiler/v4/drivers"
"github.com/volatiletech/sqlboiler/v4/importers"
)
//go:embed override
var templates embed.FS
func init() {
... |
package config
import (
"context"
"os"
"path/filepath"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestFileWatcherSource(t *testing.T) {
ctx := context.Background()
tmpdir := t.TempDir()
err := os.WriteFile(filepath.Join(tmpdir, "example.txt"), []byte{1, 2, 3, 4}, 0o600)
if !asse... |
package factories
import (
"bytes"
"context"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"syscall"
"time"
"github.com/Azure/azure-pipeline-go/pipeline"
"github.com/Azure/azure-storage-blob-go/azblob"
"github.com/giventocode/azure-blob-md5/internal"
)
//azUtil TODO
type azUtil struct {
serviceURL *azbl... |
// DO NOT EDIT. This file was generated by "github.com/frk/gosql".
package testdata
import (
"github.com/frk/gosql"
"github.com/frk/gosql/internal/testdata/common"
)
func (q *InsertResultErrorHandlerSingleQuery) Exec(c gosql.Conn) error {
const queryString = `INSERT INTO "test_user" AS u (
"id"
, "email"
, ... |
package repository
import (
"database/sql"
"github.com/bot/myteambot/app/models"
"github.com/volatiletech/sqlboiler/boil"
"github.com/volatiletech/sqlboiler/queries/qm"
)
func InsertGroup(chatID int64, name string) {
var group models.Group
group.ChatID = chatID
group.Name = name
group.InsertG(boil.Infer())... |
package main
import "fmt"
const MAX int =3
func main() {
a :=[] int {12,24,36}
var i int
var ptr [MAX] *int
for i=0;i<MAX;i++{
ptr[i]=&a[i]
}
for i=0;i< MAX;i++ {
fmt.Printf("values of a[%d] =%d\n",i,*ptr[i])
}
var m int ;
m=100;
var m1 *int
m1=&m;
var m2 **int
m2=&m1
fmt.Printf("the value is %d... |
package main
import (
"net/http"
"ratelimit/rate"
)
func myHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("DO SOME API STUFF!"))
}
func main() {
r := http.NewServeMux()
r.Handle("/bla", rate.RateHandler(http.HandlerFunc(myHandler)))
http.ListenAndServe(":2705", r)
}
|
package node
import (
"context"
"errors"
logging "github.com/ipfs/go-log"
"github.com/multiformats/go-multiaddr"
"github.com/shepf/star-tools/node/impl"
"github.com/shepf/star-tools/node/modules"
"github.com/shepf/star-tools/node/modules/helpers"
"github.com/shepf/star-tools/node/repo"
"github.com/shepf/star-... |
package main
import (
"fmt"
"github.com/Cloud-Foundations/Dominator/imageunpacker/client"
"github.com/Cloud-Foundations/Dominator/lib/log"
)
func exportImageSubcommand(args []string, logger log.DebugLogger) error {
err := client.ExportImage(getClient(), args[0], args[1], args[2])
if err != nil {
return fmt.Er... |
package csvparse
import (
"encoding/csv"
"os"
)
// LoadCSV loads the passed file name as a record.
func LoadCSV(s string) ([][]string, error) {
f, err := os.Open(s)
defer f.Close()
if err != nil {
return nil, err
}
r := csv.NewReader(f)
records, err := r.ReadAll()
if err != nil {
return nil, err
}
r... |
package cache
import (
"log"
"github.com/rapidclock/align-bot-stats-cache/models"
)
func GetGenderRatio() *models.GenderRatio {
curRatio := new(models.GenderRatio)
maleRatio, err := Get(GenderRatioMale)
if err != nil {
log.Fatal(err)
panic(err)
}
femaleRatio, err := Get(GenderRatioFemale)
if err != nil {
... |
package config
import (
"github.com/joho/godotenv"
"os"
"strconv"
)
type Config struct {
Protocol string `json:"protocol"`
Host string `json:"host"`
VHost string `json:"vhost"`
Port int `json:"port"`
Username string `json:"username"`
Password string `json:"password"`
}
func LoadConfig() (*Conf... |
package main
import (
"fmt"
)
// The d2() function also contains a for loop and a defer statement, which
// will also be executed three times. However, this time, the defer keyword is applied to an
// anonymous function instead of a single fmt.Print()
func d4() {
for i := 3; i > 0; i-- {
defer func() {
fmt.Pr... |
package main
import (
"fmt"
"github.com/blang/semver"
"github.com/magiconair/properties/assert"
"github.com/spf13/viper"
"gopkg.in/src-d/go-git.v4/plumbing/object"
"io/ioutil"
"testing"
"time"
)
func TestGetRepository(t *testing.T) {
_, err := getRepository(".")
if err != nil {
t.Fail()
}
_, err = getR... |
package installconfig
import (
"os"
"strings"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"sigs.k8s.io/yaml"
"github.com/openshift/installer/pkg/asset"
"github.com/openshift/installer/pkg/types"
"github.com/openshift/installer/pkg/types/conversion"
"github.com/openshift/installer/pkg/types/defaults... |
package main
import (
"bytes"
"fmt"
"io"
"os"
)
func main() {
var b bytes.Buffer
// 通过 string 构造一个byte数组,将数据写到Buffer中
b.Write([]byte("Hello"))
// 拼接一个字符串到Buffer中
fmt.Fprint(&b, " World!")
// 将数据写到标准输出
io.Copy(os.Stdout, &b)
}
|
package heap
import (
"fmt"
"testing"
"github.com/stretchr/testify/require"
)
func TestMaxHeapSort(t *testing.T) {
tests := []struct {
arr []int
want []int
}{
{
arr: []int{4, 2, 5, 1, 3},
want: []int{5, 4, 3, 2, 1},
},
{
arr: []int{5, 9, 1, 6, 8, 14, 6, 49, 25, 4, 6, 3},
want: []int{49,... |
package jobs
import (
"encoding/json"
"fmt"
"net/url"
"os"
"strconv"
"strings"
"github.com/spf13/cobra"
"github.com/makkes/gitlab-cli/api"
"github.com/makkes/gitlab-cli/cmd/get/output"
"github.com/makkes/gitlab-cli/table"
)
func NewCommand(client api.Client, format *string) *cobra.Command {
var pipeline ... |
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"testing"
"github.com/kpacha/load-test/db"
"github.com/kpacha/load-test/requester"
)
func TestNewExecutor_Run_contextCanceled(t *testing.T) {
store := db.NewInMemory()
exec := NewExecutor(store)
p := Plan{
Min: 1,
M... |
// Copyright 2016-2021, Pulumi Corporation.
package schema
import pschema "github.com/pulumi/pulumi/pkg/v3/codegen/schema"
// CloudAPIMetadata is a collection of all resources and types in the AWS Cloud Control API.
type CloudAPIMetadata struct {
Resources map[string]CloudAPIResource `json:"resources"`
Types m... |
package main
import (
"flag"
"github.com/golangcollege/sessions"
"github.com/jackc/pgx"
"html/template"
"log"
"module1/pkg/postgre"
"net/http"
"os"
"time"
)
type application struct {
errorLog *log.Logger
infoLog *log.Logger
session *sessions.Session
snippets *postgre.SnippetModel
t... |
/*
* @lc app=leetcode.cn id=1700 lang=golang
*
* [1700] 无法吃午餐的学生数量
*/
// @lc code=start
package main
func countStudents(students []int, sandwiches []int) int {
count := [2]int{}
for i := 0; i < len(students); i++ {
count[students[i]]++
}
for i := 0; i < len(sandwiches); i++ {
if count[sandwiches[i]] > 0 {... |
package notify
import (
pb "biohouse/api"
"git.huoys.com/middle-end/library/pkg/net/comet"
"github.com/gogo/protobuf/proto"
)
type Notify interface {
//AsyncPush 非阻塞式PUSH
AsyncPush(sessionID string, ops pb.GameCommand, msg proto.Message)
//SyncPush 阻塞式PUSH
SyncPush(sessionID string, ops pb.GameCommand... |
package requests
type LoginUser struct {
Username string
Password string
}
type RegistUser struct {
Username string
Password string
}
type CheckUsername struct {
Username string
}
func (c *LoginUser) Valid() error {
return validate.Struct(c)
}
func (c *RegistUser) Valid() error {
return validate.Struct(c)
}... |
package main
import (
"fmt"
"net/http"
"path"
"runtime"
"strings"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, fmt.Sprintf("%s/public%s", parentFilePathHelper(), r.URL.Path))
})
http.ListenAndServe(":8000", nil)
}
// urlHelper - returns the absol... |
package main
import (
"fmt"
"os"
"bufio"
"strings"
)
func doesReact(a, b string) bool {
capital := strings.ToUpper(a)
lower := strings.ToLower(a)
if (a == capital && b == lower) || (a == lower && b == capital) {
return true
}
return false
}
func main() {
f, _ := os.Ope... |
// +build linux darwin freebsd netbsd openbsd
package cmd
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"log"
"net/http"
// Import pprof handlers into http.DefaultServeMux
_ "net/http/pprof"
"os"
"os/signal"
"syscall"
"time"
docker "github.com/docker/engine-api/client"
"github.com/gorilla/mux"... |
package operators
import (
"github.com/onsi/ginkgo"
"github.com/openshift/osde2e/pkg/common/alert"
"github.com/openshift/osde2e/pkg/common/helper"
)
var configureAlertManagerOperators string = "[Suite: operators] [OSD] Configure AlertManager Operator"
var configureAlertManagerInforming string = "[Suite: informing]... |
package main
import (
"github.com/g-xianhui/op/server/pb"
"github.com/golang/protobuf/proto"
)
func echo(agent *Agent, p proto.Message) {
req := p.(*pb.MQEcho)
rep := &pb.MREcho{}
rep.Data = proto.String(req.GetData())
replyMsg(agent, pb.MECHO, rep)
}
func init() {
registerHandler(pb.MECHO, &pb.MQEcho{}, echo... |
package tls
import (
"crypto/x509"
"crypto/x509/pkix"
"github.com/openshift/installer/pkg/asset"
)
// KubeletCSRSignerCertKey is a key/cert pair that signs the kubelet client certs.
type KubeletCSRSignerCertKey struct {
SelfSignedCertKey
}
var _ asset.WritableAsset = (*KubeletCSRSignerCertKey)(nil)
// Dependen... |
package modules
import (
"fmt"
"io/ioutil"
"regexp"
"strings"
"github.com/wx13/genesis"
)
// LineInFile lets the user insert lines of text into a file.
type LineInFile struct {
// Required
File string // path to the file
Line []string // line(s) to insert
// Optional
Pattern []string // line(s) to repl... |
package game
type Position struct {
x int
y int
}
type Projectiles struct {
owner string
pos Position
}
type Frame struct {
player1Pos Position
player2Pos Position
projectiles []Projectiles
}
|
package graphql_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
"testing"
"time"
"github.com/graphql-go/graphql"
"github.com/graphql-go/graphql/gqlerrors"
"github.com/graphql-go/graphql/language/location"
"github.com/graphql-go/graphql/testutil"
)
func TestExecutesArbitraryCode(t *testing... |
package models
import (
"fmt"
"github.com/Sirupsen/logrus"
"gopkg.in/mgo.v2"
)
/*
type Player struct{
AccountID string
Chips int
}
type State struct{
CurrentPlayers []Player
ActivePlayer string
}
type Bet
type Hand struct{
Pot int
Bank int
State State
Actions []interface
}
type HighCard struct {
ID ... |
package linter
import (
"fmt"
"go/token"
"strings"
)
// Result is struct
type Result struct {
Position token.Position
Comment string
}
func NewResult(position token.Position, comment string) *Result {
// The `position` points out `type`, `func`, etc line. So, `position.Line` decrements here.
position.Line = ... |
package main
// DoctolibConfig holds the information of the config.yml doctolib link declaration
type DoctolibConfig struct {
URL string `mapstructure:"url"`
VaccineName string `mapstructure:"vaccine_name"`
PracticeID string `mapstructure:"practice_id"`
AgendaID string `mapstructure:"agenda... |
package router
import (
// "errors"
// "fmt"
"net/http"
"reflect"
"strings"
)
type StaticRouter struct {
Path string
DefaultCname string
DefaultAname string
routMap RouteMaps
}
func NewStaticRouter(path, defaultCname, defaultAname string) *StaticRouter {
t := new(StaticRouter)
t.Path = path
... |
func isInterleave(s1 string, s2 string, s3 string) bool {
if len(s3) != len(s1)+len(s2) {
return false
}
mat := make([][]bool, len(s1)+1)
for idx := 0; idx <= len(s1); idx += 1 {
mat[idx] = make([]bool, len(s2)+1)
}
mat[0][0] = true
for row := 0; row <= len(s1); row += 1 {
for col := 0; col <= len(s2); co... |
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
"github.com/iovisor/gobpf/elf"
)
func main() {
module := elf.NewModule("./program.o")
if err := module.Load(nil); err != nil {
fmt.Fprintf(os.Stderr, "Failed to load program: %v\n", err)
os.Exit(1)
}
defer func() {
if err := module.Close(); err !=... |
package main
import "fmt"
func main() {
fmt.Println()
func() {
fmt.Println("Anonymous Func")
}()
func(x int) {
fmt.Println("X", x)
}(43)
f := func() {
fmt.Println("Func Expression")
}
f()
}
|
package genstruct
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"strings"
)
var TemplatePath string
var OutputPath string
func GenStruct(templatePath string, outputPath string) {
TemplatePath = templatePath
OutputPath = outputPath
// jsonBlob, err := ioutil.ReadFile(os.Getenv("PWD") + "... |
/*
Copyright 2021 CodeNotary, 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 law or agreed to i... |
package logic
import (
"context"
"fmt"
"strings"
"tpay_backend/model"
"tpay_backend/payapi/internal/common"
"tpay_backend/utils"
"tpay_backend/payapi/internal/svc"
"tpay_backend/payapi/internal/types"
"github.com/tal-tech/go-zero/core/logx"
)
type TransferLogic struct {
logx.Logger
ctx context.Conte... |
package main
import (
"flag"
"fmt"
"log"
"net/http"
"websocker-hub/util"
"golang.org/x/net/websocket"
"encoding/json"
"io/ioutil"
"strconv"
"sync"
)
var (
newsChan = make(chan string)
wsConnPool WsConnectionPool
)
// WsConnectionPool websocket连接池
type WsConnectionPool struct {
... |
package vo
type Form struct {
PhoneNo string
LastDate string
}
|
/**
* Copyright 2019 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 requir... |
package valuestream
import (
oproto "code.google.com/p/open-instrument/proto"
"sort"
)
type By func(p1, p2 *oproto.ValueStream) bool
func (by By) Sort(values []*oproto.ValueStream) {
sfs := &valuesSorter{
values: values,
by: by,
}
sort.Sort(sfs)
}
type valuesSorter struct {
values []*oproto.... |
/*
* @lc app=leetcode.cn id=127 lang=golang
*
* [127] 单词接龙
*/
package solution
import "math"
// @lc code=start
func ladderLength(beginWord string, endWord string, wordList []string) int {
if !isContain(wordList, endWord) {
return 0
}
wordList = append(append([]string{}, beginWord), wordList...)
distance :=... |
package main
import "fmt"
func main() {
var a int = 10
fmt.Printf("a:%v,变量a的地址:%p\n", a, &a)
var p1 *int
p1 = &a
fmt.Println("p1的值:", p1)
fmt.Printf("p1的地址:%p\n", &p1)
fmt.Println("p1的数值,是a的地址,改地址存储的数据:", *p1)
// 3.操作变量 更改值 ,并不会改变地址
a = 100
fmt.Println("a:", a)
fmt.Printf("%p\n", &a)
// 4 通过指针修改变量的值
*... |
package event
// Listener type
type Listener func(ev *Event)
// Subscriber
type Subscriber struct {
Listeners map[string]*Listener
}
// Listener queue
type listenerQueue struct {
listeners []*Listener
}
// Add a Listener to queue.
func (lq *listenerQueue) add(callback *Listener){
lq.listeners = append(lq.listene... |
package seev
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document00200103 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:seev.002.001.03 Document"`
Message *MeetingCancellationV03 `xml:"MtgCxl"`
}
func (d *Document00200103) AddMessage() *... |
package main
import (
"fmt"
"github.com/therecipe/qt/bluetooth"
"github.com/therecipe/qt/core"
)
const (
serviceUuid = "e8e10f95-1a70-4b27-9ccf-02010264e9c9"
androidUuid = "c9e96402-0102-cf9c-274b-701a950fe1e8"
)
type PingPong struct {
core.QObject
_ func() `constructor:"init"`
_ float6... |
package model
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestNewField(t *testing.T) {
field := NewField("field1", StringType, []byte("value1"))
assert.Equal(t, "field1", field.Name())
assert.Equal(t, StringType, field.Type())
assert.Equal(t, "value1", string(field.Value()))
}
|
// +build mage
/*
* 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 main
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/magefile/mage/sh"
)
var cwd, ... |
package geometry
type Rect struct {
Width, Height float64
}
func (r Rect) Area() float64 {
return r.Width * r.Height
}
func (r Rect) Perim() float64 {
return 2*r.Width + 2*r.Height
}
|
package dns
import "strings"
func DnsNameToKumaCompliant(name string) (string, error) {
// the request might be of the form:
// service-name.namespace.something-else.mesh.
// it will always end with a dot, as specified by https://tools.ietf.org/html/rfc1034#section-3.1
// `Since a complete domain name ends with... |
/*
* @lc app=leetcode.cn id=1524 lang=golang
*
* [1524] 和为奇数的子数组数目
*/
// @lc code=start
// package leetcode
func numOfSubarrays(arr []int) int {
oddNums := 0
evenNums := 1
var res = 0
sum := 0
for _, num := range arr {
sum += num
if sum%2 == 1 {
res += evenNums
oddNums += 1
} else {
res += odd... |
package apperr
import "fmt"
type Error struct {
Message string `json:"message"`
Hint string `json:"hint"`
InternalError error `json:"-"`
}
func (e Error) Error() string {
return fmt.Sprintf("app_eror: %s. internal_err: %v", e.Message, e.InternalError)
}
func New(message, hint string) error {
re... |
package downloader
// 一个可以获取到的视频信息
type VideoFile struct {
FilePath, Title, Desc, ID, Md5 string
FileSize int64
}
|
package main
import (
"fmt"
"io/ioutil"
"strconv"
"strings"
)
func main() {
data, err := ioutil.ReadFile("input.txt")
if err != nil {
panic(err)
}
lines := strings.Split(strings.TrimSpace(string(data)), ",")
part1(lines)
part2(lines)
}
func part1(lines []string) {
is := toInt(lines)
fmt.Println(run(i... |
package volume
type Index interface {
Get(key string) (fi FileInfo, err error)
Set(key string, fi FileInfo) error
Delete(key string) error
List(key string) ([]string, error)
ListN(key string, count int) ([]string, error)
Close() error
}
|
package fliptest
const defaultTemplate string = `
---
AWSTemplateFormatVersion: '2010-09-09'
Description: 'Stack to launch a vpc lambda to test Internet in a VPC'
Parameters:
SubnetId:
Description: The subnet id to deploy the lambda into
Type: String
VpcId:
Description: The vpc to deploy the lambda i... |
package p1
import (
"bufio"
"fmt"
"math"
"os"
)
func getColumn(ticket string) int {
min := 0
max := 7
for _, token := range ticket[7:] {
switch token {
case 'L':
max = max - int(math.Ceil(float64(max - min) / 2))
case 'R':
min = min + int(math.Ceil(float64(max - min) / 2))
}
}
return min
}
fun... |
package polochon
// Torrent represents a torrent file
type Torrent struct {
Name string `json:"name"`
Quality Quality `json:"quality"`
URL string `json:"url"`
Seeders int `json:"seeders"`
Leechers int `json:"leechers"`
Source string `json:"source"`
UploadUser string `json:"u... |
package strucct
type UserLogin struct {
Id int `xorm:"not null pk autoincr INT(10)"`
Name string `xorm:"not null default '' index VARCHAR(100)"`
Uid string `xorm:"not null default '' unique VARCHAR(40)"`
Password string `xorm:"not null default '' VARCHAR(40)"`
Mail string `xorm:"no... |
package nat
import (
"fmt"
"sync"
"time"
ma "gx/ipfs/QmNTCey11oxhb1AxDnQBRHtdhap6Ctud872NjAYPYYXPuc/go-multiaddr"
"gx/ipfs/QmSF8fPo3jgVBAy8fpdjjYqgG87dkJgUprRBHRd2tmfgpP/goprocess"
manet "gx/ipfs/QmZcLBXKaFe8ND5YHPkJRAwmhJGrVsi1JqDZNyJ4nRK5Mj/go-multiaddr-net"
)
// Mapping represents a port mapping in a NAT.
t... |
package mysql_storage
import (
"database/sql"
"github.com/jmoiron/sqlx"
"server/src/dto"
)
type QuotesRepository struct {
db *sqlx.DB
}
func (repo *QuotesRepository) GetQuoteById(id int) (*dto.Quote, error){
selectStatement := "SELECT * FROM `Quotes` WHERE Id = ?"
quote := &dto.Quote{}
if err := repo.db.Get(q... |
package hzutils
import (
"bytes"
"fmt"
"reflect"
"strconv"
)
// StringinSlice Does String in Slice?
// @param string, []string
// @return bool
func StringinSlice(s string, slice []string) bool {
for _, v := range slice {
if v == s {
return true
}
}
return false
}
// StringsToJSON Format String to JSON
... |
package main
func main() {
}
func isLeafNode(node *TreeNode) bool {
return node.Left == nil && node.Right == nil
}
func dfs(node *TreeNode) (ans int) {
if node.Left != nil {
if isLeafNode(node.Left) {
ans += node.Left.Val
} else {
ans += dfs(node.Left)
}
}
if node.Right != nil && !isLeafNode(node.Ri... |
// Copyright 2015 The Go Circuit Project
// Use of this source code is governed by the license for
// The Go Circuit Project, found in the LICENSE file.
//
// Authors:
// 2015 Petar Maymounkov <p@gocircuit.org>
// Package tcp implements a peer transport over TCP.
package tcp
import (
"bufio"
"encoding/binary"
"g... |
package handlers
import (
"encoding/json"
"log"
"net/http"
"github.com/matscus/Hamster/Mock/info_service/datapool"
)
type ClientSearchRQ struct {
Meta struct {
Channel string `json:"channel"`
} `json:"meta"`
Data struct {
RequestFields []string `json:"requestFields"`
Filter struct {
GUID strin... |
package leetcode
/*A binary tree is univalued if every node in the tree has the same value.
Return true if and only if the given tree is univalued.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/univalued-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/
/**
* Definition for a binary tree node.
* type TreeNod... |
package types
import (
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
// oracle module sentinel errors
var (
ErrUnknownFeedName = sdkerrors.Register(ModuleName, 2, "unknown feed")
ErrInvalidFeedName = sdkerrors.Register(ModuleName, 3, "invalid feed name")
ErrExistedFeedName = sdkerrors.Reg... |
/*
Package rpio provides GPIO access on the Raspberry PI without any need
for external c libraries (ex: WiringPI or BCM2835).
Supports simple operations such as:
- Pin mode/direction (input/output)
- Pin write (high/low)
- Pin read (high/low)
- Pull up/down/off
Example of use:
rpio.Open()
defer rpio.Close()
pin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.