text stringlengths 11 4.05M |
|---|
package cmd
import (
"time"
"github.com/estudo/logging"
"github.com/estudo/oo/implementacao"
)
func Start() {
logger()
ponteiro()
anonimo()
colecao()
oo.Impl()
}
func logger() {
logger := logging.New(time.RFC3339, true)
logger.Log("info", "starting up service")
logger.Log("warning", "no tasks found")
l... |
import "fmt"
func main() {
nums := []int{1,3,-1,-3,5,3,6,7}
fmt.Println(maxSlidingWindow(nums, 3))
}
func maxSlidingWindow(nums []int, k int) []int {
l := len(nums)
if l == 0 {
return []int{}
}
var ret []int
for i := 0; i < l - k + 1; i++ {
max := nums[i]
j := i + 1
for j <= i + k -1 {
max = check... |
package gorequests
import (
"bytes"
"strings"
// "crypto/tls"
"errors"
"fmt"
"io"
"log"
"mime/multipart"
"net/http"
"net/url"
"time"
)
// func Options(requestURL string, headers, timeout time.Duration) (r *Response) {
// r = do("OPTIONS", requestURL, headers, "", nil)
// return
// }
/*
Get
*/
func Get(r... |
/*
Copyright 2021 The Kubernetes 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, ... |
package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
)
var (
option = struct {
maxSearchPackets int
verbose bool
fileName string
}{
1000000,
false,
"",
}
)
func parseCmdArgs() {
// オプションの処理
flag.IntVar(&option.maxSearchPackets, "m", option.maxSearchPackets, "Number of ts packet... |
package quickfix
import (
"bytes"
"math"
"sort"
)
//FieldMap is a collection of fix fields that make up a fix message.
type FieldMap struct {
tagLookup map[Tag][]tagValue
tagOrder
}
// tagOrder true if tag i should occur before tag j
type tagOrder func(i, j Tag) bool
type tagSort struct {
tags []Tag
compa... |
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"os"
"strconv"
"rest-api.jishnu.net/models"
_ "github.com/go-sql-driver/mysql"
)
func main() {
var err error
username := os.Getenv("USERNAME")
password := os.Getenv("MYSQL_DB_PASSWORD")
host := os.Getenv("MYSQL_DB_HOST")
port, err := strconv.... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//743. Network Delay Time
//There are N network nodes, labelled 1 to N.
//Given times, a list of travel times as directed edges times[i] = (u, v, w), w... |
package editor
import (
"github.com/gdamore/tcell"
"github.com/rivo/tview"
)
type Header struct {
*tview.Box
*Editor
path string
pristine bool
}
func (e *Editor) NewHeader() *Header {
return &Header{
Box: tview.NewBox().SetBorder(false),
Editor: e,
}
}
// Draw draws this primitive onto the screen... |
// +build !tinygo
package vugu
// CompKey is the key used to identify and look up a component instance.
type CompKey struct {
ID uint64 // unique ID for this instance of a component, randomly generated and embeded into source code
IterKey interface{} // optional iteration key to distinguish the same compo... |
package laraboot
import (
"fmt"
"log"
// "github.com/BurntSushi/toml"
"github.com/cloudfoundry/packit"
"github.com/paketo-buildpacks/packit/chronos"
"github.com/paketo-buildpacks/packit/postal"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
)
//go:generate faux --interface EntryResolver --output fakes/entry_re... |
package isSymmetric
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func isSymmetric(root *TreeNode) bool {
if root == nil {
return true
}
return _isSymmetric(root.Left, root.Right)
}
func _isSymmetric(left, right *TreeNode) bool {
// left == right == nil
if left == nil && right == nil {... |
package pluginutil
import (
"strconv"
"strings"
"code.cloudfoundry.org/cli/plugin"
)
const numComponents = 3
// ParsePluginVersion parses the given plugin version and return its parsed form. If the given plugin
// version is invalid, calls the given fail function with a suitable message. The fail function will
/... |
package utils
import (
"path"
"runtime"
)
func callerLastPath(s string, limit int) string {
index := 0
dir := s
var arr []string
for !IsEmpty(dir) {
if index >= limit {
break
}
index++
arr = append([]string{path.Base(dir)}, arr...)
dir = path.Dir(dir)
}
return path.Join(arr...)
}
func CallerGe... |
package actions
import (
"errors"
"github.com/barrydev/api-3h-shop/src/factories"
"github.com/barrydev/api-3h-shop/src/model"
)
func GetShippingById(shippingId int64) (*model.Shipping, error) {
shipping, err := factories.FindShippingById(shippingId)
if err != nil {
return nil, err
}
if shipping == nil {
... |
package animals
// Go interfaces encourages one to be lazy, and this is a good thing.
// Instead of writing types to fulfil interfaces, write interfaces to fulfil usage requirements.
type Dog struct{}
func (a Dog) Speaks() string {
return "woof"
}
|
package main
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"golang.org/x/crypto/bcrypt"
)
var taxedAmt = []float32{0.98, 0.67} //Fraction left after taxes
var minEventsToRedeem int = 2
func SignUp(w http.ResponseWriter, r *http.Request) {
user := &userDetails{}
e := json.NewDecoder(r.Body).Decode(use... |
package controller
import (
"fmt"
"io/ioutil"
"strings"
"time"
"github.com/ghodss/yaml"
"github.com/zduymz/hpa-operator/pkg/utils"
"k8s.io/api/autoscaling/v2beta2"
"k8s.io/client-go/kubernetes"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
utilruntime "k8s.io/apimachin... |
package main
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
"syscall"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/ubclaunchpad/inertia/local"
"golang.org/x/crypto/ssh/terminal"
)
var cmdDeploymentUser = &cobra.Command{
Use: "user",
Short: "Configure user access to Inertia Web"... |
// Copyright 2016 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 taobaosdk
import (
"testing"
)
func TestGroupsGet(t *testing.T) {
sdk := NewTaobao()
// s := sdk.Tmc.GroupAdd("test", []string{"sandbox_c_1"})
s := sdk.Tmc.UserGet("sandbox_c_1", []string{"user_nick", "topics", "is_valid", "user_id", "created", "modified"})
b, e := s.JsonMap()
c := b.StringOr("tmc_user_... |
// Package feedtrigger is a simple library which is aimed to handle new
// RSS/Atom entries by using a trigger function.
package feedtrigger
import (
"context"
"fmt"
"log"
"strings"
"sync"
"time"
"golang.org/x/sync/errgroup"
"github.com/mmcdole/gofeed"
"github.com/philippgille/gokv"
"github.com/philippgill... |
package config
import (
"fmt"
"time"
)
type Config struct {
Protocol string
Domain string
ImgEndpoint string
StaticPath string
StaticDashPath string
DBURL string
Host string
Port string
JWTSecret []byte
IdleTimeout time.Duration
WriteTimeout tim... |
// Copyright 2013 Walter Schulze
//
// 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... |
package client
import (
ws "github.com/gorilla/websocket"
exchange "github.com/preichenberger/go-coinbase-exchange"
)
const (
GDAX_SOCKET_URL = "wss://ws-feed.gdax.com"
SUBSCRIBE_TYPE = "subscribe"
MESSAGE_MATCH = "match"
)
type SocketClient struct {
gdaxClient *exchange.Client
wsConn *ws.Conn
}
type Subs... |
package main
import (
"bytes"
"encoding/binary"
"encoding/json"
"fmt"
"html/template"
"log"
"net/http"
"os"
"sort"
"strconv"
"github.com/boltdb/bolt"
"github.com/gorilla/mux"
)
type BucketTokens struct {
Bucket Bucket `json:"bucket"`
Tokens []Token `json:"tokens"`
}
type Bucket struct {
Id int... |
package main
import (
"bytes"
"encoding/json"
"fmt"
"html/template"
"net/http"
"os"
"reflect"
"runtime"
"github.com/julienschmidt/httprouter"
)
func init() {
router := httprouter.New()
//router.GET("/user/:userId", ErrorHandler(LogHandler(getUserDetails)))
router.GET("/user", ErrorHandler(LogHandler(H... |
package mini
// Kafka runner for the scheduler
import (
"fmt"
"math/rand"
"net"
"time"
"github.com/etf1/kafka-message-scheduler-admin/server/db/simple"
"github.com/etf1/kafka-message-scheduler-admin/server/helper"
"github.com/etf1/kafka-message-scheduler-admin/server/resolver/schedulers/httpresolver"
"github... |
package main
import "fmt"
const VERSION = "1.0"
func main() {
fmt.Printf("BCCTL v%s\n", VERSION)
usage()
} |
//+build prod
package main
const PORT = ":80"
const DB_NAME = "lucias.db" |
/*
Copyright 2017 The Kubernetes 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, sof... |
package csv
import (
"github.com/operator-framework/api/pkg/operators/v1alpha1"
)
// WatchNotification is an sink interface that can be used to get notification
// of CSV reconciliation request(s) received by the operator.
type WatchNotification interface {
// OnAddOrUpdate is invoked when a add or update reconcili... |
package utils
import (
"bufio"
"log"
"os"
"strings"
)
//readStringStdin reads a string from STDIN and strips and trailing \n characters from it
func ReadStringStdin() string {
reader := bufio.NewReader(os.Stdin) //pause the program and wait for user input
inputVal, err := reader.ReadString('\n')
if err != nil ... |
package mt
import (
"fmt"
"image/color"
"io"
)
type AOID uint16
type aoType uint8
const genericCAO aoType = 101
type AOInitData struct {
// Version.
//mt:const uint8(1)
// For players.
Name string
IsPlayer bool
ID AOID
Pos
Rot [3]float32
HP uint16
// See (de)serialize.fmt.
Msgs []AOMsg
}
ty... |
//************************************************************************//
// RightScale API client
//
// Generated with:
// $ praxisgen -metadata=cm16/api_docs -output=cm16 -pkg=cm16 -target=1.6 -client=API
//
// The content of this file is auto-generated, DO NOT MODIFY
//************************... |
// RAINBOND, Application Management Platform
// Copyright (C) 2014-2017 Goodrain Co., Ltd.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your opt... |
package main
import (
"log"
"os"
"strconv"
"strings"
"github.com/loqutus/artifactory-replication/pkg/binary"
"github.com/loqutus/artifactory-replication/pkg/credentials"
"github.com/loqutus/artifactory-replication/pkg/docker"
"github.com/loqutus/artifactory-replication/pkg/ecr"
"github.com/loqutus/artifactor... |
package hot100
// 关键: dfs
// 1. 双重遍历,当发现了与第一个字符匹配之后, 就围绕这个i,j 进行dfs深搜匹配
func exist(board [][]byte, word string) bool {
var dfs func(i, j, k int) bool
// 标记号,防止重复计算
flags := make([][]bool, len(board))
for i := 0; i < len(board); i++ {
flags[i] = make([]bool, len(board[i]))
}
dfs = func(i, j, k int) bool {
// ... |
package main
import (
"fmt"
)
const aConst int = 65
func main() {
var aString string = "This is the String in Go"
fmt.Println(aString)
fmt.Printf("This variable's type is %T\n", aString)
var aInteger int = 100
fmt.Println(aInteger)
var defaultInt int
fmt.Println(defaultInt)
var anotherString = "This is... |
package commands
import (
"errors"
"fmt"
"net"
"net/url"
"strings"
"github.com/spf13/cobra"
"github.com/valyala/fasthttp"
"github.com/authelia/authelia/v4/internal/authorization"
"github.com/authelia/authelia/v4/internal/configuration/validator"
)
func newAccessControlCommand(ctx *CmdCtx) (cmd *cobra.Comma... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-07-13 09:14
# @File : _98_Validate_Binary_Search_Tree.go
# @Description : 判断是否是二叉搜索树
什么是二叉搜索树: 左孩子 < root < 右孩子
# @Attention :
*/
package v0
import "testing"
func Test_isValidBST(t *testing.T) {
// type args struct {
// root *TreeNode
// }
// tests := ... |
package main
type config struct {
CertFile string
KeyFile string
}
func defaultConfig() *config {
return &config{
CertFile: "/etc/pki/consumer/cert.pem",
KeyFile: "/etc/pki/consumer/key.pem",
}
}
|
package main
import (
"fmt"
"sync"
"time"
)
type atomicInt struct {
value int
lock sync.Mutex
}
func (a *atomicInt) increment() {
a.lock.Lock()
defer a.lock.Unlock()
a.value++
}
func (a *atomicInt) get() int {
a.lock.Lock()
defer a.lock.Unlock()
return int(a.value)
}
func main() {
var n atomicInt
n.in... |
package runtimes
import (
"github.com/mee6aas/kyle/internal/pkg/runtime"
"github.com/pkg/errors"
)
// Add adds a runtime into the collection with specified activity name as the key.
func Add(actName string, r *runtime.Runtime) (e error) {
if !r.IsConnected() {
e = errors.New("Not connected runtime")
return
}
... |
package models
import (
"errors"
"labix.org/v2/mgo/bson"
)
/*
* 单个实体查找
*/
func (d *ProductDal) FindByID(id int) Product {
result := []Product{}
uc := d.session.DB(DbName).C(ProductCollection)
err := uc.Find(bson.M{"productID": id}).All(&result)
if err != nil {
panic(err)
}
if len(result)>0 ... |
package networkextensions
// Error is the error type for this package, ready to be unwrapped with
// `errors.As`.
type Error string
// Error implements the error interface
func (err Error) Error() string {
return string(err)
}
|
package tasks
import (
"fmt"
"strconv"
)
type TaskDeleter interface {
DeleteTask(int) error
}
// RemoveTask removes a task
func RemoveTask(store TaskDeleter, args []string) {
for _, arg := range args {
id, err := strconv.Atoi(arg)
if err != nil {
fmt.Printf("%d is not a valid ID", id)
}
err = store.De... |
package main
import (
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/TempleEight/spec-golang/auth/comm"
"github.com/TempleEight/spec-golang/auth/dao"
"github.com/dgrijalva/jwt-go"
"github.com/google/uuid"
)
type mockDAO struct {
authList []dao.Auth
}
type mockComm... |
package crypto
import (
"fmt"
"os"
"testing"
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/crypto/encoding/amino"
)
var ledgerEnabledEnv = "TEST_WITH_LEDGER"
func TestRealLedgerSecp256k1(t *testing.T) {
if os.Getenv(ledgerEnabledEnv) == "" {
t.Skip(fmt.Sprintf("Set '%s' to run code... |
package main
import (
"fmt"
"sort"
)
// Printer outputs results in human-readable format.
type Printer struct{}
// PrintDupes prints results to stdout.
func (p *Printer) PrintDupes(dupes map[string][]string) {
lines := make([]string, 0)
for hash, filenames := range dupes {
for _, filename := range filenames {... |
package main
import (
"fmt"
"log"
"net/http"
"os"
"time"
)
//NotificationsHandler handles requests for the /notifications resource
type NotificationsHandler struct {
notifier *Notifier
}
//NewNotificationsHandler constructs a new NotificationsHandler
func NewNotificationsHandler(notifier *Notifier) *Notificati... |
package main
//region Usings
import "github.com/ravendb/ravendb-go-client"
//endregion
var globalDocumentStore *ravendb.DocumentStore
func main() {
createDocumentStore()
createDatabase()
queryRelatedDocuments()
globalDocumentStore.Close()
}
func createDocumentStore() (*ravendb.DocumentStore, error) ... |
package admob
import (
"encoding/json"
"errors"
"fmt"
"github.com/econnelly/myrevenue"
"github.com/econnelly/myrevenue/adnetwork"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
type ReportRequester struct {
PublisherID string `json:"publisher_id"`
ClientID string `json:"c... |
package services
import (
"errors"
"fmt"
"net/url"
"github.com/mrdulin/go-rpc-cnode/models"
"github.com/mrdulin/go-rpc-cnode/utils/http"
)
var (
ErrGetMessages = errors.New("get messages")
ErrGetUnreadMessage = errors.New("get unread message")
ErrMarkOneMessage = errors.New("mark one message")
ErrMar... |
// Copyright 2020 The Operator-SDK 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 ... |
package handlers
import (
"github.com/dgrijalva/jwt-go"
"github.com/labstack/echo"
"time"
)
type JwtClaims struct {
Email string
jwt.StandardClaims
}
func CreateJwtToken(email string) (string, error) {
claims := JwtClaims{
email,
jwt.StandardClaims{
ExpiresAt: time.Now().Add(24 * time.Hour).Unix(),
},... |
package tenantfederation
import (
"context"
"errors"
"fmt"
"reflect"
"sort"
"strings"
"testing"
"time"
"github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/mocktracer"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prome... |
package main
import (
"os"
"fmt"
"log"
"bufio"
//"net/url"
"bytes"
"strings"
"net/http"
"io/ioutil"
"encoding/json"
"time"
"math/rand"
"regexp"
);
type RelayMessage struct {
Msg string `json:"msg"`
RelayIndex int `json:"relayIndex"`
NodeURLs []string `json:"nodeURLs"`
}
func RandomSubset(list []strin... |
package skel
import (
"github.com/globalsign/mgo"
)
// Del 定义删除操作
func (skel *Skel) Del() (err error) {
c := skel.GetC()
defer c.Database.Session.Close()
err = c.Remove(skel)
if err != nil {
if err != mgo.ErrNotFound {
return
}
err = nil
return
}
return
}
|
package main
import (
"fmt"
)
type Person struct {
Id string
Name string
Num int32
}
type IError struct {
Op string
Path string
Err error
}
func main() {
var per map[string]Person
per = make(map[string]Person, 5)
per["123"] = Person{"456", "jack", 789}
temp, ok := per["123"]
if ok {
tt := Person... |
package secrets
import (
"encoding/json"
"io/ioutil"
"log"
)
type secrets struct {
Token string
}
// ReadTokenFromSecrets will read the JSON file located at 'path' and return
// the value of the 'token' key within. Super secure local token storage!
func ReadTokenFromSecrets(path string) (token string) {
fileCon... |
// +build acceptance networking lbaas_v2 monitors
package elbaas
import (
"testing"
//"github.com/gophercloud/gophercloud/acceptance/clients"
//"github.com/gophercloud/gophercloud/acceptance/tools"
//"github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/elbaas/healthcheck"
)
func TestHealthList... |
package states
import (
"context"
"time"
cloudevents "github.com/cloudevents/sdk-go/v2"
derrors "github.com/direktiv/direktiv/pkg/flow/errors"
log "github.com/direktiv/direktiv/pkg/flow/internallogger"
"github.com/direktiv/direktiv/pkg/model"
"github.com/google/uuid"
)
type Instance interface {
GetInstanceID... |
package server
import (
"errors"
"io"
"net"
"server/libs/log"
"server/libs/rpc"
"server/share"
"server/util"
"golang.org/x/net/websocket"
)
var (
ERRNOTSUPPORT = errors.New("not support")
)
type ClientCodec struct {
rwc io.ReadWriteCloser
cachebuf []byte
node *ClientNode
}
func (c *ClientCodec... |
package main
import (
"context"
"errors"
"testing"
"time"
"github.com/brigadecore/brigade/v2/scheduler/internal/lib/queue"
"github.com/stretchr/testify/require"
)
func TestRunHealthcheckLoop(t *testing.T) {
testCases := []struct {
name string
scheduler *scheduler
assertions func(error)
}{
{
... |
package main
import (
"errors"
"flag"
"fmt"
"io/ioutil"
"os"
"os/user"
"strings"
)
type Task struct {
description string
}
type TaskList struct {
tasks []*Task
}
func (t *TaskList) Add(taskDescription string) {
if t.tasks == nil {
t.tasks = make([]*Task, 0)
}
task := Task{description: taskDescription}... |
package models
import (
"fmt"
)
func DBhandler(db, sqlformat string) {
sql := fmt.Sprintf("/*--user=%s;--password=%s;--host=%s;--execute=1;--port=%s;*/"+
"inception_magic_start;"+
"use %s;"+
"%s;"+
"inception_magic_commit;", MySQLRemoteUser, MySQLRemotePass, MySQLRemoteHost, MySQLRemotePort, db, sqlformat)
... |
package cmd
import (
"context"
"errors"
"time"
"github.com/dkorittki/loago/internal/pkg/instructor/client"
"github.com/spf13/cobra"
)
// pingCmd represents the ping command
var pingCmd = &cobra.Command{
Use: "ping",
Short: "Test connection to workers",
Long: `Ping tests the connectivity to workers specific... |
package main
import (
"bytes"
"flag"
"fmt"
"io"
"log"
"rtsp"
)
func init() {
flag.Parse()
}
const sampleRequest = `OPTIONS rtsp://example.com/media.mp4 RTSP/1.0
CSeq: 1
Require: implicit-play
Proxy-Require: gzipped-messages
`
const sampleResponse = `RTSP/1.0 200 OK
CSeq: 1
Public: DESCRIBE, SETUP, TEARDOWN... |
package cmd
import (
"fmt"
"github.com/spf13/cobra"
"os"
)
var rootCmd = &cobra.Command{
Use: "regit",
Short: "Regit is for git commands that support regular expressions",
Long: `Regit is for git commands that support regular expressions`,
Run: func(cmd *cobra.Command, args []string) {
},
}
var dryRun boo... |
// 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 handlers
import (
"bytes"
"database/sql"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"sync"
"github.com/SIGBlockchain/project_aurum/internal/block"
"github.com/SIGBlockchain/project_aurum/internal/contracts"
"github.com/SIGBlockchain/project_aurum/internal/ifaces"
"github.com/SIGBloc... |
package subscription
import (
"github.com/dennor/go-paddle/events/types"
"github.com/dennor/phpserialize"
)
const CancelledAlertName = "subscription_cancelled"
// Cancelled refer to https://paddle.com/docs/subscriptions-event-reference/#subscription_cancelled
type Cancelled struct {
AlertID int ... |
package main
import "fmt"
func main(){
//自动推导
var a = 10
fmt.Println(a)
fmt.Printf("%T\n",a)
//常用的自动推导
//自动推导 := 左边变量名没使用过
b := 10
b = 20
b = 30
fmt.Println(b)
c :=3.14
fmt.Println(c)
fmt.Printf("%T\n",c)
d,f,e := 20,3.14,30
fmt.Println(d,f,e)
fmt.Printf("%T",e)
} |
package RemoteSyslog
import (
"time"
"os"
"errors"
"net"
"strconv"
"github.com/op/go-logging"
)
type PapertrailBackend struct {
ClientHostname string
Tag string
Hostname string
Network string
ConnectTimeout int
WriteTimeout int
Port ... |
package main
import (
"fmt"
)
const (
a = 42 //untyped constant
v int = 43 //typed constant
)
func main() {
fmt.Println(v)
fmt.Printf("%T\n", v)
fmt.Println(a)
fmt.Printf("%T", a)
} |
package more
import "fmt"
type Vertex struct {
X int
Y int
}
func Struct() {
fmt.Println("== Struct ==")
fmt.Println(Vertex{1, 2})
}
func StructField() {
fmt.Println("== StructField ==")
v := Vertex{1, 2}
v.X = 4
fmt.Println(v.X)
}
func StructPointer() {
fmt.Println("== StructPointer... |
package command
import (
"github.com/urfave/cli"
)
func (p *Handler) MakeProjectCommand(ctx *cli.Context) (err error) {
p.init()
p.renderStatic()
p.make()
p.makeConfig()
p.make()
p.makeCurd()
p.make()
p.makeService()
p.make()
p.makeApi()
p.make()
p.clean()
p.done()
return
}
|
package cgroups
import (
"fmt"
"github.com/opencontainers/runtime-spec/specs-go"
"github.com/sirupsen/logrus"
"io/ioutil"
"os"
"path/filepath"
"strconv"
)
const (
//cgroupMemorySwapLimit = "memory.memsw.limit_in_bytes"
//cgroupMemoryLimit = "memory.limit_in_bytes"
cgroupKernelMemoryLimit = "memory.kmem.... |
package setr
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document01100103 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:setr.011.001.03 Document"`
Message *SubscriptionOrderCancellationRequestV03 `xml:"SbcptOrdrCxlReqV03"... |
package common
import (
"fmt"
"log"
"math/rand"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/hashicorp/raft"
raftboltdb "github.com/hashicorp/raft-boltdb"
)
const (
GET = "get"
SET = "set"
DEL = "del"
LEADER = "leader"
EXIT = "exit"
TXN = "txn"
ADD ... |
// +build test
package utils
import "github.com/gookit/gcli/v3/interact"
func readPassword(question ...string) string {
pwd, _ := interact.ReadLine(question[0])
return pwd
}
|
package chart_extender
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"text/template"
"helm.sh/helm/v3/pkg/postrender"
"github.com/mitchellh/copystructure"
"github.com/werf/werf/pkg/deploy/secrets_manager"
"github.com/werf/logboek"
"sigs.k8s.io/yaml"
helm_... |
/*
Copyright 2017, Yoshiki Shibukawa
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 queries
import (
"log"
"github.com/jmoiron/sqlx"
"gitlab.com/semestr-6/projekt-grupowy/backend/obsluga-formularzy/attributes/models"
"gitlab.com/semestr-6/projekt-grupowy/backend/obsluga-formularzy/configuration"
)
const GET_RESOURCE_BY_ID_SQL = `
SELECT
*
FROM
resources."Resources" r
WHERE
r."Reso... |
func optimalDivision(nums []int) string {
res:=""
num:=make([]string,len(nums))
for i,v:=range nums{
num[i] = strconv.Itoa(v)
}
res+=num[0]
if len(num)>2{
res+="/("+strings.Join(num[1:],"/")+")"
}else if len(num)>1{
res+="/"+num[1]
}
return res
}
|
package server
import (
"errors"
"log"
"net"
"strings"
)
type Server interface {
Run() error
Close() error
}
func NewServer(protocol, addr string, dh DataHandler) (Server, error) {
switch strings.ToLower(protocol) {
case "tcp":
return &TCPServer{
addr: addr,
dataHandler: dh,
}, nil
case "ud... |
//go:generate go-bindata -pkg static -ignore .../.DS_Store -o files.go files/...
package static
import (
"net/http"
"os"
"github.com/elazarl/go-bindata-assetfs"
)
// all static/ files embedded as a Go library
func FileSystemHandler() http.Handler {
var h http.Handler
if info, err := os.Stat("static/files/"); e... |
package Util
import (
"testing"
)
func TestNewHashMap(t *testing.T) {
h := NewHashMap(HashCrc)
ipList := []string{"192.168.0.1","192.168.0.2","192.168.0.3","192.168.0.4","192.168.0.1#1","192.168.0.2#2","192.168.0.3#3","192.168.0.4#4"}
for _, v := range ipList{
h.Add(v)
}
k1 := h.Get("10.10.10.1")
k2 := h.G... |
package main
import (
"github.com/gin-gonic/gin"
"github.com/gorilla/securecookie"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/memstore"
uuid "github.com/iris-contrib/go.uuid"
)
func main() {
gin.SetMode("release")
app := gin.New()
storeKey := securecookie.GenerateRandomKey(32)
stor... |
/*
gonum_test contains basic test functions which demonstrate the various matrix operations available in gonum
*/
package structures
import (
"testing"
"gonum.org/v1/gonum/mat"
)
// Test01 shows how to multiply two matrices and scale a matrix
func Test01(t *testing.T) {
var a, b, c *mat.Dense
a = ones(2, 2)
b ... |
package parser
import (
"io/ioutil"
"testing"
)
func assertSameSlice(t *testing.T, result, expected []string) {
t.Helper()
if len(result) != len(expected) {
t.Errorf("Expected '%q' but got '%q'", expected, result)
}
for _, val1 := range result {
exists := false
for _, val2 := range expected {
if val1... |
/*
Nikolay has a lemons, b apples and c pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio 1: 2: 4. It means that for each lemon in the compote should be exactly 2 apples and exactly 4 pears. You can't crumble up, break up or cut these fruits into pieces. These fruits — lemo... |
package controllers
import (
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/trewzaki/gin-lab/models"
)
func CreateUser(c *gin.Context) {
userModel := models.User{}
c.ShouldBindWith(&userModel, binding.JSON)
if createUserErr := models.DB.Create(&userModel).Err... |
//+build !test
package main
import (
"context"
"golang-api/handler"
"log"
"net/http"
)
func main() {
var m = http.NewServeMux()
var s = http.Server{Addr: ":8080", Handler: m}
m.HandleFunc("/hash", handler.HashPassword)
m.HandleFunc("/shutdown", handler.ExecuteShutdown)
m.HandleFunc("/stats", handler.Proces... |
package roll
import (
"context"
"fmt"
"os"
"time"
"github.com/square/p2/pkg/alerting"
"github.com/square/p2/pkg/audit"
"github.com/square/p2/pkg/health"
"github.com/square/p2/pkg/logging"
"github.com/square/p2/pkg/manifest"
"github.com/square/p2/pkg/pods"
"github.com/square/p2/pkg/rc"
rcf "github.com/squa... |
/*
Copyright IBM Corporation 2020
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... |
package db
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
"quoter/src/api/config/loggers"
)
var Database *sql.DB
const (
host = "localhost"
port = 5432
password = "quoter"
user = "quoter"
dbName = "quoter"
)
func ConnectAndSetDatabase() {
connectionString := fmt.Sprintf("host=%s port=%... |
package p07
func minCostClimbingStairs(cost []int) int {
a := cost[0]
b := cost[1]
for i := 2; i < len(cost); i++ {
var c int
if a < b {
c = a + cost[i]
} else {
c = b + cost[i]
}
a = b
b = c
}
if a < b {
return a
}
return b
}
|
package main
import "fmt"
func main() {
square := func(num int) int {
return num * num
}
v := square(5)
fmt.Println(v)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.