text stringlengths 11 4.05M |
|---|
package machinetypes
import (
"encoding/json"
"log"
"net/http"
"github.com/qnib/metahub/pkg/daemon"
"github.com/qnib/metahub/pkg/storage"
"github.com/gorilla/context"
)
func getAddHandler(service daemon.Service) http.Handler {
storageService := service.Storage()
return http.HandlerFunc(func(w http.Respons... |
// Package aws2tf ingests JSON from AWS CLI and emits Terraform templates.
// Currently, only security groups are implemented. Poorly, at that.
//
// TODO:
// - learn interfaces
// - make the ipRange.print* methods nicer
package aws2tf
import (
"fmt"
)
type ipRange struct {
Description string
CidrIP string
}
... |
package main
import (
"im/config"
"im/internal/logic/api"
"im/pkg/db"
"im/pkg/logger"
"im/pkg/rpc"
)
func main() {
logger.Init()
db.InitMysql(config.Logic.MySQL)
db.InitRedis(config.Logic.RedisIP, config.Logic.RedisPassword)
// 初始化RpcClient
rpc.InitConnIntClient(config.Logic.ConnRPCAddrs)
rpc.InitUserIntC... |
// Copyright 2019 GoAdmin Core Team. All rights reserved.
// Use of this source code is governed by a Apache-2.0 style
// license that can be found in the LICENSE file.
package dialect
import (
"strings"
"github.com/GoAdminGroup/go-admin/modules/config"
)
// Dialect is methods set of different driver.
type Dialec... |
package django
const Requirements = `
# Requirements
Django==1.8.3
PyMySQL==0.6.6
python-memcached==1.54
pytz==2015.4
#whitenoise==2.0.2
webassets==0.10.1
cssmin==0.2.0
jsmin==2.1.2
django-assets==0.10
django-markdown==0.8.4
django-easy-pjax==1.2.0
#django-material==0.4.1
djangorestframework==3.2.0
django-debug-toolb... |
package main
import (
"github.com/gin-gonic/gin"
api "app/pkg/api"
"os"
)
/*
* Setup main router
*/
func setupRouter() *gin.Engine {
router := gin.Default()
//Upload OPTIONS API Entry
router.OPTIONS("/upload", func(c *gin.Context) {
api.ApplyHeaders(c)
})
//Download GET API Entry... |
package mobile
import (
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
"github.com/textileio/go-textile/core"
"github.com/textileio/go-textile/mill"
"github.com/textileio/go-textile/pb"
)
// AddSchema adds a new schema via schema mill
func (m *Mobile) AddSchema(node []byte) ([]byte, error... |
package dashboard
import (
"fmt"
"net/http"
"github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/balance"
"github.com/iotaledger/wasp/packages/chain"
"github.com/iotaledger/wasp/packages/coretypes"
"github.com/iotaledger/wasp/packages/hashing"
"github.com/iotaledger/wasp/packages/kv/codec"
"github.c... |
package rpc
import (
"context"
"errors"
"time"
"github.com/rs/xid"
v1 "github.com/tinkerbell/pbnj/api/v1"
"github.com/tinkerbell/pbnj/grpc/oob/bmc"
"github.com/tinkerbell/pbnj/pkg/logging"
"github.com/tinkerbell/pbnj/pkg/task"
)
// BmcService for doing BMC actions.
type BmcService struct {
Log logging.Logge... |
package initcmd
import (
"bytes"
"path/filepath"
"reflect"
"time"
"github.com/devspace-cloud/devspace/pkg/util/survey"
"github.com/sirupsen/logrus"
"github.com/devspace-cloud/devspace/cmd"
"github.com/devspace-cloud/devspace/e2e/utils"
"github.com/devspace-cloud/devspace/pkg/devspace/build/builder/helper"
... |
// Copyright 2017 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 controller
import (
"fmt"
"github.com/go-kit/kit/log/level"
"github.com/pkg/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/cache"
)
// runWorker is a long-running function that will continually call the
// processNextWorkItem function in order to read and process a messag... |
package main
import (
"context"
"encoding/binary"
"github.com/juju/errors"
"github.com/pingcap/tidb/kv"
)
var (
emptyBytes = make([]byte, 0)
paddingZeros = make([]byte, 9)
errCorruptedData = errors.New("Failed to decode corrupted data")
)
const (
rdbEscapeLength = 9
signMask = 0x8000000000... |
package main
import (
"fmt"
)
// 53. 最大子序和
// 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
// 进阶:
// 如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。
// https://leetcode-cn.com/problems/maximum-subarray/
func main() {
// fmt.Println(maxSubArray3([]int{-2, 1, -3, 4, -1, 2, 1, -5, 4})) // 6
fmt.Println(maxSubArray3([]int... |
package main
//给定一个整数数组 prices ,它的第 i 个元素 prices[i] 是一支给定的股票在第 i 天的价格。
//
//设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。
//
//注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
//
//
//
//示例 1:
//
//输入:k = 2, prices = [2,4,1]
//输出:2
//解释:在第 1 天 (股票价格 = 2) 的时候买入,在第 2 天 (股票价格 = 4) 的时候卖出,这笔交易所能获得利润 = 4-2 = 2 。
func main() {
}
func maxProfit(k ... |
package inmemory
import (
"encoding/json"
"math/rand"
"os"
"path/filepath"
"sync"
"time"
"github.com/Tinee/go-graphql-chat/domain"
)
type Client struct {
u *userInMemory
ms *messagesInMemory
p *profileInMemory
}
func NewClient() *Client {
return &Client{
u: &userInMemory{
mtx: &sync.Mutex{},
},
... |
package mbclient
func (c *MBClient) getTypeString(typeFilters []string) string {
typesString := "("
for i, filter := range typeFilters {
typesString += "type:" + filter
if i < len(typeFilters)-1 {
typesString += " OR "
}
}
typesString += ")"
return typesString
}
|
package multiply
import (
"fmt"
"strings"
)
func multiply(num1, num2 string) (mult string) {
baseNum := map[byte]int{
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'0': 0,
}
length1, length2 := len(num1), len(num2)
result := make([][]int, length1)
slot := 0
for i ... |
package controller
import (
"fmt"
"log"
"net/http"
"local.ex/main/pages/about"
"local.ex/main/pages/home"
)
func Controller() {
port := "7890"
fmt.Printf("Starting server on port %q...\n", port)
http.HandleFunc("/", home.Page)
http.HandleFunc("/about", about.About)
err := http.ListenAndServe(":"+port, ni... |
package main
import "fmt"
func main() {
var N int
fmt.Scanf("%d", &N)
for n := 0; n < N; n++ {
var x int
var sum int
fmt.Scanf("%d", &x)
for i := 1; i < x; i++ {
if x%i == 0 {
sum += i
}
}
if sum != x {
fmt.Printf("%d nao eh perfeito\n", x)
continue
}
fmt.Printf("%d eh perfeito... |
package main
import (
"context"
"fmt"
"github.com/cmcpasserby/scli"
"github.com/cmcpasserby/unity-loader/unity"
)
func createSearchCmd() *scli.Command {
return &scli.Command{
Usage: "unity-loader search [partialVersion]",
ShortHelp: "Searches for a unity version on the archive site",
LongHelp: ... |
// 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 release
import (
"archive/zip"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"time"
"github.com/ExploratoryEngineering/reto/pkg/gitutil"
"github.com/ExploratoryEngineering/reto/pkg/toolbox"
)
// Build builds a new release from the current setup
func Build(tagVersion, commitNewRelease bool) error {... |
package middlewares
import (
"devbook-api/src/authentication"
"devbook-api/src/responses"
"log"
"net/http"
)
func Logger(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Printf("\n %s %s %s", r.Method, r.RequestURI, r.Host)
next(w, r)
}
}
func Authenticate... |
package animal
import (
"encoding/json"
"errors"
"github.com/game-explorer/animal-chess-server/model"
"github.com/game-explorer/animal-chess-server/repository"
)
type MessageRsp struct {
ToPlayerId int64
Msg model.Message
}
func buildJson(i interface{}) []byte {
bs, _ := json.Marshal(i)
return bs
}
f... |
package main
import (
"os"
"fmt"
"errors"
"strings"
)
type Config struct {
LogLevel int
ListenHost string
ListenPort int
GitLabUrl string
GitLabToken string
LabelPrefix string
LabelColor string
IgnoreUser string
}
func (config *Config) loadDefault() {
config.LogLevel = LOG_DEBUG
config.ListenH... |
package main
import (
"github.com/gorilla/mux"
"github.com/hellofresh/health-go"
"time"
)
func status(r *mux.Router) {
health.Register(health.Config{
Name: "server",
Timeout: time.Second * 5,
SkipOnErr: false,
Check: func() error {
// rabbitmq health check implementation goes here
return nil
... |
package module
import (
"fmt"
"buddin.us/eolian/dsp"
"github.com/mitchellh/mapstructure"
)
func init() {
Register("PanMix", func(c Config) (Patcher, error) {
var config struct {
Size int
}
if err := mapstructure.Decode(c, &config); err != nil {
return nil, err
}
if config.Size == 0 {
config.S... |
package couchdb
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"time"
)
type CouchDB struct {
client *http.Client
url *url.URL
}
type CouchDBConfig struct {
Host string
Database string
Username string
Password string
Timeout int
}
// Create new CouchDB from config
func New... |
package fakes
type FakeTemplateDeleter struct {
DeleteArgument string
DeleteError error
}
func NewFakeTemplateDeleter() *FakeTemplateDeleter {
return &FakeTemplateDeleter{}
}
func (fake *FakeTemplateDeleter) Delete(templateName string) error {
fake.DeleteArgument = templateName
return fake.Del... |
// Copyright 2016 The G3N 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 constraint
import (
"github.com/hecate-tech/engine/experimental/physics/equation"
)
// Distance is a distance constraint.
// Constrains t... |
package main
import (
"app/base/core"
"app/listener"
"app/manager"
"log"
"os"
)
func main() {
core.ConfigureApp()
if len(os.Args) > 1 {
switch os.Args[1] {
case "listener":
listener.RunListener()
return
case "manager":
manager.RunManager()
return
}
}
log.Fatal("You need to provide a comm... |
package kubectl
import (
"context"
"io"
"net"
"net/http"
"net/url"
"sort"
"time"
"github.com/devspace-cloud/devspace/pkg/devspace/config/generated"
"github.com/devspace-cloud/devspace/pkg/devspace/config/versions/util"
"github.com/devspace-cloud/devspace/pkg/devspace/kubectl/portforward"
"github.com/devspa... |
package launchpad
import (
"gitlab.com/gomidi/midi"
)
type scrollingTextBuilderS struct {
Seq []byte
outputStream midi.Out
}
func (l *LaunchpadS) Text(color Color) ScrollingTextBuilder {
return l.text(color, false)
}
func (l *LaunchpadS) TextLoop(color Color) ScrollingTextBuilder {
return l.text(color... |
package main
import(
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/gob"
"encoding/pem"
"fmt"
"os"
)
//Function main generates an rsa key with a size of 512 bytes, chekcs for errors.
//Prints genrated private key primes and exponent
//Prints genrated publicKey modulus and exponent
//Saves the privat... |
package main
import (
"bytes"
"crypto/cipher"
"testing"
)
func TestXORCipher(t *testing.T) {
cases := []struct {
stream cipher.Stream
src, want []byte
}{
{
NewXORCipher([]byte{1, 2}),
[]byte{1, 2, 3, 4, 5, 6},
[]byte{0, 0, 2, 6, 4, 4},
},
{
NewXORCipher([]byte{1, 2, 3}),
[]byte{1, 2, ... |
package inc
import (
"bufio"
"os"
"regexp"
)
func FGrepBool(file string, reg *regexp.Regexp) bool {
if f, err := os.Open(file); err == nil {
buf := bufio.NewReader(f)
for {
line, err := buf.ReadBytes('\n')
if err != nil {
return false
}
if reg.Match(line) {
return true
}
}
}
return ... |
package checksum
import (
"bufio"
"math"
"strconv"
"strings"
)
// Checksum returns a spreadsheet checksum.
// For each row, determine the difference between the largest
// value and the smallest value; the checksum is the sum of all
// of these differences
func Checksum(spreadsheet string) int {
var checksum = 0... |
package cmd
import (
"bufio"
"bytes"
"io"
"time"
)
type Reader struct {
reader io.Reader
BytesRead int
}
func newReader(r io.Reader) *Reader {
return &Reader{reader: r}
}
func (r *Reader) Read(p []byte) (n int, err error) {
n, err = r.reader.Read(p)
r.BytesRead += n
return n, err
}
type Message struct... |
package clubs
import (
"os"
"github.com/anihouse/bot/app"
"github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
)
var (
log *logrus.Logger
conf cfg
)
type module struct {
app *app.Module
enabled bool
}
func (module) ID() string {
return "clubs"
}
func (m module) IsEnabled() bool {
return m.enabled
}
fun... |
package bytestrings
import (
"testing"
)
func TestWorkWithBuffer(t *testing.T) {
err := WorkWithBuffer()
if err != nil {
t.Errorf("unexpected error")
}
}
|
package main
import "fmt"
func main() {
names := []string{}
names[0] = "Goku"
fmt.Println(names)
}
|
package main
import (
"encoding/json"
"fmt"
)
//序列化:把go语言中的结构体变量-->json格式字符串
//反序列化:把json格式字符串 --> go语言可以识别的结构体变量
type person struct{
Name string //首字母大写,因为是json转换的,所以json需要拿到该变量,所以需要首字母大写
Age int
}
//下面的方法可以使变量名为小写字母开头
type person2 struct{
Name string `json:"name",db:"name",ini:"name"` //表示在json 数据库 ini配置文件以... |
package worker
import (
"fmt"
"testing"
"time"
"github.com/brunoga/context"
)
func TestWorker_New_NilWorkerFunc(t *testing.T) {
w, err := New(nil)
if w != nil {
t.Errorf("Expected nil Worker.")
}
if err != ErrNilWorkerFunc {
t.Errorf("Expected ErrNilWorkerFunc error. Got %q.", err)
}
}
func TestWorker_... |
package main
import "secure/app"
func main() {
app.Start()
}
|
package util
import (
"context"
"fmt"
"path/filepath"
"strings"
"github.com/werf/werf/pkg/docker"
)
func RemoveHostDirsWithLinuxContainer(ctx context.Context, mountDir string, dirs []string) error {
var containerDirs []string
for _, dir := range dirs {
containerDirs = append(containerDirs, ToLinuxContainerP... |
package goo_mq
import (
"fmt"
"github.com/Shopify/sarama"
"github.com/liqiongtao/goo"
"time"
)
type KafkaProducer struct {
*Kafka
producer sarama.AsyncProducer
}
func (*KafkaProducer) config() *sarama.Config {
config := sarama.NewConfig()
config.Producer.RequiredAcks = sarama.WaitForAll
config.Producer.Part... |
package leetcode
func buddyStrings(A string, B string) bool {
if A == B {
dup := make(map[rune]struct{})
for _, c := range A {
if _, ok := dup[c]; ok {
return true
}
dup[c] = struct{}{}
}
return false
}
chA, chB := byte(0), byte(0)
lA, lB := len(A), len(B)
if lA != lB {
return false
}
cha... |
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"time"
)
func main() {
fs := http.FileServer(http.Dir("static"))
http.Handle("/favicon.ico", http.StripPrefix("/favicon.ico", fs))
http.HandleFunc("/", handleJob)
log.Println("Server started on port 3000")
http.ListenAndServe(":3000", nil)
}
//Pa... |
// Copyright (c) 2020 Xiaozhe Yao & AICAMP.CO.,LTD
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
package entities
import (
"reflect"
"testing"
)
func TestPrivateEnvironment_TableName(t *testing.T) {
type fields struct {
ID string
Name string
}
tests := []str... |
package utils
import (
"bytes"
"encoding/gob"
"log"
)
func GetBytes(data interface{}) ([]byte, error) {
var buffer bytes.Buffer
encoder := gob.NewEncoder(&buffer)
err := encoder.Encode(data)
if err != nil {
return nil, err
}
return buffer.Bytes(), nil
}
func MLogger(message string, statusCode int, err err... |
package models
import (
"gopkg.in/mgo.v2/bson"
"github.com/astaxie/beego"
)
// task model
type Task struct {
Id bson.ObjectId `bson:"_id" json:"id" form:"-"`
Name string `bson:"name" json:"name" form:"name"`
Done bool `bson:"done" json:"done" form:"done"`
}
// db & collection info
// extracting it from... |
package reflection
import (
"fmt"
"log"
"math"
"reflect"
"testing"
)
type ExampleStruct struct {
Int8 int8
Int16 int16
Int32 int32
Int64 int64
Uint8 uint8
Uint16 uint16
Uint32 uint32
Uint64 uint64
Float32 float32
Float64 float64
Bool bool
String string
Map map[string]int
Func ... |
package setup
import (
"fmt"
"github.com/gardener/test-infra/integration-tests/e2e/config"
"github.com/gardener/test-infra/integration-tests/e2e/kubetest"
"github.com/gardener/test-infra/integration-tests/e2e/util"
tmutil "github.com/gardener/test-infra/pkg/util"
"github.com/hashicorp/go-multierror"
"github.com... |
package database
import (
"testing"
)
func TestMysql(t *testing.T) {
DB := Connect()
err := DB.Ping()
if err != nil {
t.Errorf("DB connection %d", "ping error")
}
}
|
package bundler
import (
"log"
"os"
"github.com/streadway/amqp"
)
var (
amqpURI = "amqp://" + os.Getenv("RABBITMQ_HOST") + ":" +
os.Getenv("RABBITMQ_PORT")
amqpExchange = "siphon.apps.notifications"
amqpExchangeType = "fanout"
amqpConsumerTag = "siphon-bundler"
)
// PostAppUpdated sends an app_updated... |
package main
import "fmt"
func main() {
defer fmt.Println("Bye")
defer fmt.Println("Bye1")
fmt.Println("Hello")
fmt.Println("Hye")
}
|
package aws
import (
"context"
"encoding/base64"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/pkg/error... |
package assertions
import (
"encoding/json"
"fmt"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestShouldEqual(t *testing.T) {
type args struct {
actual interface{}
expected []interface{}
}
tests := []struct {
name string
args args
wantErr bool
}{
{
name: "with string"... |
package main
import (
"cloud.google.com/go/logging"
cplogging "commentparser/logging"
"commentparser/models"
"commentparser/server"
"commentparser/services"
"encoding/json"
"fmt"
"golang.org/x/net/context"
"google.golang.org/api/option"
"io/ioutil"
"log"
"os"
"strings"
"time"
)
// entry point for the ap... |
// Copyright 2019 Yunion
//
// 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 writi... |
package redis
import (
"context"
"time"
"github.com/gomodule/redigo/redis"
"github.com/pkg/errors"
)
//go:generate confions config Config
// Config contains configuration options for a connection pool to a redis
// database.
type Config struct {
Network string
Address string
Database ... |
package evaluation
// #cgo CFLAGS: -I${SRCDIR}/../rust
// #cgo LDFLAGS: -L${SRCDIR}/../rust/expr_tree/target/release -lexpr_tree
// #include "expr_tree/src/expr_tree.h"
// #include <stdlib.h>
import "C"
import (
"reflect"
"unsafe"
)
// EvalFromBytesRust passes the given flatbuffer to Rust for evaluation,
// and ret... |
package 数组
import (
"bytes"
"strings"
)
func numUniqueEmails(emails []string) int {
hasEmailExist := make(map[string]bool)
for _, email := range emails {
hasEmailExist[getFormattedEmail(email)] = true
}
return len(hasEmailExist)
}
func getFormattedEmail(email string) string {
parts := strings.Split(email, "... |
package main
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func buildTree(preorder []int, inorder []int) *TreeNode {
return buildfTreeRe(preorder, inorder)
}
// 递归从先跟中找到跟,从中跟中找到位置 ,划分左右子树
func buildfTreeRe(preorder []int, inor... |
// Copyright 2017 The Fuchsia 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 main
import (
"fmt"
"log"
"strings"
"app/context"
"fidl/bindings"
"netstack/link/eth"
"syscall/zx"
"syscall/zx/mxerror"
"garnet/public/... |
func convertToTitle(n int) string {
res:=[]rune{}
for n!=0{
n--
res = append([]rune{rune(n%26)+'A'},res...)
n = n/26
}
return string(res)
}
|
package main
import (
"html/template"
"os"
"log"
"strings"
)
var tpl *template.Template
type structure struct{
Name string
Age int
}
var fm = template.FuncMap{
"trim" : first_3,
}
func first_3(str string) string{
str = strings.TrimSpace(str)
str =str[:3]
return str
}
func init(){
tpl=template.Must(... |
package listener
import (
"app/base/database"
"app/base/structures"
"github.com/bmizerany/assert"
"testing"
"app/base/core"
)
func TestStorageInit(t *testing.T) {
storage := InitStorage(3, false)
assert.Equal(t, 0, storage.StoredItems())
assert.Equal(t, 3, storage.Capacity())
}
func TestStorageFlush(t *test... |
package transactions
import (
"encoding/json"
"net/http"
"github.com/garyburd/redigo/redis"
"github.com/felipeguilhermefs/restis/router"
)
func MultiRoute(conn redis.Conn) router.Route {
return router.Route{
"/multi",
"POST",
MultiHandler(conn),
}
}
func MultiHandler(conn redis.Conn) http.H... |
package main
import "fmt"
type Vehicle interface {
Move()
}
type Car struct {
MovementType string
}
// This method means type Car implements the interface Vehicle,
// but we don't need to explicitly declare that it does so.
func (c Car) Move() {
fmt.Println(c.MovementType)
}
func main() {
var v Vehicle = Car{"... |
package command
import (
"fmt"
"github.com/urfave/cli"
"mix/core/logger"
"mix/core/plugin"
"mix/plugins/mysql"
"os"
)
const (
NAME = "mysql"
DATABASE = "database"
CONNECTION = "connection"
USERS = "users"
USERNAME = "username"
PASSWORD = "password"
PRIVILEGES = "privileges"
HOST =... |
package api
import (
"fmt"
"net/http"
"net/http/httptest"
"os"
"regexp"
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewHTTPClient(t *testing.T) {
type args struct {
config token... |
package caaa
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document01400103 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:caaa.014.001.03 Document"`
Message *AcceptorDiagnosticResponseV03 `xml:"AccptrDgnstcRspn"`
}
func (d *Document... |
package util
import (
log "github.com/sirupsen/logrus"
"sigs.k8s.io/yaml"
)
func MustUnmarshallYAML(text string, v interface{}) {
err := yaml.UnmarshalStrict([]byte(text), v)
if err != nil {
log.Warnf("invalid YAML: %v", err)
err = yaml.Unmarshal([]byte(text), v)
}
if err != nil {
panic(err)
}
}
|
package connection
import (
"database/sql"
"go-mysql/config"
"time"
)
func GetGoblogConn () *sql.DB{
dbgoblog := config.GetDbByPath("goblog").GetDb()
dbgoblog.SetMaxIdleConns(0)
dbgoblog.SetConnMaxLifetime(300 * time.Second)
return dbgoblog
}
|
package main
import (
"fmt"
"github.com/pkg/errors"
)
type sampleError struct {
s string
}
func (e *sampleError) Error() string {
return e.s
}
func (e *sampleError) String() string {
return e.Error()
}
func main() {
err := errors.Wrap(mkError("test"), ":wrap") // Wrap()時にはwithStackされる
if isStringer(errors.C... |
// Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
package apilib
import (
"fmt"
"github.com/iotaledger/wasp/packages/coretypes/requestargs"
"github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/address/signaturescheme"
"github.com/iotaledger/wasp/client/level1"
"github.com/iotaledg... |
package server
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestUnmarshalJSON(t *testing.T) {
u := repeatedValue{}
assert.Nil(t, u.UnmarshalJSON([]byte("[1, 2, 3]")))
assert.Equal(t, []int64{1, 2, 3}, u.int64Val)
u = repeatedValue{}
assert.Nil(t, u.UnmarshalJSON([]byte("[1.2, 2.3, 3.4]")))
... |
package main
import "fmt"
//通道缓冲区
func main() {
//创建一个缓冲区,缓冲区大小为2,缓冲区的类型为int
ints := make(chan int, 2)
//往缓冲区里放数据
ints <- 5
ints <- 10
//从缓冲区里取数据
a := <-ints
b := <-ints
fmt.Println(a)
fmt.Println(b)
}
|
package client
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
)
func TestGetAuthString(t *testing.T) {
_ = os.Setenv("ARGO_TOKEN", "my-token")
defer func() { _ = os.Unsetenv("ARGO_TOKEN") }()
assert.Equal(t, "my-token", GetAuthString())
}
func TestNamespace(t *testing.T) {
_ = os.Setenv("ARGO_... |
package checks
import (
"encoding/json"
"fmt"
"os"
"github.com/xeipuuv/gojsonschema"
"github.com/yugabyte/yugabyte-db/managed/yba-installer/common"
log "github.com/yugabyte/yugabyte-db/managed/yba-installer/logging"
"sigs.k8s.io/yaml"
)
var ValidateInstallerConfig = &validateConfigCheck{"validate-config", fal... |
package testutil
var IntrospectionQuery = `
query IntrospectionQuery {
__schema {
queryType { name }
mutationType { name }
subscriptionType { name }
types {
...FullType
}
directives {
name
description
locations
args {
...InputValue
... |
package index1
import "testing"
func TestMethod1(t *testing.T) {
sum := Method1(10)
if sum != 55 {
t.Log("测试数据不符合预期")
t.FailNow()
}
t.Log("测试成功")
}
|
package main
import (
"flag"
"fmt"
"os"
)
func main() {
// 对于flag而言,第一个字段为命名,第二个字段为默认值,第三个值为帮助信息
name := flag.String("name", "张三", "姓名")
age := flag.Int("age", 18, "年龄")
married := flag.Bool("married", false, "婚否")
delay := flag.Duration("d", 0, "时间间隔")
flag.Parse()
fmt.Println("os args is", os.Args)
fmt.P... |
package cmd
import (
"github.com/bitmaelum/bitmaelum-suite/cmd/bm-client/handlers"
"github.com/spf13/cobra"
)
var listAccountsCmd = &cobra.Command{
Use: "list-accounts",
Aliases: []string{"list-account", "ls", "list"},
Short: "List your accounts",
Long: `Displays a list of all your accounts currently a... |
package main
import (
"fmt"
"time"
)
func main() {
timeObj := time.Now()
year := timeObj.Year()
month := timeObj.Month()
day := timeObj.Day()
fmt.Printf("%d-%02d-%02d \n", year, month, day)
/**
时间类型有一个自带的方法 Format进行格式化
需要注意的是Go语言中格式化时间模板不是长久的 Y-m-d H:M:S
而是使用Go的诞生时间 2006年1月2日 15点04分 (记忆口诀:2006 1 2 3 4... |
/*
* Copyright Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "... |
package controllers
import (
"github.com/gin-gonic/gin"
"github.com/sergiolucena1/database"
"github.com/sergiolucena1/models"
"strconv"
)
//Primeiro endpoint
func ShowProduct(c *gin.Context){
id := c.Param("id")
newid, err := strconv.Atoi(id) // convertendo pra inteiro
if err != nil{
c.JSON(400,gin.H{
"e... |
package realestatecomau_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"io/ioutil"
"testing"
)
func TestRealestatecomau(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Realestatecomau Suite")
}
var ReadRealEstateComAu_Buy_list_1 string
var _ = BeforeSuite(func() {
contents, err :... |
package logs
import (
"testing"
"github.com/10gen/realm-cli/internal/cloud/realm"
"github.com/10gen/realm-cli/internal/utils/test/assert"
)
func TestLogTypes(t *testing.T) {
for _, tc := range []struct {
logType string
logTypes []string
}{
{"", nil},
{logTypeAuth, []string{realm.LogTypeAuth, realm.LogT... |
package datasets
import (
"fmt"
"github.com/codeformuenster/dkan-newest-dataset-notifier/util"
"github.com/imroc/req"
)
type DatasetItem struct {
Modified ISODate `json:"modified"`
Issued ISODate `json:"issued"`
Title string `json:"title"`
Description string `json:"description"`
Identifier s... |
package web_param
type JwtParam struct {
Token string `json:"token"`
}
|
package main
import (
"fmt"
"log"
"net/http"
"evergrid/server/services/status"
"evergrid/db"
"github.com/ant0ine/go-json-rest/rest"
)
func main() {
connection := db.Connection{}
connection.Init()
fmt.Println(*connection.Users())
api := rest.NewApi()
api.Use(rest.DefaultDevStack...)
router, err := re... |
package fakes
import (
"github.com/cloudfoundry-incubator/notifications/models"
"github.com/cloudfoundry-incubator/notifications/postal"
)
type FakeMailRecipe struct {
DispatchArguments []interface{}
Responses []postal.Response
Error error
TrimCalled bool
}
func (fa... |
package main
import (
"testing"
"net/http"
"net/http/httptest"
"io/ioutil"
"strings"
"encoding/json"
)
func TestShowIndexPageUnauthenticated(t *testing.T) {
r := getRouter(true)
r.GET("/", showIndexPage)
req, _ := http.NewRequest("GET", "/", nil)
testHTTPResponse(t, r, req, func(w *httptest.ResponseRecorde... |
package main
/*
MIT License
Copyright (c) 2019 Horacio Duran <horacio.duran@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the right... |
package hot100
import (
"strconv"
"strings"
)
// 关键
// 回溯算法 dfs
// 并且,注意 current ,当append 之后是不可以重新初始化的,因为后续的递归dfs 依赖了这个
func restoreIpAddresses(s string) []string {
current:=make([]string,4)
ret:=make([]string,0)
var dfs func(index int,ipIndex int)
dfs= func(index int,ipIndex int) {
// dfs: 先考虑退出条件
// 当当前长... |
package rule
import (
ev "events"
"fmt"
"time"
)
type hisVolList struct{
totalVolume int
curVolume int
qhisVolume []int
}
func makeHisVolList() *hisVolList{
his := hisVolList{}
his.totalVolume = 0
his.curVolume = 0
his.qhisVolume = make([]int, 0, 4)
return &his
}
func (h... |
package main
import (
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
)
func main() {
//Get file directory from user input
fmt.Println("Enter the directory you want to clean (default-../TestFolder): ")
var root string
fmt.Scanln(&root)
var files []string
//Set default directory
if root == "... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.