text
stringlengths
11
4.05M
package herd import ( "fmt" "io" "net/http" net_url "net/url" "strings" "time" "github.com/Cloud-Foundations/Dominator/lib/constants" "github.com/Cloud-Foundations/Dominator/lib/format" "github.com/Cloud-Foundations/Dominator/lib/html" "github.com/Cloud-Foundations/Dominator/lib/json" "github.com/Cloud-Fou...
package postgres import ( "context" "fmt" "github.com/go-pg/pg/v9" _ "github.com/lib/pq" ) type dbLogger struct{} func (d dbLogger) BeforeQuery(c context.Context, q *pg.QueryEvent) (context.Context, error) { return c, nil } func (d dbLogger) AfterQuery(c context.Context, q *pg.QueryEvent) error { fmt.Println(...
package calc import "testing" func TestProd(t *testing.T) { exp := 120.0 act := Prod([]float64{1.0, 2.0, 3.0, 4.0, 5.0}) if !Near(exp, act) { t.Error("Expected", exp, "got", act) } }
package main import "fmt" type Vertex struct { X int Y int } type user struct { name string age int hight float32 } type event struct { day, month, year int } func main() { v := Vertex{1, 2} v.X = 4 fmt.Println(v.X) // user fmt.Println(user{"leo", 23, 1.77}) // event e := event{18, 6, 1996} e.day =...
package methods import ( "github.com/rkuris/journey/database" "github.com/rkuris/journey/date" "github.com/rkuris/journey/structure" ) func SaveUser(u *structure.User, hashedPassword string, createdBy int64) error { userId, err := database.InsertUser(u.Name, u.Slug, hashedPassword, u.Email, u.Image, u.Cover, date...
package bot import ( "fmt" "github.com/darkliquid/go-ircevent" "github.com/darkliquid/leader1/debug" "github.com/darkliquid/leader1/utils" "sort" "strings" "time" ) func (bot *Bot) RunBuiltinCommands(event *irc.Event) { args := strings.Split(strings.TrimSpace(event.Message()), " ") command := args[0] // Bi...
package models import ( "github.com/jinzhu/gorm" ) type Response struct { gorm.Model Code int `json:"code,omitempty"` Message string `json:"message,omitempty"` }
package task1 import ( "math" "testing" ) func TestSqrt(t *testing.T) { const delta = 0.5 testCases := []struct { name string inputValue, expectedValue float64 }{ { name: "two", inputValue: 2, expectedValue: 1.4, }, { name: "four", inputValue: ...
package main import ( "flag" "fmt" "os" "time" ) var debug bool var name string var wait time.Duration func main() { //name := flag.String("name", "", "The name to say hello to") if name == "" { fmt.Println("must add name to use this tool!") flag.Usage() os.Exit(1) } if debug { fmt.Printf("Going to...
package main import ( "testing" "github.com/stretchr/testify/assert" //"github.com/go-test/deep" "reflect" //"fmt" ) //-------------------------------- Created Structs --------------- func TestCityType(t *testing.T) { // Set up City1 := City{"A City Road", "A Exit...
package k8s import ( "github.com/gorilla/mux" "net/http" "fmt" ) func Router() *mux.Router { r := mux.NewRouter() r.HandleFunc("/home", home).Methods("Get") return r } func home(write http.ResponseWriter, request *http.Request) { fmt.Fprintln(write,"Hello you have request progress") }
func partition(s string) [][]string { res := [][]string{} out := []string{} var dfs func(int) dfs = func(start int){ if start==len(s){ res = append(res, c(out)) return } for i:=start;i<len(s);i++{ if valid(s,start,i){ out = appe...
package lb_client import ( "crypto/tls" "dynamicpath/lib/MonitorInfo" "dynamicpath/lib/monitor_api" "dynamicpath/src/load_balancer/lb_context" "dynamicpath/src/load_balancer/logger" "golang.org/x/net/http2" "net/http" ) func StartMonitor(upf *lb_context.UpfContext) { client := &http.Client{} client.Transport...
package clair import ( "encoding/json" "fmt" "net/http" "github.com/coreos/clair/api/v1" "github.com/docker/distribution" "github.com/docker/distribution/manifest/schema1" "github.com/docker/distribution/manifest/schema2" "github.com/docker/docker/reference" ) //Analyze return Clair Image analysis func Analy...
package camt import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document08600101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:camt.086.001.01 Document"` Message *BankServicesBillingStatementV01 `xml:"BkSvcsBllgStmt"` } func (d *Docume...
package main import "fmt" func isValid(s string) bool { if len(s) == 0 { return true } if len(s) == 1 { return false } l := len(s) b := make([]byte, l) next := 0 for _, c := range s { switch c { case '(', '[', '{': b[next] = byte(c) next++ case ')': if next == 0 { return false } i...
package aes import ( "crypto/aes" "crypto/cipher" "crypto/rand" "fmt" "io" "io/ioutil" "log" "os" ) func EncryptTxt(args []string) { if len(args) == 0 { log.Fatal("No arguments provided. Please see small-aes -h") } key := []byte(args[1]) if len(key) != 32 && len(key) != 24 && len(key) != 16 { log.Fa...
package jarvisbot import ( "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" "strings" "github.com/tucnak/telebot" ) const googleSearchAPI = "https://www.googleapis.com/customsearch/v1?key=%s&cx=%s&q=" func (j *JarvisBot) GoogleSearch(msg *message) { if len(msg.Args) == 0 { so := &telebot.SendOptions...
package basic import "fmt" type Human interface { Say() string } type Man struct { } func (m *Man) Say() string { return "man" } func IsNil(h interface{}) bool { return h == nil } /* func f2() { var c Man var d Human //接口变量和实现这个接口类型的变量, 属于两个不同的类型, 不能比较 fmt.Println( c == d) } */ func interfaceNil() { /* ...
/* The Computer Language Benchmarks Game * http://shootout.alioth.debian.org/ * * contributed by Krzysztof Kowalczyk */ package main import ( "bytes" _ "fmt" "io/ioutil" "log" "os" "time" ) var bigbuf []byte var comptbl = [256]uint8{} func build_comptbl() { l1 := []byte("UACBDKRWSN") l2 := []byte("ATGV...
package main import ( "os" "fmt" "io/ioutil" "os/exec" "path" "strings" "io" "bufio" ) const ExtStr string =""; var ExtMap map[string]interface{}; func init(){ GetExtList() } func GetExtList(){ ExtMap=make(map[string] interface{}) if(ExtStr !=""){ list:=strings.Split(ExtStr,","); for _,value:=ra...
package pulsar import ( "context" "io/ioutil" "time" "github.com/apache/pulsar-client-go/pulsar" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/batchcorp/collector-schemas/build/go/protos/events" "github.com/batchcorp/plumber-schemas/b...
package p2p const Version = "0.3.3" // fuzz conn
root: . tmp_path: ./tmp build_name: runner-build build_log: runner-build-errors.log valid_ext: .go, .tpl, .tmpl, .html no_rebuild_ext: .tpl, .tmpl, .html ignored: assets, tmp, configs, docker, k8s, node_modules, migrations, public, views, web build_delay: ...
package cryptutil import ( "encoding/base64" "reflect" "testing" "github.com/stretchr/testify/assert" ) func TestEncodeAndDecodeAccessToken(t *testing.T) { plaintext := []byte("my plain text value") key := NewKey() c, err := NewAEADCipher(key) if err != nil { t.Fatalf("unexpected err: %v", err) } ciphe...
package codex import ( "github.com/pelletier/go-toml" "github.com/pkg/errors" log "github.com/sirupsen/logrus" "io/ioutil" "os" "path/filepath" ) const ConfigFileName = "codex.toml" type Config struct { Upload UploadConfig `toml:"upload"` Kernel KernelConfig `toml:"kernel"` configFile string } type Upload...
package idbenchmark_test import ( "database/sql" "log" "os" "testing" _ "github.com/go-sql-driver/mysql" ) const ( m1 = "INSERT INTO m1 VALUES (NULL)" m2 = "REPLACE INTO m2 VALUES (NULL)" m3 = "UPDATE m3 SET id=LAST_INSERT_ID(id+1)" m4 = "UPDATE m3 SET id=LAST_INSERT_ID(id+1) LIMIT 1" i1 = "INSERT INTO i1 ...
package model // User is model of user type User struct { ID string `json:"id"` Username string `json:"username"` Fullname string `json:"fullname"` Birthday string `json:"birthday"` Email string `json:"email"` Password string `json:"password"` } // Diary is model of diary type Diary struct { ID s...
package cloud import ( "sync" "time" "github.com/devspace-cloud/devspace/pkg/devspace/cloud/config/versions/latest" "github.com/pkg/errors" ) var cacheMutex sync.Mutex // CacheSpace caches a given space and service account func (p *provider) CacheSpace(space *latest.Space, serviceAccount *latest.ServiceAccount...
package oauth2 // ReferenceTokenRepository Stores reference tokens type ReferenceTokenRepository interface { AddToken(token ReferenceToken) error GetToken(tokenID string) (ReferenceToken, bool, error) // RemoveToken(tokenID string) error // RemoveAllTokensForClient(clientID string) error }
/* Package users provides the ability to retrieve and manage users through the Resell v2 API. Example of getting a single user referenced by its id user, _, err := users.Get(context, resellClient, userID) if err != nil { log.Fatal(err) } fmt.Println(user) Example of getting all users allUsers, _, err ...
package kasalink import ( "bytes" "encoding/binary" ) //Kasa uses something called auto key ciphering for communicating with their devices. It's trivial, but does make //communications non-human readable. func encrypt(plaintext string) []byte { var ( n = len(plaintext) buf = n...
package endpoint import ( "context" "github.com/go-kit/kit/endpoint" "github.com/rwool/saas-interview-challenge1/pkg/service" ) // DocumentRequest contains a document to process. type DocumentRequest struct { service.DocumentRequest } // DocumentFrequencyReportResponse contains a DocumentFrequencyReport and an ...
package infrastructure import ( supportThumbnailDomain "../domain" "encoding/json" "net/http" ) func HandleController(supportThumbnailRepository supportThumbnailDomain.SupportThumbnailRepository) func(w http.ResponseWriter, _ *http.Request) { return func(w http.ResponseWriter, _ *http.Request) { results := supp...
package mongodb import "time" const createIndexTimeout = time.Second * 5
package webhooks import ( "context" "errors" "fmt" "os" "testing" "time" "github.com/kubevirt/hyperconverged-cluster-operator/pkg/controller/commonTestUtils" "github.com/kubevirt/hyperconverged-cluster-operator/pkg/util" "github.com/kubevirt/hyperconverged-cluster-operator/pkg/controller/common" networkad...
package kafka import ( "github.com/Shopify/sarama" "sync" ) type Consumer struct { addr []string WG sync.WaitGroup Topic string PartitionList []int32 Consumer sarama.Consumer } func NewKafkaConsumer(addr []string, topic string) *Consumer { p := Consumer{} p.Topic = topic p....
/* You are given an array of dates in the format Dec 11 and a month in the format Dec as arguments. Each date represent a video that was uploaded on that day. Return the number of uploads for a given month. Examples uploadCount(["Sept 22", "Sept 21", "Oct 15"], "Sept") ➞ 2 uploadCount(["Sept 22", "Sept 21", "Oct 15...
package main import ( "gorm.io/gorm" "io" ) type Invocation string func Run(input string, stdout io.Writer, stderr io.Writer, db *gorm.DB, s *Slack) (err error) { _, context, err := Parse(input, stdout, stderr) if err != nil { if _, err = io.WriteString(stderr, err.Error()+"\n"); err != nil { return err }...
package gcppubsub import ( "context" "sync" "time" "cloud.google.com/go/pubsub" "github.com/pkg/errors" "github.com/batchcorp/plumber-schemas/build/go/protos/opts" "github.com/batchcorp/plumber-schemas/build/go/protos/records" "github.com/batchcorp/plumber/backends/gcppubsub/types" "github.com/batchcorp/pl...
package cli import "strconv" type Flag struct { args []string } // Check if a flag exists in the argument list func (f Flag) Bool(keys ...string) bool { for _, elem := range f.args { for _, key := range keys { if elem == key { return true } } } return false } // Extract a list of parameters with t...
func missingNumber(nums []int) int { for idx := 0; idx < len(nums); { num := nums[idx] if num >= len(nums){ idx += 1 continue } if num == idx{ idx += 1 continue } nums[idx], nums[num] = nums[num], nums[idx] } for...
package consensus import ( "encoding/hex" "fmt" "sync" "github.com/Secured-Finance/dione/config" types2 "github.com/Secured-Finance/dione/consensus/types" "github.com/Secured-Finance/dione/blockchain/pool" "github.com/asaskevich/EventBus" "github.com/sirupsen/logrus" "github.com/Secured-Finance/dione/bl...
package nettests import ( "io/ioutil" "path" "testing" ooni "github.com/ooni/probe-cli" "github.com/ooni/probe-cli/internal/database" "github.com/ooni/probe-cli/utils/shutil" ) func newTestingContext(t *testing.T) *ooni.Context { homePath, err := ioutil.TempDir("", "ooniprobetests") if err != nil { t.Fatal...
package asserts import ( "regexp" "sync" "github.com/prometheus/client_golang/prometheus" ) var ( Asserts sync.Map assertsmetrics = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "mqops_operation_status", Help: "Response status", }, []string{"status", "operation", "code"}, ) succes...
package megasena import ( "fmt" "github.com/fabioxgn/go-bot" . "github.com/smartystreets/goconvey/convey" "net/http" "net/http/httptest" "regexp" "testing" ) const ( retornoJSON = `{"concurso":{ "numero":"1636", "data":"17\/09\/2014", "cidade":"OSASCO-SP", "local":"Caminh\u00e3o da Sorte", ...
// Copyright 2021 The searKing Author. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ffmpeg import "encoding/json" // See also https://github.com/FFmpeg/FFmpeg/blob/master/doc/ffprobe.xsd type FFprobeType struct { ProgramVersion...
package list import ( "unsafe" "github.com/Beyond-simplechain/foundation/allocator" "github.com/Beyond-simplechain/foundation/offsetptr" ) // template type List(Value,Allocator) type Value = int var Allocator allocator.MemoryManager = nil type Node struct { next offsetptr.Pointer `*Node` prev offsetptr.Poin...
// Copyright 2015 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 handlers import "log" import "net/http" import "data" type Products struct { l *log.Logger } func NewProducts(l*log.Logger) *Products { return &Products{l} } func (p*Products) ServeHTTP(rw http.ResponseWriter, r *http.Request){ if r.Method == http.MethodGet { p.getProducts(rw,r) return } rw.WriteHe...
package weather_domain import ( "encoding/json" "net/http" ) type WeatherErrorInterface interface { Status() int Message() string } type WeatherError struct { Code int `json:"code"` ErrorMessage string `json:"error"` } func (w *WeatherError) Status() int { return w.Code } func (w *We...
package main import ( "bufio" "io" "log" "net" ) func main() { listen, err := net.Listen("tcp", ":9080") if err != nil { log.Fatalf("listen error: %v\n", err) } log.Println("start tcp listen") for { conn, err := listen.Accept() if err != nil { log.Printf("listener.Accept(\"%s\") error(%v)", list...
package _509_Fibonacci_Number import "testing" func TestFib(t *testing.T) { if ret := fib(2); ret != 1 { t.Errorf("wrong ret with %d", ret) } if ret := fib(3); ret != 2 { t.Errorf("wrong ret with %d", ret) } if ret := fib(4); ret != 3 { t.Errorf("wrong ret with %d", ret) } }
package main import ( "flag" "fmt" "log" "net/http" "path/filepath" "github.com/lizebang/file-transfer/handle" "github.com/lizebang/file-transfer/ip" "github.com/lizebang/file-transfer/qr" ) var ( dirpath string filename string host string port string ) func init() { host = ip.IP() flag.Usage...
package compose import ( "fmt" "time" "github.com/kudrykv/latex-yearly-planner/app/components/calendar" "github.com/kudrykv/latex-yearly-planner/app/components/page" "github.com/kudrykv/latex-yearly-planner/app/config" ) func Weekly(cfg config.Config, tpls []string) (page.Modules, error) { if len(tpls) != 1 { ...
package main import ( "fmt" "testing" ) func TestModuleFuel(t *testing.T) { tests := []struct { mass int required int }{ {14, 2}, {1969, 966}, {100756, 50346}, } for _, tt := range tests { t.Run(fmt.Sprintf("mass %d", tt.mass), func(t *testing.T) { required := moduleFuel(tt.mass) if requir...
package integration_test import ( "github.com/cloudfoundry/libbuildpack/cutlass" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("deploy includes headers", func() { var app *cutlass.App AfterEach(func() { if app != nil { app.Destroy() } app = nil }) Context("with a public fo...
package main import "errors" var allTodos = make(map[int]*Todo) var globalTodoId = 0 func addTodo(todo *Todo) { defer func() { globalTodoId++ }() todo.Id = globalTodoId allTodos[todo.Id] = todo } func getTodos() []Todo { result := make([]Todo, 0) for _, todo := range allTodos { result = append(result, *todo...
package response type BaseResponse struct { Success bool `json:"success"` Code int `json:"code"` Msg string `json:"msg"` }
package pingpong import ( "coms4113/hw5/pkg/base" ) func IsFinal(state_ *base.State) bool { for _, node := range state_.Nodes() { client, ok := node.(*Client) if !ok { continue } count := client.Attribute().(int) return count == 5 } return false }
package run import ( "os" "testing" "github.com/stretchr/testify/assert" "core" ) func init() { if err := os.Chdir("src/run/test_data"); err != nil { panic(err) } } func TestSequential(t *testing.T) { graph, labels1, labels2 := makeGraph() code := Sequential(graph, labels1, nil, true) assert.Equal(t, 0,...
package main import ( "errors" "os" "strconv" "github.com/doylecnn/contribution_bot/chatbots" "github.com/rs/zerolog" "github.com/rs/zerolog/log" ) type env struct { Port string BotToken string BotAdminID int AppID string Domain string ProjectID string } func main() { zerolog.SetGloba...
// Copyright 2016 Etix Labs // // 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 wr...
package rudp import ( "net" "sync" "sync/atomic" "time" ) // A Conn is a connection to a client or server. // All Conn's methods are safe for concurrent use. type Conn struct { udpConn udpConn id PeerID pkts chan Pkt errs chan error timeout *time.Timer ping *time.Ticker closing uint32 closed chan ...
package v1 import ( "context" "database/sql" "github.com/golang/protobuf/ptypes" v1 "github.com/laughtt/loginService/api/proto/v1" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) const ( apiVersion = "v1" ) //AuthServiceServer connection type AuthServiceServer struct { db *sql.DB } //NewAu...
package main const difficultyEasy int = 1 const difficultyImpossible int = 2 const clientPlayer int = 1 const cpuPlayer int = 2 const initialGameState string = "[[0,0,0],[0,0,0],[0,0,0]]" const cpuTurnTimeLimit float64 = 10 // seconds const clientWin int = 1 const cpuWin int = 2 const tieGame int = 3 const thread...
package main /* #include <errno.h> #include <pwd.h> #include <security/pam_appl.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> char* string_from_argv(int i, char** argv) { return strdup(argv[i]); } char* get_user(pam_handle_t* pamh) { if (!pamh) return NULL; int pam_err ...
package main import "fmt" func main() { nums := []int{1, 2, 3, 3, 3, 3, 5} fmt.Println(removeDuplicates(nums)) } func removeDuplicates(nums []int) int { n := len(nums) if n < 2 { return n } left, right := 1, 1 for right < n { if nums[right] != nums[right-1] { nums[left] = nums[right] left++ } ...
package tango import ( "tango" "fmt" ) func Example200OK() { fmt.Println(tango.FetchMeaning("200")) // Output: OK } func Example500InternalServerError() { fmt.Println(tango.FetchMeaning("500")) // Output: Internal Server Error } func Example000Unknown() { fmt.Println(tango.FetchMeaning("000")) // Output...
package avformat import ( "bytes" "io/ioutil" "os" "path/filepath" "reflect" "testing" "github.com/imkira/go-libav/avutil" "github.com/shirou/gopsutil/process" ) func TestVersion(t *testing.T) { major, minor, micro := Version() if major < 57 || minor < 0 || micro < 0 { t.Fatalf("Invalid version") } } f...
/* * Copyright (C) 2020 The Android Open Source Project * * 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 app...
package x_os import ( "testing" "github.com/guoyao/gogo/x_testing" ) func TestIsExist(t *testing.T) { funcName := "IsExist" expected, result := true, IsExist("os_test.go") if result != expected { t.Error(x_testing.Error(funcName, result, expected)) } expected, result = false, IsExist("not_exist_file.go") ...
package main import ( "encoding/binary" "fmt" "net" ) // only needed below for sample processing func main() { fmt.Println("Launching Echo server...") // listen on all interfaces port 80 ln, _ := net.Listen("tcp", ":8080") // accept connection on port conn, _ := ln.Accept() for { buf := make([]byte, 10...
// Author: sheppard(ysf1026@gmail.com) 2014-03-12 package proto import ( ) type ReqAdd struct { A, B int }
package movie type ChildrenPrice struct { } func (c ChildrenPrice) GetPriceCode() int { return CHILDREN } func (c ChildrenPrice) GetCharge(daysRented int) float64 { result := 1.5 if daysRented > 3 { result += float64(daysRented-3) * 2 } return result } func (c ChildrenPrice) GetFrequentRenterPoints(daysRente...
package main import ( "encoding/json" "flag" "fmt" "io" "math/rand" "os" "time" "github.com/onsi/gomega" "github.com/golang/glog" "github.com/onsi/ginkgo" "github.com/spf13/cobra" "github.com/spf13/pflag" "k8s.io/apiserver/pkg/util/logs" "k8s.io/kubernetes/pkg/kubectl/cmd/templates" e2e "k8s.io/kuber...
package parse_test import ( "fmt" "os" "github.com/tmc/parse" ) func ExampleNewClient() { appID := os.Getenv("APPLICATION_ID") apiKey := os.Getenv("REST_API_KEY") _, err := parse.NewClient(appID, apiKey) fmt.Println(err) // output: <nil> }
package machine import ( "fmt" "math/rand" ) // Default values for rotor properties. const ( DefaultPosition = 0 DefaultStep = 1 DefaultCycle = 26 ) // Rotor represents a mechanical rotor used in xenigma. A rotor contains connections // used to make electric pathways and generate a path through the machi...
package persistence import ( "errors" "github.com/adamveld12/goadventure/game" uuid "github.com/satori/go.uuid" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" "strings" ) type playerServiceImpl struct { store *mgo.Collection } func (p playerServiceImpl) New(name string) (game.Player, error) { if name == "" || stri...
package testsuite import ( "context" "testing" "go.mercari.io/datastore" ) func namespacePutAndGet(ctx context.Context, t *testing.T, client datastore.Client) { defer func() { err := client.Close() if err != nil { t.Fatal(err) } }() type Data struct { Name string } key := client.IDKey("Test", 1,...
package storage import ( "fmt" "github.com/biezhi/gorm-paginator/pagination" md "github.com/ebikode/eLearning-core/model" ) // DBGradeStorage encapsulates DB Connection Model type DBGradeStorage struct { *MDatabase } // NewDBGradeStorage Initialize Grade Storage func NewDBGradeStorage(db *MDatabase) *DBGradeSto...
// Package gitconfig expose a few methods to interact with a git configuration package gitconfig import ( "fmt" "os/exec" "strings" ) // AddOrigin sets the remote origin func AddOrigin(main string) error { output, err := exec.Command("git", "remote", "add", "origin", main).Output() if err != nil && len(output) ...
// // Copyright (c) 2017, Stardog Union. <http://stardog.com> // // 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 b...
package broker import ( "fmt" "github.com/piotrpersona/saga/model" "github.com/go-redis/redis" ) type redisBroker struct { channel string client *redis.Client } func (rb redisBroker) Save(order model.Order) (orderID string, err error) { orderID = order.ID channelName := fmt.Sprintf("%s.%s", rb.channel, ord...
package roredis import ( "testing" "time" ) const testValsDuration = 20 * time.Second const testKey = "testKey" const testBogusKey = "bogusKey" const testVal1 = "abc123" const testKeyDB1 = "testKeyDB1" const testVal1DB1 = "abc123DB1" // A Redis instance is required for the tests here var testCfg = RedisCfg{ Host:...
package golang import ( "math" ) func angleClock(hour int, minutes int) float64 { anglePreHour := 30.0 hourAngleList := [12]float64{ 0, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330, } minutesBase0 := float64(minutes) * 6 hourBase0 := hourAngleList[hour%12] + minutesBase0/360*anglePreHour return...
package main import ( "encoding/json" "io/ioutil" "net/http" ) type RuterLine struct { Name string `json:"name"` } type SpotsLayout struct { Span float32 `json:"span"` ItemSpacing float32 `json:"itemSpacing"` } type RuterLineArray []RuterLine type SpotsRuterObject struct { Kind string `jso...
package main import ( "github.com/PuerkitoBio/goquery" "net/http" "log" "os" "strconv" "fmt" "strings" "io" "runtime" "time" ) func main() { fmt.Println("runtime on " + strconv.Itoa(runtime.NumCPU()) + " goroutine") runtime.GOMAXPROCS(runtime.NumCPU()) url := "http://taohuabt.cc/thread-1820205-1-index....
package openid import ( "errors" "net/http" "net/http/httptest" "testing" "github.com/dgrijalva/jwt-go" "github.com/stretchr/testify/mock" ) const idToken string = "IDTOKEN" func Test_authenticateUser_WhenGetIDTokenReturnsError_WhenErrorHandlerContinues(t *testing.T) { _, c := createConfiguration(t, errorHan...
package clients import ( "encoding/json" "errors" "fmt" "net/url" "path" "strconv" "time" "github.com/go-resty/resty" "github.com/hyperpilotio/go-utils/funcs" "github.com/hyperpilotio/workload-profiler/models" "github.com/op/go-logging" ) type SlowCookerClient struct{} type SlowCookerCalibrateResult stru...
package main func main() { } /* 根据URL判断 */
package main import ( "fmt" "io" "os" ) // 复制文件函数 // sourcePath:源文件的地址 // distPath:目的文件的地址 func copyFile(sourcePath, distPath string) { // 打开源文件 sourceFile, sourceErr := os.Open(sourcePath) if sourceErr != nil { fmt.Println("sourceErr = ", sourceErr) return } // 创建目的文件 distFile, distErr := os.Create(dis...
package main import ( "encoding/csv" "github.com/bogdanovich/dns_resolver" "math/rand" "os" "text/tabwriter" "time" ) //aw test import ( "fmt" "strings" ) func main() { var queryServer string = os.Args[1] var filename string = "DnsPing " + strings.Replace(queryServer, ".", "-", -1) + ".csv" server := []s...
package kandinsky import ( "bytes" "fmt" "math" "reflect" "sync" "github.com/gosvg/gosvg" ) // Marshal marshals a value into a valid SVG document represented as a byte slice. // Users should note that size here represents a nominal document size; SVG documents // are vector graphics and as such do not have a n...
package main import ( "testing" ) func Test_checkTemplatesFiles(t *testing.T) { tests := []string{ "resources/templates/changelog-md.tpl", "resources/templates/releasenotes-md.tpl", } for _, tt := range tests { t.Run(tt, func(t *testing.T) { got, err := defaultTemplatesFS.ReadFile(tt) if err != nil { ...
package helper import ( "encoding/json" "log" "runtime" "strconv" "strings" ) // MyCaller 取call我的人 func MyCaller() (name string) { defer func() { if catchErr := recover(); catchErr != nil { log.Println("🎃 helper.MyCaller 發生錯誤!", catchErr, " 🎃") return } }() fpcs := make([]uintptr, 1) n := runti...
package main import ( "github.com/urfave/cli" ) func init() { app.Commands = append(app.Commands, cli.Command{ Name: "serve", Aliases: []string{"s"}, Usage: "Serve your site locally", Action: func(c *cli.Context) error { if err := cfg.load("_config.yml"); err != nil { return err } return c...
package controller import ( "net/http" "github.com/model" "html/template" "strconv" ) type CountryController struct { countryTemplate *template.Template } type CountryDataResponse struct { CountryData *[]model.Country CountryEdit *model.Country } var countryModel model.Country func (f CountryController) regist...
package common import ( "errors" "fmt" "github.com/raft-kv-store/raftpb" log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "testing" ) func TestCmap_TryLocks(t *testing.T) { // TryLocks succeeds without intersected keys m1 := NewCmap(log.New(), 0) m1.Set("a", int64(1)) m1.Set("b", int64...
// 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 ...