text stringlengths 11 4.05M |
|---|
package main
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"regexp"
"strings"
"time"
)
const (
START_BLOCK_CHAR = '\x0b'
END_BLOCK_CHAR = '\x1c'
CR_CHAR = '\x0d'
)
var httpClient = &http.Client{
Timeout: time.Second * 10,
}
func HL7TS(t tim... |
package main
import (
"fmt"
"book/ch06"
)
func main() {
p := ch06.Point{1, 2}
q := ch06.Point{2, 4}
fmt.Println(p.Distance(q))
path := ch06.Path{
{1, 1},
{5, 1},
{5, 4},
{1, 1},
}
fmt.Println(path.Distance())
}
|
package make
import (
"encoding/json"
"fmt"
"os"
"com.samderlust/izetool/ize/utils"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
const (
nameFlag = "name"
)
func Make() *cobra.Command {
var flags []string
cmd := &cobra.Command{
Use: "make <template>",
Short: "make files and folders",
Long: "... |
package How_Many_Numbers_Are_Smaller_Than_the_Current_Number
func smallerNumbersThanCurrent(nums []int) []int {
result := make([]int, len(nums))
cnt := [101]int{}
for _, v := range nums {
cnt[v]++
}
for i := 1; i < len(cnt)-1; i++ {
cnt[i] += cnt[i-1]
}
for i, v := range nums {
if v > 0 {
result[i] =... |
package model
import (
"time"
"github.com/gin-gonic/gin"
)
// BaseModel is
type BaseModel struct {
ID string `json:"id" gorm:"primary_key"` //
CreatedAt time.Time `json:"-"` //
UpdatedAt time.Time `json:"-"` //
DeletedAt *time.Time `json:"-" sql:"index"` ... |
package token
import "cointhink/proto"
import "cointhink/db"
import "log"
import "github.com/satori/go.uuid"
var Columns = "token, account_id, algorun_id"
var Fields = ":token, :account_id, :algorun_id"
var Table = "tokens"
func Insert(item *proto.Token) error {
item.Id = db.NewId(Table)
item.Token = uuid.NewV4().... |
package main
import (
"os/exec"
)
// Command for device network commands.
type Command struct {
Runner CmdRunner
SetupCfg *SetupCfg
}
// RemoveApInterface removes the AP interface.
func (c *Command) RemoveApInterface() {
cmd := exec.Command("iw", "dev", "wlan0", "del")
cmd.Start()
cmd.Wait()
}
func (c *Comm... |
// Copyright (c) 2019 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package script
import (
"fmt"
"os"
"testing"
)
func TestCommandFROM(t *testing.T) {
tests := []commandTest{
{
name: "FROM set to local",
source: func() string {
return "FROM local"
},
script: func(s *... |
package nats
import (
"encoding/json"
"fmt"
"reflect"
"strings"
"sync"
"time"
"github.com/nats-io/go-nats"
"github.com/nats-io/go-nats/encoders/protobuf"
"github.com/sirupsen/logrus"
)
const connectionRetries = 10
type natsCB func(topic, reply string, msg map[string]interface{})
type plainHandler func(msg ... |
package utils
import "strings"
// ParseLine parse line
func ParseLine(line string) (string, string) {
params := strings.SplitN(strings.Trim(line, "\r\n"), " ", 2)
if len(params) == 1 {
return params[0], ""
}
return params[0], strings.TrimSpace(params[1])
}
|
package sync
import (
"fmt"
"time"
"github.com/cynt4k/wygops/cmd/config"
"github.com/cynt4k/wygops/internal/repository"
"github.com/cynt4k/wygops/internal/services/ldap"
"github.com/leandro-lugaresi/hub"
"go.uber.org/zap"
)
// Service : Sync service struct
type Service struct {
hub *hub.Hub
repo ... |
package setup
import "log"
func RunRedisContainer() {
if err := runRedisContainer(); err != nil {
log.Fatal(err)
}
}
func StopRedisContainer() {
if err := stopRedisContainer(); err != nil {
log.Fatal(err)
}
}
func RunMQContainer() {
if err := runMQContainer(); err != nil {
log.Fatal(err)
}
}
func StopM... |
// Command lyft can request and manage Lyft rides from the command line.
package main // import "go.avalanche.space/lyft"
import (
"bufio"
"context"
"errors"
"flag"
"fmt"
"log"
"os"
"os/exec"
"runtime"
"strings"
"text/tabwriter"
"go.avalanche.space/lyft-go"
"googlemaps.github.io/maps"
)
// TODO: impleme... |
package queues
type Request struct {
From string
Message string
}
type Response struct {
From string
To string
Message string
}
|
package controller
import (
"github.com/gin-gonic/gin"
JwtConfig "golangdemo/rps-game/configs/jwt-conf"
LogConf "golangdemo/rps-game/configs/log-conf"
"golangdemo/rps-game/configs/system-code"
JwtHelper "golangdemo/rps-game/helpers/jwt"
"golangdemo/rps-game/helpers/logging"
"golangdemo/rps-game/helpers/utils"
... |
package function
import (
"errors"
"testing"
)
// ------------------------------------------------------------------------------------------------------
func TestCategoryCanBeAddedToProduct(t *testing.T) {
CategoryTestID := "0x12"
ProductTestID := "0x13"
executor := Executor{
Store: MockStorage{DatabaseGatewa... |
package store
import (
"bytes"
"strings"
"testing"
"time"
"github.com/minotar/imgd/pkg/cache/util/test_helpers"
"github.com/minotar/imgd/pkg/util/tinytime"
)
type mockClock struct {
time time.Time
}
func (m *mockClock) Now() time.Time {
return m.time
}
func (m *mockClock) Add(t time.Duration) {
m.time = m... |
// Copyright 2019 The gVisor 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 agree... |
package main
import (
"encoding/json"
"errors"
"log"
"net/http"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
var (
// ErrNotParsed is thrown when the json is not parsed
ErrNotParsed = errors.New("error parsed json")
// ErrNotBody is thrown when a body is not provided
ErrNot... |
package engineio
import (
)
type Socket struct{
}
func (s *Socket) Send(string){
}
func (s *Socket) Close(){
}
func (s *Socket) OnMessage(func(data []byte)){
}
func (s *Socket) OnClose(func()){
} |
package m
import (
"errors"
"fmt"
"math"
"math/rand"
"strconv"
"strings"
)
//============================================================================
// Language Constants
//============================================================================
const (
Sentinal = iota
NumberLiteral
NegativeCellRef... |
package batch
import (
"fp-dynamic-elements-manager-controller/internal/db/persistence"
"fp-dynamic-elements-manager-controller/internal/queue/structs"
"github.com/rs/zerolog/log"
"math"
)
func GetPaginatedBatchResults(page, pageSize int, status structs.Status, repo *persistence.UpdateStatusRepo) (items structs.P... |
// Copyright 2014 Aller Media AS. All rights reserved.
// License: GPL3
// Package metl provides helper functions for the etl packages & commands
package metl
import (
"fmt"
log "github.com/Sirupsen/logrus"
"github.com/jwaldrip/odin/cli"
"os"
"path/filepath"
)
type Runnable interface {
DefineFlags(*cli.SubCom... |
package main
// https://www.codewars.com/kata/51b6249c4612257ac0000005/train/go
var valueMap = map[string]int{
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000,
}
// RomanNumeralsDecode solve it!
func RomanNumeralsDecode(roman string) int {
v := 0
for i := 0; i < len(roman); i++ {
cv := val... |
package testdb
import (
"context"
"github.com/rickbassham/example-go/pkg/identity"
)
type User struct {
Entity
Username string `db:"username"`
}
func init() {
statements["user_insert"] = "INSERT INTO users (created_by, updated_by, username) VALUES (?, ?, ?)"
statements["user_select_active"] = "SELECT id, cre... |
package merge
func ArrayMerge(a, b []int64) []int64 {
lenOfA := len(a)
lenOfB := len(b)
if lenOfA == 0 {
return b
}
if lenOfB == 0 {
return a
}
i := 0
j := 0
c := []int64{}
for {
if a[i] > b[j] {
c = append(c, b[j])
j++
} else {
c = append(c, a[i])
i++
}
if i == lenOfA {
c = append... |
package datatrade
import (
"github.com/cerana/cerana/acomm"
"github.com/cerana/cerana/provider"
)
// Provider is a provider of data import and export functionality.
type Provider struct {
config *Config
tracker *acomm.Tracker
}
// New creates a new instance of Provider.
func New(config *Config, tracker *acomm.T... |
package version
import (
"gocli/cmd/commands"
"gocli/utils"
"fmt"
"gocli/config"
)
var CmdRun = &commands.Command{
UsageLine: "version/v",
Short: "show version",
Long: `
show version
`,
Run: showVersion,
}
func init() {
commands.AddGroup("default", CmdRun)
}
func showVersion(cmd *commands.Command, ar... |
package _0_Decorator_Pattern
import "testing"
func TestDecoratorPattern(t *testing.T) {
type fields struct {
decoratedShape Shape
}
tests := []struct {
name string
fields fields
want string
}{
{"redCircle", fields{&RedShapeDecorator{Circle{}}}, "Circle| RedBorder"},
{"redCircle", fields{&RedShapeD... |
package main
import "fmt"
var a int
var b float64
var c string
var d bool
func main() {
fmt.Printf("%v, %T\n", a, a)
fmt.Printf("%v, %T\n", b, b)
fmt.Printf("%v, %T\n", c, c)
fmt.Printf("%v, %T\n", d, d)
}
|
package main
import "time"
import "fmt"
//测试waker进程启动别的进程时的权限等情况
func main(){
for{
fmt.Println("hello")//打印一行的函数
time.Sleep(time.Second * 3)//3s 为间隔
}
} |
/*
* Copyright 2018 The Service Manager 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 l... |
// Copyright (C) 2019-2020 Zilliz. 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 l... |
package main
import "fmt"
func main() {
func() {
fmt.Println("This is an anonamous function using immediately invokable execution I learnt from js")
}()
}
|
package storageos
import (
"fmt"
"strings"
"github.com/storageos/cluster-operator/pkg/util/k8s/resource"
"github.com/storageos/cluster-operator/pkg/util/version"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const (
// SchedulerExtenderName is the name of StorageOS scheduler.
Sc... |
package web
import (
"errors"
"fmt"
"net/http"
"github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin"
"github.com/smartcontractkit/chainlink/services"
"github.com/smartcontractkit/chainlink/store/models"
"go.uber.org/multierr"
)
// SessionsController manages session requests.
type SessionsControl... |
package main
import "fmt"
/*
type Name interface {
Method1(param_list) return_type
Method2(param_list) return_type
...
}
*/
type Information interface {
General()
Attributes()
Inventory()
}
// Implemention of Interface into Concrete Types
type Product struct {
Name, Description string
Weight, Price float... |
package tree
import (
"testing"
"sync"
"math/rand"
"fmt"
"math"
"runtime"
//"sync/atomic"
)
func setupGrids(min_points int, max_points int, num_grids int) (grids []*Grid, min_dense_points, min_cluster_points int) {
min_interval := 0.0
max_interval := 1.0
interval_length := 0.1
dim := 2
min_dense_points = ... |
package fuzzy
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"index/suffixarray"
"io"
"log"
"os"
"regexp"
"sort"
"strings"
"sync"
)
const (
SpellDepthDefault = 2
SpellThresholdDefault = 5
SuffDivergenceThresholdDefault = 100
)
type Pair struct {
str1 string
str2 string
}
type... |
package templates
import (
"html/template"
"log"
texttemplate "text/template"
)
var LoginFormTemplate *template.Template
var HomePageTemplate *template.Template
var BadPageTemplate *template.Template
var CoursePageTemplate *template.Template
var SubjectPageTemplate *template.Template
var FacultyPageTemplate *templ... |
package notificationdelivery
import "fmt"
//ErrDeliveryNotFound error raised if given delivery not found
type ErrDeliveryNotFound struct {
Delivery string
}
//Error return error message
func (e *ErrDeliveryNotFound) Error() string {
return fmt.Sprintf("notification delivery: delivery not found [%s]", e.Delivery)
}... |
package main
import (
"crypto/tls"
"crypto/x509"
"flag"
"fmt"
"io/ioutil"
"log"
"net"
"os"
"runtime"
"time"
"github.com/Sirupsen/logrus"
"github.com/docker/engine-api/client"
"github.com/zanecloud/tunneld/tunnel/audit/zaneaudit"
"github.com/zanecloud/tunneld/tunnel/ssh"
)
const (
VERSION stri... |
package compat
import (
"os"
"testing"
"github.com/google/go-containerregistry/pkg/v1/empty"
"github.com/google/go-containerregistry/pkg/v1/mutate"
"github.com/google/go-containerregistry/pkg/v1/random"
"github.com/google/go-containerregistry/pkg/v1/types"
)
func TestWriteImage(t *testing.T) {
cl, err := rand... |
package privileges
import "github.com/cohesity/management-sdk-go/models"
import "github.com/cohesity/management-sdk-go/configuration"
/*
* Interface for the PRIVILEGES_IMPL
*/
type PRIVILEGES interface {
GetPrivileges (*string) ([]*models.PrivilegeInformation, error)
}
/*
* Factory for the PRIVIL... |
package aursir4go
import "net"
import (
"log"
"time"
)
func pingUdp(UUID string, killFlag *bool){
var pingtime = 8*time.Second
serverAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:5556")
if err != nil {
log.Fatal("DOCKERZMQ",err)
}
con, err := net.DialUDP("udp", nil, serverAddr)
if err != nil {
log.F... |
package socat
import (
"testing"
"github.com/LarsFronius/rootlesskit/pkg/port"
"github.com/LarsFronius/rootlesskit/pkg/port/testsuite"
)
func TestSocat(t *testing.T) {
df := func() port.ParentDriver {
d, err := New(testsuite.TLogWriter(t, "socat.Driver"))
if err != nil {
t.Fatal(err)
}
return d
}
te... |
package controllers
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"github.com/gorilla/mux"
"github.com/jiharevzahar/fullstack/api/models"
"github.com/jiharevzahar/fullstack/api/responses"
"github.com/jiharevzahar/fullstack/api/utils/formaterror"
)
func (server *Server) CreateTime... |
package common
import (
"errors"
"reflect"
"sync"
)
func NewScatterSlice(data interface{}, do func(todo interface{}) interface{}) (result []interface{}, e error) {
defer func() {
if err := recover(); err != nil {
e = errors.New(err.(string))
}
}()
v := reflect.ValueOf(data) //使用断言机制判断当前传入类型
if v.Kind()... |
// Copyright 2020 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 zip
import (
"os"
"github.com/Dynatrace/dynatrace-operator/src/controllers/csi/metadata"
"github.com/spf13/afero"
)
type Extractor interface {
ExtractZip(sourceFile afero.File, targetDir string) error
ExtractGzip(sourceFilePath, targetDir string) error
}
func NewOneAgentExtractor(fs afero.Fs, pathResol... |
package router
import (
"github.com/gin-gonic/gin"
"hd-mall-ed/packages/admin/controller/staticController"
)
func staticRouter(router *gin.RouterGroup) {
static := router.Group("/static")
{
static.GET("/list", staticController.GetListByQuery)
}
}
|
package utils
import (
"context"
"os"
kitlog "github.com/go-kit/kit/log"
)
type contextKey int
const (
logCtxKey contextKey = iota
)
// WithLogger stores a go-kit log *Context to a context.Context
func WithLogger(parent context.Context, logCtx kitlog.Logger) context.Context {
return context.WithValue(parent, ... |
/*
* @lc app=leetcode id=144 lang=golang
*
* [144] Binary Tree Preorder Traversal
*
* https://leetcode.com/problems/binary-tree-preorder-traversal/description/
*
* algorithms
* Medium (55.11%)
* Likes: 1555
* Dislikes: 58
* Total Accepted: 502.1K
* Total Submissions: 905.2K
* Testcase Example: '[1,n... |
package neovm
import (
"testing"
"math/big"
"github.com/zhaohaijun/matrixchain/vm/neovm/types"
)
func TestOpBigInt(t *testing.T) {
var e ExecutionEngine
e.EvaluationStack = NewRandAccessStack()
for _, code := range []OpCode{INC, DEC, NEGATE, ABS, PUSH0} {
e.EvaluationStack.Push(NewStackItem(types.NewIntege... |
package cmd
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"github.com/exercism/cli/api"
"github.com/exercism/cli/config"
"github.com/spf13/cobra"
)
// prepareCmd does necessary setup for Exercism and its tracks.
var prepareCmd = &cobra.Command{
Use: "prepare",
Aliases: []string{"p"},
Short: "Pre... |
package main
import "fmt"
func add(a, b int) int {
return a + b
}
func main() {
a := []int{1,2,3}
for _, v := range a {
fmt.Println(v)
}
fmt.Println(add(1,456))
} |
package rtmapi
import (
"context"
"errors"
"fmt"
"github.com/gorilla/websocket"
"github.com/oklahomer/golack/v2/event"
"github.com/oklahomer/golack/v2/testutil"
"net"
"reflect"
"strconv"
"testing"
"time"
)
func TestConnect(t *testing.T) {
testutil.RunWithWebSocket(func(addr net.Addr) {
url := fmt.Sprint... |
package server
import (
"crypto/sha256"
"net"
"google.golang.org/protobuf/proto"
"github.com/iotaledger/hive.go/crypto/identity"
)
const (
// MaxPacketSize specifies the maximum allowed size of packets.
// Packets larger than this will be cut and thus treated as invalid.
MaxPacketSize = 1280
)
// MType is t... |
/**
* Copyright 2016 l0vest0rm.gostream.example.emitto 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 ... |
// Copyright 2016 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 api
import (
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/aws"
"github.com/paulmatencio/s3c/datatype"
)
func GetObject(req datatype.GetObjRequest) (*s3.GetObjectOutput,error){
input := &s3.GetObjectInput{
Bucket: aws.String(req.Bucket),
Key: aws.String(req.Key),
}
return req... |
package cmd
import (
"flag"
"fmt"
"log"
"strings"
"github.com/m7shapan/my-http/repositories"
"github.com/m7shapan/my-http/services"
)
type CMD struct {
}
func (c CMD) Start() {
c.md5ResponseHandler()
}
func (c CMD) md5ResponseHandler() {
parallel := flag.Int("parallel", 10, "the max number of parallel requ... |
package requests
import (
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"net/http"
"net/http/cookiejar"
"net/http/httptrace"
"net/url"
"os"
"strings"
"time"
"golang.org/x/net/proxy"
)
// var
var (
ErrEmptyProxy = errors.New("proxy is empty")
)
// Session httpclient session
// Clients and Transports are s... |
package user
import "github.com/skycoin/getsky.org/db/models"
// Users serve as an interface to users storage
type Users interface {
Get(string) (*models.UserDetails, error)
GetByEmail(string) (*models.UserDetails, error)
Register(models.User, string) error
UpdateSettings(models.UserSettings) error
}
|
/*
Copyright 2020 The Knative 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, soft... |
package main
import (
"./cookie"
"io/ioutil"
"math/rand"
"net/http"
)
const (
alnum = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ123456789"
)
// Generate random string of n bytes
func randomString(n int) string {
buf := make([]byte, n)
for i := 0; i < n; i++ {
buf[i] = alnum[rand.Intn(len(alnum))]
}... |
package gochat
import (
"os";
"net";
"fmt";
"bufio";
"strings";
"container/vector";
)
type Server struct {
listener *net.TCPListener;
incomingMessages chan Message;
registerForMessages chan *Client;
clients *vector.Vector;
}
type Message struct {
sender string;
message string;
}
func (s *Server) Star... |
package backend
import (
"bytes"
"encoding/json"
"math/rand"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
)
const (
testTenantID = "fake"
)
func TestBlockMeta(t *testing.T) {
testVersion := "blerg"
testEncoding := EncLZ4_256k
testDataEncoding := "blarg"
id := uuid.New()
b := ... |
package usecase
import (
"ehsan_esmaeili/model"
"ehsan_esmaeili/repository"
)
type Buy_PackUsecase interface {
InsertUser(user *model.Samsicoin) (use *model.GetaUser, err error )
}
type Buy_PackUsecaseSqlServer struct {
userRepositorySqlServer *repository.UserRepositorySqlServer
}
var Buy_Pack *UserUsecaseSqlS... |
// Copyright 2020 SEQSENSE, 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 ... |
package comparator
func Levenshtein(x, y string) int {
s1, s2 := []rune(x), []rune(y)
len1, len2 := len(s1), len(s2)
if len1 == 0 {
return len2
}
if len2 == 0 {
return len1
}
var cost int
if s1[len1 - 1] == s2[len2 - 1] {
cost = 0
} else {
cost = 1
}
shortX, shortY := string(s1[0:len1 - 1]), str... |
package utils
import (
"fmt"
"math/rand"
"testing"
"time"
)
var InData []string = []string{"this", "is", "test", "data", "for", "in", "function"}
func Test_In(t *testing.T) {
t.Run("bingo", func(t *testing.T) {
if In("this", InData) == false {
t.Fatalf("this expected in InData [%v], but got fasle", InData)... |
package com
import (
"JsGo/JsBench/JsProduct"
"JsGo/JsHttp"
"JsGo/JsLogger"
"JsGo/JsStore/JsRedis"
"JunSie/constant"
"JunSie/util"
"fmt"
"strconv"
"time"
)
func Init_operation() {
JsHttp.WhiteHttp("/getoperationnum", GetOperationNum) //获取运营版面数字
JsHttp.WhiteHttp("/getprorepertory", GetProRepertory) //获取获取库存... |
package roi
import (
"database/sql"
"errors"
"fmt"
"strings"
"golang.org/x/crypto/bcrypt"
)
var CreateTableIfNotExistsUsersStmt = `CREATE TABLE IF NOT EXISTS users (
id STRING UNIQUE NOT NULL CHECK (length(id) > 0) CHECK (id NOT LIKE '% %'),
username STRING NOT NULL CHECK (length(username) > 0) CHECK (usernam... |
package LeetCode
import "fmt"
func Code11() {
height := []int{1, 8, 6, 2, 5, 4, 8, 3, 7}
fmt.Println(maxArea(height))
}
/**
给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器,且 n 的值至少为 2。
图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下... |
package lc
// Time: O(n)
// Benchmark: 24ms 7.1mb | 100%
func countMatches(items [][]string, ruleKey string, ruleValue string) int {
var i int
switch ruleKey {
case "type":
i = 0
case "color":
i = 1
case "name":
i = 2
}
var total int
for _, item := range items {
if item[i] == ruleValue {
total++
... |
package duck_task
import (
"finiteStateMachine/task"
"fmt"
)
type Factory struct{}
func (f *Factory) CreateTask(taskID string, configInfoData interface{}) (task.Task, error) {
configInfo, ok := configInfoData.(ConfigInfo)
if !ok {
return nil, fmt.Errorf("config err")
}
baseTask := task.NewBaseTask(taskID, D... |
package ch12
func makeSubsets(result *[][]int, subset, nums []int) {
*result = append(*result, append([]int{}, subset...))
for i := 0; i < len(nums); i++ {
makeSubsets(result, append(subset, nums[i]), nums[i+1:])
}
}
func subsets(nums []int) [][]int {
result := [][]int{}
makeSubsets(&result, []int{}, nums)
r... |
package nsqd
import (
"bytes"
"errors"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/nsqio/go-diskqueue"
"github.com/nsqio/nsq/internal/lg"
"github.com/nsqio/nsq/internal/quantile"
"github.com/nsqio/nsq/internal/util"
)
type Topic struct {
// 64bit atomic vars need to be first for proper alignment on ... |
package main
func f(a) {
}
|
package profiling
import (
"fmt"
"net/http"
"time"
// register the pprof handler
_ "net/http/pprof"
"go.uber.org/zap"
)
var addr string
var logger *zap.Logger
// Start start the http pprof service
func Start(port int, l *zap.Logger) {
logger = l
go loop(port)
}
func loop(port int) {
defer func() {
if ... |
package keyvaultx
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"fmt"
"github.com/Azure/azure-sdk-for-go/services/keyvault/auth"
"github.com/Azure/azure-sdk-for-go/services/keyvault/v7.0/keyvault"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/... |
package aa
import "github.com/janoszen/exoscale-account-wiper/plugin"
func New() plugin.DeletePlugin {
return &Plugin{}
}
|
package repository
import (
"fmt"
"github.com/braulio94/datacaixa/backend/database"
"github.com/braulio94/datacaixa/backend/model"
)
func (r *DatabaseRepository) GetTable(tableId int) (table model.Table) {
formattedQuery := fmt.Sprintf(database.SelectTable, tableId)
_ = database.Database.QueryRow(formattedQuery)... |
package config
import (
"fmt"
"github.com/pkg/errors"
"go.starlark.net/starlark"
"github.com/tilt-dev/tilt/internal/sliceutils"
"github.com/tilt-dev/tilt/internal/tiltfile/starkit"
"github.com/tilt-dev/tilt/internal/tiltfile/value"
"github.com/tilt-dev/tilt/pkg/apis/core/v1alpha1"
"github.com/tilt-dev/tilt/p... |
//
// 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 commands
import (
"fmt"
"github.com/spf13/cobra"
"github.com/buglloc/rip/v2/pkg/cfg"
)
var version = &cobra.Command{
Use: "version",
Short: "Print rip version",
RunE: func(_ *cobra.Command, _ []string) error {
fmt.Printf("RIP v%s\n", cfg.Version)
return nil
},
}
func init() {
RootCmd.AddComma... |
package main
import (
"fmt"
"html"
"net/http"
)
type QueryController struct{}
func (c QueryController) Respond(w http.ResponseWriter, r *http.Request, data map[string]string) {
query := r.FormValue("Body")
ddgResponse, err := QueryDDG(query)
if err != nil {
fmt.Println(err)
http.Error(w, err.Error(), 500... |
package main
import (
"fmt"
)
// Commands represents list of commands.
type Commands []*Command
// Execute executes all commands unless one fails.
func (cmds Commands) Execute() (ok bool, err error) {
for _, cmd := range cmds {
ok, err := cmd.Run()
status(ok, cmd.String())
if err != nil {
return false, fm... |
// Copyright 2021 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 main
import (
"fmt"
"log"
gor "gorgonia.org/gorgonia"
)
func main() {
g := gor.NewGraph()
// define the expression
x := gor.NewScalar(g, gor.Float64, gor.WithName("x"))
y := gor.NewScalar(g, gor.Float64, gor.WithName("y"))
z, err := gor.Add(x, y)
if err != nil {
log.Fatal(err)
}
// create a VM... |
package shortener
import (
"context"
"encoding/json"
"net/http"
"github.com/go-kit/kit/endpoint"
)
func MakeFindEndpoint(svc RedirectService) endpoint.Endpoint {
return func(_ context.Context, request interface{}) (interface{}, error) {
req := request.(findRequest)
url, err := svc.Find(req.Code)
if err !... |
package parse_html
import "strings"
type Replace struct {
Before string `json:"before"`
After string `json:"after"`
}
func (params *Replace) replace(text string) string {
if params != nil {
if params.Before == "\\n" {
text = strings.ReplaceAll(text, "\n", params.After)
} else if params.Before == "\\t" {
... |
package clientManager
import (
"strconv"
"openreplay/backend/pkg/db/postgres"
"openreplay/backend/services/integrations/integration"
)
type manager struct {
clientMap integration.ClientMap
Events chan *integration.SessionErrorEvent
Errors chan error
RequestDataUpdates chan postgres.Integration // not point... |
// Package goutils contains a collection of useful Golang utility methods and libraries
package goutils
import (
// Standard lib
"fmt"
"io"
"net"
"net/http"
"regexp"
"time"
)
type (
// RequestConfig contains a set of configuration settings
// to be used with the methods that make HTTP requests
RequestConfig... |
package main
import (
"testing"
)
func Test_getHundreds(t *testing.T) {
tables := []struct {
number int
result int
}{
{23, 0},
{345, 3},
{3456, 4},
{65452234, 2},
}
for i := 0; i < len(tables); i++ {
row := tables[i]
actual := getHundreds(row.number)
if actual != row.result {
t.Errorf("Get ... |
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package cmd
import (
"bytes"
"regexp"
"github.com/spf13/cobra"
)
func runDelete(paths []string, pattern *regexp.Regexp) error {
return walkReplace(func(data []byte) []byte {
v... |
package storage
import (
"io"
)
type Filer interface {
io.Reader
Pather
Length() int64
}
type SaveFetcher interface {
Saver
Fetcher
}
type Saver interface {
Save(path string) (io.WriteCloser, error)
}
type Fetcher interface {
Fetch(path string) (io.ReadCloser, error)
}
type Pather interface {
Path() stri... |
package model
import "github.com/ionous/sashimi/util/ident"
type EventModel struct {
Id ident.Id `json:"id"`
Name string `json:"name"`
Capture EventModelCallbacks `json:"capture,omitempty"`
Bubble EventModelCallbacks `json:"bubble,omitempty"`
}
func (e EventModel) String() string... |
// Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Package crosdisks provides an interface to talk to cros_disks service
// via D-Bus and utilities.
package crosdisks
import (
"context"
"io/ioutil"
"os"
"path"
"strin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.