text
stringlengths
11
4.05M
package state import ( "github.com/darkliquid/go-ircevent" "github.com/darkliquid/leader1/config" "sync" ) type StateTracker struct { channels map[string]*Channel nicks map[string]*Nick conn *irc.Connection mutex sync.Mutex cfg *config.Settings } func New(cfg *config.Settings, conn *irc.Connec...
package sem import ( "errors" "fmt" "net/smtp" "strings" ) // HOST smtp地址及端口 const HOST = "smtp.163.com:25" // SendMail 网易暂不支持通过API发送邮件,网易163邮箱发送邮件的逻辑函数 func SendMail(user, password, host, to, subject, body, mailtype string) error { hp := strings.Split(host, ":") auth := smtp.PlainAuth("", user, password, hp[0...
package micro import ( "mix/plugins/mysql" ) func MakeEntityMethods(renderService *RenderService, entity *mysql.Entity) { renderEntity := ToRenderEntity(entity) renderService.Entities = append(renderService.Entities, renderEntity) renderMethods := make([]*RenderMethod, 0) renderMethods = append(renderMethods,...
package metric // type TcpRow struct { LocalAddr string LocalPort uint16 RemoteAddr string RemotePort uint16 State int } // type TcpTable struct { Table []TcpRow } // 获取当前被监听的tcp端口号 func (p *TcpTable) GetActivePorts() []uint16 { var ports []uint16 if len(p.Table) == 0 { return ports } var tports =...
package control import ( . "../config" "sort" ) func add_new_peer_to_elevlist(id string) { var empty_queue [2][N_floors]int var empty_ack_list [2][N_floors]int for j := 0; j < 2; j++ { for k := 0; k < N_floors; k++ { empty_queue[j][k] = 0 empty_ack_list[j][k] = 0 } } new_empty_peer := elevator_states...
package main import "fmt" type MyInt int func (i MyInt) String() string { return "myint" } func main() { fmt.Printf("%s\n", MyInt(1)) }
package day09 import ( "strconv" "../utils" ) var input, _ = utils.ReadFile("day09/input.txt") var preamble = 25 func isValid(val int, list []int) bool { for i := 0; i < len(list); i++ { for j := i + 1; j < len(list); j++ { if list[i]+list[j] == val { return true } } } return false } // ParseLi...
/* There are many different styles of music and many albums exhibit multiple styles. Create a function that takes an array of musical styles from albums and returns how many styles are unique. Examples uniqueStyles([ "Dub, Dancehall", "Industrial, Heavy Metal", "Techno, Dubstep", "Synth-pop, Euro-Disco", "I...
package elements import ( "fmt" "sort" "strconv" "github.com/Nv7-Github/Nv7Haven/eod/types" ) func (b *Elements) FoundCmd(elem string, m types.Msg, rsp types.Rsp) { b.lock.RLock() dat, exists := b.dat[m.GuildID] b.lock.RUnlock() if !exists { return } rsp.Acknowledge() el, res := dat.GetElement(elem) ...
package mysql import ( "github.com/jinzhu/gorm" "github.com/smilga/analyzer/api" ) type FeatureStore struct { DB *gorm.DB } func (s *FeatureStore) All() ([]*api.Feature, error) { fs := []*api.Feature{} err := s.DB.Find(&fs).Error if err != nil { return nil, err } return fs, nil } func (s *FeatureStore) Ge...
package aoc2015 import ( "crypto/md5" "fmt" "strconv" ) // checkHash checks the first n nibbles (half-octets) of the MD5 of Augend+string(Addend) // and returns true if they are all zero. func checkHash(n int, augend string, addend int) bool { hash := md5.Sum([]byte(augend + strconv.Itoa(addend))) // This is wh...
package main import ( "fmt" "os" "os/signal" "path/filepath" "sync" "time" "github.com/containerd/containerd" "github.com/containerd/containerd/contrib/apparmor" "github.com/containerd/containerd/defaults" gocni "github.com/containerd/go-cni" "github.com/crosbymichael/boss/config" "github.com/crosbymichae...
/* Copyright 2021 The KubeVela Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, so...
package main import "fmt" func TypeJudge(items ...interface{}) { for index, v := range items { switch v.(type) { case bool: fmt.Printf("第%v参数是bool类型, 值:%v\n", index, v) case float64: fmt.Printf("第%v参数是float64类型, 值:%v\n", index, v) case int, int32, int64: fmt.Printf("第%v参数是整数类型, 值:%v\n", index, v) ...
package leetcode // Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. // Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. func intToRoman(num int) string { roman, decimalPlace := "", 1 symbols := map[int]string{1: "I", 2: "...
package ds /** * Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value. Example 1: Input: [1,12,-5,-6,50,3], k = 4 Output: 12.75 Explanation: Maximum average is (12-5-6+5...
// Copyright (c) 2019 Chair of Applied Cryptography, Technische Universität // Darmstadt, Germany. All rights reserved. This file is part of go-perun. Use // of this source code is governed by a MIT-style license that can be found in // the LICENSE file. package sim import ( _ "perun.network/go-perun/backend/sim/cha...
package main func myPow(x float64, n int) float64 { var N int64 N = int64(n) if n < 0 { x = 1 / x N = -N } return fastPow(x, N) } func fastPow(x float64, n int64) float64 { if n == 0 { return 1.0 } fast := fastPow(x, n/2) if n%2 == 0 { return fast * fast } else { return fast * fast * x } }
package git /* #include <git2.h> extern const git_oid * git_indexer_hash(const git_indexer *idx); extern int git_indexer_append(git_indexer *idx, const void *data, size_t size, git_transfer_progress *stats); extern int git_indexer_commit(git_indexer *idx, git_transfer_progress *stats); extern int _go_git_indexer_new(...
package main import ( "fmt" "time" ) func main() { go a() for i :=1;i<6;i++{ fmt.Println(i) time.Sleep(time.Millisecond) } } func a() { defer b() panic("A test panic!") } func b() { if demo := recover();demo != nil{ fmt.Println("Recover panic demo:", demo) } }
package main import ( "bartenderAsFunction/model" "reflect" "testing" "bartenderAsFunction/testUtils" "github.com/stretchr/testify/assert" "github.com/aws/aws-lambda-go/events" "encoding/json" ) func Test_serveCommand(t *testing.T) { type args struct { items *[]model.Item toServe string } tests := []s...
/* * Tencent is pleased to support the open source community by making Blueking Container Service available. * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except * in compliance with the License. You may obta...
package handler import ( "dappapi/models" jwt "dappapi/pkg/jwtauth" "dappapi/tools" "log" "net/http" "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/binding" "github.com/mojocn/base64Captcha" "github.com/mssola/user_agent" ) var store = base64Captcha.DefaultMemStore func PayloadFunc(data interface{}) ...
package main import "github.com/PuerkitoBio/fetchbot" import ( "fmt" "github.com/DennisDenuto/property-price-collector/data/training/dropbox" "github.com/DennisDenuto/property-price-collector/site" pphc "github.com/DennisDenuto/property-price-collector/site/propertypricehistorycom" log "github.com/Sirupsen/logrus...
package main import "fmt" type Person struct { LastName string FirstName string Age int } func (p Person) String() string { return fmt.Sprintf("%s:%s : Age: %d", p.LastName, p.FirstName, p.Age) } func main() { p := Person{ LastName: "hoge", FirstName: "fuga", Age: 20, } fmt.Println(p.Stri...
/* * KSQL * * This is a swagger spec for ksqldb * * API version: 1.0.0 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package swagger type Statement struct { Ksql string `json:"ksql,omitempty"` StreamsProperties *StatementStreamsProper...
/* * Copyright 2017 - 2019 KB Kontrakt 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 require...
package storage import ( "bytes" "encoding/json" "fmt" "io" "io/ioutil" "os" "path/filepath" "time" "github.com/naelyn/go-docker-registry/Godeps/_workspace/src/github.com/golang/glog" ) func unmarshalJson(r io.Reader, v interface{}) error { b, err := ioutil.ReadAll(r) if err == nil { err = json.Unmarsha...
package server import ( "errors" "net/http" "github.com/calvinmclean/automated-garden/garden-app/pkg" "github.com/rs/xid" ) // PlantRequest wraps a Plant into a request so we can handle Bind/Render in this package type PlantRequest struct { *pkg.Plant } // Bind is used to make this struct compatible with the g...
package rpn import ( "strconv" "unicode/utf8" ) type operator func(int, int) int var operations = map[rune]operator{ '+': func(left, right int) int { return left + right }, '-': func(left, right int) int { return left - right }, '*': func(left, right int) int { return left * right }, ...
package processtack // MinStackLink 节点元素 type MinStackLink struct { Min int Val int Next *MinStackLink } // ConstructorLink 初始化节点 func ConstructorLink() MinStackLink { return MinStackLink{} } // Push 入栈操作 func (stack *MinStackLink) Push(x int) { // 构建节点 temp := &MinStackLink{x, x, nil} if stack.Next == nil ...
package database import ( "gopkg.in/mgo.v2" "themis/utils" ) // Connect connects to the database, returning a database handle. func Connect(configuration utils.Configuration) (*mgo.Session, *mgo.Database) { session, err := mgo.DialWithInfo(&mgo.DialInfo { Addrs: []string { configuration.DatabaseHost }, Use...
package main import ( "fmt" "github.com/mayflower/docker-ls/lib" ) type versionCmd struct{} func (v versionCmd) execute(argv []string) error { fmt.Printf("version: %s\n", lib.Version()) return nil } func newVersionCmd() versionCmd { return versionCmd{} }
// 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 amqp_kit import ( "context" "net/http" "testing" "github.com/streadway/amqp" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) func TestNewError(t *testing.T) { e := NewError(`test message`, `test_message`, http.StatusBadRequest) assert.Equal(t, e.Code, `test_message`) asser...
package model const ( Port string= ":8899" )
package helpers import ( "time" ) func GetCurrentTimeStamp() string{ return time.Now().Format("2006-01-02 15:04:05") } func GetImageDirectory() string{ return time.Now().Format("2006/01/02/15") } func CurrentTimeMillis() int64{ return time.Now().Unix()*1000 }
package main import ( "fmt" "github.com/hnakamur/go-scp" "github.com/howeyc/gopass" "golang.org/x/crypto/ssh" "gopkg.in/yaml.v2" "os" "path/filepath" "strings" ) type Config struct { Server struct { User string `yaml:"user"` Port int8 `yaml:"port"` Host string `yaml:"host"` } `yaml:"server"` Path str...
package main import ( "context" "strings" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" ) func getClientIP(request events.ALBTargetGroupRequest) string { fwdHeader := request.Headers["x-forwarded-for"] // if there are multiple IPs, use the first in chain IPs := strings.Split(fwdH...
// Copyright 2020 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 package admapi // Endpoints for creating and getting Distributed key shares. import ( "encoding/base64" "fmt" "net/http" "time" "github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/address" dkg_pkg "github.com/iotaledger/wasp/pac...
package domain import ( "fmt" "github.com/tokopedia/tdk/go/app/resource" ) type Order struct { OrderID int ProductID int Quantity int Invoice string } type OrderDomain struct { resource OrderResourceItf } func InitOrderDomain(rsc OrderResourceItf) OrderDomain { return OrderDomain{ resource: rsc, } ...
package models import ( "testing" "golang.org/x/crypto/nacl/secretbox" ) var userTokenKey = []byte(`I3w8GGTsb9R3SKCvRzUd4aNasYIhX2IC`) func TestUISession_EncryptandSetUserToken(t *testing.T) { uis := UISession{} var key [32]byte copy(key[:], userTokenKey) if err := uis.EncryptandSetUserToken([]byte(`asdf`), k...
package protocol import ( "bytes" "github.com/giskook/mdas_client/base" ) type RestartPacket struct { Tid uint64 Serial uint16 } func (p *RestartPacket) Serialize() []byte { var writer bytes.Buffer WriteHeader(&writer, 0, PROTOCOL_REP_RESTART, p.Tid, p.Serial) base.WriteDWord(&writer, 1) base.WriteLengt...
package subscription import ( "fmt" ) // ErrSubscriptionNotFound occurs when subscription cannot be found. type ErrSubscriptionNotFound struct { ID ID } func (e ErrSubscriptionNotFound) Error() string { return fmt.Sprintf("Subscription %q not found.", e.ID) } // ErrSubscriptionAlreadyExists occurs when subscript...
package handlers import ( "testing" "time" "github.com/stretchr/testify/assert" "github.com/authelia/authelia/v4/internal/configuration/schema" ) func TestAuthzBuilder_WithConfig(t *testing.T) { builder := NewAuthzBuilder() builder.WithConfig(&schema.Configuration{ AuthenticationBackend: schema.Authenticat...
package cookie import ( "net/http" "net/http/cookiejar" "net/http/httptest" "net/url" "testing" ) type test struct { A string B int } func TestCookie(t *testing.T) { testFunc := func(w http.ResponseWriter, r *http.Request) { switch r.Method { case "GET": // set struct c := Ini...
// 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 mysql import ( "database/sql" "github.com/Tanibox/tania-core/src/assets/repository" "github.com/Tanibox/tania-core/src/assets/storage" ) type ReservoirReadRepositoryMysql struct { DB *sql.DB } func NewReservoirReadRepositoryMysql(db *sql.DB) repository.ReservoirReadRepository { return &ReservoirReadRep...
package main import ( "bufio" "fmt" "github.com/kr/pty" "io" "log" "os" "os/exec" "regexp" "strings" "time" ) type Deployer struct { config *PluginConfig runningJob *DeployJob } type DeployJob struct { process *os.Process params *DeployParams quit chan bool kill chan bool killing bool } ...
package sessions import ( "encoding/json" "errors" "time" "github.com/go-jose/go-jose/v3/jwt" "github.com/google/uuid" ) // ErrMissingID is the error for a session state that has no ID set. var ErrMissingID = errors.New("invalid session: missing id") // timeNow is time.Now but pulled out as a variable for test...
package drop import ( "fmt" "log" "time" "github.com/boltdb/bolt" "github.com/fxnn/deadbox/config" "github.com/fxnn/deadbox/daemon" "github.com/fxnn/deadbox/model" "github.com/fxnn/deadbox/rest" ) type Daemonized interface { model.Drop daemon.Daemon } // facade contains the implementation of model.Drop. /...
package cmds import ( "os" "testing" "github.com/BaritoLog/go-boilerplate/slicekit" . "github.com/BaritoLog/go-boilerplate/testkit" log "github.com/sirupsen/logrus" ) func init() { log.SetLevel(log.ErrorLevel) } func TestGetKafkaBrokers(t *testing.T) { FatalIf(t, !slicekit.StringSliceEqual(configKafkaBrokers...
package key import "github.com/giantswarm/microerror" var wrongTypeError = &microerror.Error{ Kind: "wrongTypeError", } // IsWrongTypeError asserts wrongTypeError. func IsWrongTypeError(err error) bool { return microerror.Cause(err) == wrongTypeError } var malformedCloudConfigKeyError = &microerror.Error{ Kind: ...
package main import ( "fmt" "time" ) func increment(ch chan bool, x *int) { ch <- true *x++ <-ch } func main() { pipline := make(chan bool, 1) num := 0 for i := 0; i < 1000; i++ { go increment(pipline, &num) } time.Sleep(time.Second) fmt.Println("num 的值 : ", num) }
// [_命令行参数_](http://en.wikipedia.org/wiki/Command-line_interface#Arguments) // 是指定程序运行参数的一个常见方式。例如,`go run hello.go`, // 程序 `go` 使用了 `run` 和 `hello.go` 两个参数。 package main import "os" import "fmt" func main() { // `os.Args` 提供原始命令行参数访问功能。注意,切片中 // 的第一个参数是该程序的路径,并且 `os.Args[1:]`保存 // 所有程序的的参数。 argsWithProg := os....
package dao import "github.com/stretchr/testify/mock" import _ "github.com/lib/pq" type MockSession struct { mock.Mock } func (_m *MockSession) LoadAgent(id string) (*Agent, error) { ret := _m.Called(id) var r0 *Agent if rf, ok := ret.Get(0).(func(string) *Agent); ok { r0 = rf(id) } else { if ret.Get(0) !...
package main import ( "fmt" "./recentservers" "./servers" ) func main() { servers, err := servers.LoadServers("config/servers.json") if err != nil { panic(err) } err = recentservers.SetConfigFile("config/recent_servers.json") if err != nil { panic(err) } recentServer, err := recentservers.GetRecentSe...
package workflow import ( "time" "k8s.io/client-go/rest" clientcmdapi "k8s.io/client-go/tools/clientcmd/api" ) type ClientConfig struct { // Host must be a host string, a host:port pair, or a URL to the base of the apiserver. // If a URL is given then the (optional) Path of that URL represents a prefix that mus...
package universal_multizone import ( "fmt" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/onsi/gomega/types" "github.com/kumahq/kuma/pkg/config/core" . "github.com/kumahq/kuma/test/e2e/trafficroute/testutil" . "github.com/kumahq/kuma/test/framework" ) func KumaMultizone() { var meshMTLSOn...
package main import "fmt" type produto struct { nome string preco float64 desconto float64 } // Método: função como receiver func (p produto) precoComDesconto() float64 { return p.preco * (1 - p.desconto) } func main() { var produto1 produto produto1 = produto{ nome: "lápis", preco: 0.5, ...
package main import ( "fmt" "os" "github.com/giantswarm/conair/btrfs" ) var cmdCommit = &Command{ Name: "commit", Description: "Commit a container", Summary: "Commit a container", Run: runCommit, } func runCommit(args []string) (exit int) { if len(args) < 1 { fmt.Fprintln(os.Stderr, "Co...
package envoyconfig import ( envoy_config_core_v3 "github.com/envoyproxy/go-control-plane/envoy/config/core/v3" envoy_config_listener_v3 "github.com/envoyproxy/go-control-plane/envoy/config/listener/v3" envoy_extensions_filters_http_ext_authz_v3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/...
package renter import ( "strings" "testing" "gitlab.com/NebulousLabs/Sia/modules" "gitlab.com/NebulousLabs/Sia/types" ) // TestPDBRGouging checks that `checkPDBRGouging` is correctly detecting price // gouging from a host. func TestPDBRGouging(t *testing.T) { t.Parallel() // allowance contains only the fields...
// Package sessions contains gorilla sessions cookies. // // MIT License // // Copyright (c) 2016 Angel Del Castillo // // 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,...
package main import ( "fmt" "github.com/codegangsta/negroni" "net/http" "os" ) func main() { port := os.Getenv("PORT") if len(port) == 0 { port = "8081" } mux := http.NewServeMux() mux.HandleFunc("/", hello) //启动一个httpsEREVER 内注入对应的 // http.Handler // gin.HANLER // behi./roughen // echo // 自我诶你对serv...
package v1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "github.com/operator-framework/api/pkg/operators" ) const ( Group = "packages." + operators.GroupName Version = "v1" PackageManifestKin...
package dict import ( "bytes" "unicode/utf8" ) func isAnsiAsUtf8(buf []byte) bool { offset := 0 for offset < len(buf) { r, size := utf8.DecodeRune(buf[offset:]) if r == utf8.RuneError { return false } offset += size } return true } func ReadLines(filename String) []String { // file, err := os.Ope...
package binance import ( "context" "net/http" ) // ListSavingsFlexibleProductsService https://binance-docs.github.io/apidocs/spot/en/#get-flexible-product-list-user_data type ListSavingsFlexibleProductsService struct { c *Client status string featured string current int64 size int64 } // Status ...
package sample_data import "github.com/psinthorn/gostore/pb" // return new storage object func NewStorage() *pb.Storage { storage := &pb.Storage{ Driver: randomStorage(), Memory: &pb.Memory{ Value: uint64(randomInt(2, 6)), Unit: pb.Memory_GIGABYTE, }, } return storage }
package client import ( "github.com/liut/staffio/pkg/common" ) // Staff is a retrieved employee struct. type Staff struct { UID string `json:"uid" form:"uid"` // 登录名 CommonName string `json:"cn,omitempty" form:"cn"` // 全名 GivenName string `j...
package main import ( "log" "net/http" "os" "time" "meli/pkg/handler" "github.com/patrickmn/go-cache" ) func main() { handler.GoDotEnv() infoLog := log.New(os.Stdout, "INFO\t", log.Ldate|log.Ltime) c := cache.New(5*time.Minute, 10*time.Minute) infoLog.Printf("Starting server on %s", os.Getenv("PORT")) ht...
package reverse import ( "testing" ) func TestString(t *testing.T) { message, err := String([]byte("Hello World!")) if string(message) != "!dlroW olleH" || err != nil { t.Fatalf(`String([]byte("Hello World!")) = %q, %v, want "!dlroW olleH", error`, message, err) } } func BenchmarkString(b *testing.B) { for i...
package main import ( "time" toxiproxy "github.com/Shopify/toxiproxy/client" "github.com/sirupsen/logrus" ) var log = logrus.New() func init() { log.SetLevel(logrus.DebugLevel) } type Toxic struct { client *toxiproxy.Client proxy *toxiproxy.Proxy } func (toxic *Toxic) Clean() { log.Debugln("Cleaning Toxic...
package main import ( "context" "fmt" "github.com/google/go-github/github" "golang.org/x/oauth2" "gopkg.in/alecthomas/kingpin.v2" "sync" "time" ) var ( owner = kingpin.Arg("owner", "GitHub owner.").Required().String() repo = kingpin.Arg("repo", "GitHub repository").Re...
package routers import ( "ibgamemanage/controllers" "github.com/astaxie/beego" ) func init() { //查看博客详细信息 beego.Router("/view/:PlayerId([0-9]+)", &controllers.ViewController{}) beego.Router("/", &controllers.IndexController{}) beego.Router("/login", &controllers.LoginController{}) //新建博客博文 beego.Router("/ne...
package main var isVisit map[string]int // 保留已经得到的结果,该结构相当于一个备忘录 // 记忆化搜索函数调用者 func minDistance(word1 string, word2 string) int { /* 1. 进行一些预处理 */ isVisit = make(map[string]int) /* 2. 开始调用记忆化搜索函数,返回记忆化搜索结果 */ return minDistanceExec(word1, word2) } // 记忆化搜索函数 func minDistanceExec(word1 string, word2 string) i...
package main import "testing" func TestP1(t *testing.T) { cases := []struct { in int out int }{ {10, 23}, {1000, 233168}, } for _, c := range cases { v := sum(c.in) if v != c.out { t.Errorf("P1: %v\tExpected: %v", v, c.out) } } }
package test import ( "encoding/json" "io/ioutil" "net/http" "testing" "github.com/stretchr/testify/assert" ) func GetResponseBody(t *testing.T, response *http.Response) string { b, err := ioutil.ReadAll(response.Body) if err != nil { t.Fatal(err) } return string(b) } func AssertJSONMatches(t *testing.T...
package log_client import ( "github.com/kataras/iris/context" "gocherry-api-gateway/admin/services" "time" ) var logFileName string func init() { x := time.Date(2017, 02, 27, 17, 30, 20, 20, time.Local) logDir := services.GetAppConfig().Common.LogDir logFileName = logDir + "proxy_log_" + x.Format("2006-01-02")...
/** * @Author : henry * @Data: 2020-08-13 13:22 * @Note: **/ package models import ( "encoding/json" "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mssql" "github.com/vouchersAPI/app" ) var MsDB *gorm.DB var err error type VoucherDB struct { Type string `json:"type"` Ip string `j...
package types type Type int const ( TYPE_INT Type = 110 TYPE_STRING Type = 190 TYPE_MAP Type = 210 )
package git import ( "runtime" "sort" "testing" "time" ) func TestRefModification(t *testing.T) { t.Parallel() repo := createTestRepo(t) defer cleanupTestRepo(t, repo) commitId, treeId := seedTestRepo(t, repo) _, err := repo.References.Create("refs/tags/tree", treeId, true, "testTreeTag") checkFatal(t, er...
func maximumProduct(nums []int) int { m1,m2,m3:=math.MinInt32,math.MinInt32,math.MinInt32 a1,a2:=math.MaxInt32,math.MaxInt32 for _,v:=range nums{ if v>m1{ m1,m2,m3=v,m1,m2 }else if v>m2{ m2,m3=v,m2 }else if v>m3{ m3=v } if v<a1{ ...
package zenrpc_mw import ( "context" "encoding/json" "time" "github.com/go-kit/kit/log" "github.com/semrush/zenrpc" ) func Logger(logger log.Logger) zenrpc.MiddlewareFunc { return func(invoke zenrpc.InvokeFunc) zenrpc.InvokeFunc { return func(ctx context.Context, method string, params json.RawMessage) zenrpc...
//go:generate mockgen -destination=./mock/output_mock.go github.com/nomkhonwaan/myblog/pkg/log Outputer package log import ( "log" "os" ) // Outputer is a compatible interface for logging with format type Outputer interface { // Log with format to the output Printf(format string, args ...interface{}) } // Defau...
// vi:nu:et:sts=4 ts=4 sw=4 // See License.txt in main repository directory // CSV File Adjustment program // This program provides a convenient way to add a field // with a constant value or delete one or more fields // from a csv. // Generated: Mon May 20, 2019 21:42 package main import ( "encoding/csv" "flag" ...
/* Description In the game show "The Price is Right", a number of players (typically 4) compete to get on stage by guessing the price of an item. The winner is the person whose guess is the closest one not exceeding the actual price. Because of the popularity of the one-person game show "Who Wants to be a Millionaire...
// Copyright © 2016 Prateek Malhotra (someone1@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 rights // to use, copy, m...
package testing import ( "context" "io" "io/ioutil" "net/http" "strings" "time" "github.com/devspace-cloud/devspace/pkg/devspace/config/generated" "github.com/devspace-cloud/devspace/pkg/devspace/kubectl" "github.com/devspace-cloud/devspace/pkg/devspace/kubectl/portforward" "github.com/devspace-cloud/devspa...
package main import ( "fmt" piscine "./func" ) func main() { // n := 20 // piscine.PointOne(&n) // fmt.Println(n) // a := 20 // b := &a // n := &b // piscine.UltimatePointOne(&n) // fmt.Println(a) // a := 13 // b := 2 // var div int // var mod int // piscine.DivMod(a, b, &div, &mod) // ...
// Copyright 2016 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 runner import ( "context" "github.com/jcftang/gitbuilder-go/buildroot" log "github.com/sirupsen/logrus" ) // RunAll Executes the repo setup, build/test and report func RunAll(ctx context.Context, b buildroot.BuildRoot) error { for _, branch := range b.Branches() { _nextrev, err := b.NextRev(branch) i...
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package ssh import ( "bytes" "context" "fmt" "io" "os" "github.com/Azure/aks-engine/pkg/api" "github.com/pkg/errors" ) // CopyToRemote copies a file to a remote host. // // Context ctx is only enforced during the ...
package main import "log" type Memento struct { state string } func(m *Memento)SetState(s string){ m.state = s } func(m *Memento)GetState()string{ return m.state } type Originator struct { state string } func(o *Originator)SetState(s string){ o.state = s } func (o *Originator)GetState()string{ return o.sta...
package cron import ( "context" "testing" "time" "github.com/stretchr/testify/assert" ) func TestCron(t *testing.T) { called := make(chan bool) c, err := Start(context.Background(), []Job{{ Name: "testing", Run: func(ctx context.Context) { called <- true }, Schedule: ConstantInterval{Interval: t...
package loaders_test import ( "context" "testing" "time" "github.com/syncromatics/kafmesh/internal/graph/loaders" "github.com/syncromatics/kafmesh/internal/graph/model" gomock "github.com/golang/mock/gomock" "github.com/pkg/errors" "gotest.tools/assert" ) func Test_Topics_Inputs(t *testing.T) { ctrl := gom...
package pruning import ( "context" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/tools/cache" "github.com/operator-framework/api/pkg/operators/v1alpha1" "github.com/operator-framework/operator-lifecycle-manager/pkg/api/client/...
package flex import ( "context" "os" "time" gomock "github.com/golang/mock/gomock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/watch" fakekubeclientset "k8s.io/client-go/kubernetes/fake" testcore "k8s.io/...
package tools import ( "github.com/PagerDuty/go-pagerduty" "reflect" "testing" ) func TestGetMappedEscalationPolicies(t *testing.T) { var EscalationPolicies []pagerduty.EscalationPolicy testPolicy := pagerduty.EscalationPolicy{} testPolicy.Name = "Test Policy" testPolicy.NumLoops = 2 testPolicy.ID = "Test1" ...
package phpGo import ( "testing" ) type tmpStruct struct { A string B int } func TestEmpty(t *testing.T) { if !Empty(nil) { t.Error() } if !Empty("") { t.Error() } if !Empty("0") { t.Error() } if !Empty(false) { t.Error() } tmpArr := [2]interface{}{0, 1} if !Empty(tmpArr, 0) || Empty(tmpArr,...