text
stringlengths
11
4.05M
// Copyright 2023 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 ...
/* Copyright 2020 The Qmgo 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...
// Copyright 2021 Google LLC // // 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 ...
package p01 import ( "testing" ) func TestStock3(t *testing.T) { a := []int{3, 3, 5, 0, 0, 3, 1, 4} if maxProfits(a) != 6 { t.FailNow() } } func maxProfits(prices []int) int { if len(prices) == 0 { return 0 } count := 2 dp := make([][3][2]int, len(prices)) for i := 1; i < len(prices); i++ { for j := 2...
/* The pigeonhole principle states that If N items are put into M boxes, with N > M, then at least one box must contain more than one item. For many, this principle has a special status compared to other mathematical enouncements. As E.W. Dijkstra wrote, It is surrounded by some mystique. Proofs using it ar...
package db import ( "database/sql" "fmt" "log" ) func StartDB(user, pass, db, host string) *sql.DB { DB_CONNECT_STRING := fmt.Sprintf("host=%s port=5432 user=%s password=%s dbname=%s sslmode=disable", host, user, pass, db) dbConn, err := sql.Open("postgres", DB_CONNECT_STRING) if err != nil { log.Fatalf("Data...
package main import "fmt" func main() { //var s uint16、 //s := []int{0, 1, 2, 3, 4, 5, 6} //s1 := s[1:3] //s1[0] = 121 //fmt.Println(s) data := []string{"one", "", "three"} data1 := nonempty2(data) fmt.Println(data,data1) //s2 := string(b) } func nonempty2(strings []string) []string { out := strings[:0] //...
package main import "fmt" func main() { // // Define map // emails := make(map[string]string) // // assign kv // emails["Abhinav"] = "abhinav@designs.studio" // emails["Joe"] = "Joe@JoeDonuts.com" // emails["John"] = "John@Doe.com" // // print map // fmt.Println(emails) // // print one kv // fmt.Println(...
package main import ( "bufio" "fmt" "os" "sort" "strconv" "strings" "sync" ) func min(a, b int) int { if a < b { return a } return b } func sortChunk(arr []int, wg *sync.WaitGroup) { defer wg.Done() fmt.Println("Sorting chunk : ", arr) if len(arr) > 1 { sort.Slice(arr, func(i, j int) bool { return a...
package main import ( "fmt" "html/template" "log" "net/http" "os" "sort" "github.com/gorilla/pat" "github.com/gorilla/sessions" "github.com/markbates/goth" "github.com/markbates/goth/gothic" "github.com/markbates/goth/providers/twitter" ) //ProviderIndex ... type ProviderIndex struct { Providers []st...
package atomix import ( "fmt" "math" "sync/atomic" ) // Complex64 is an atomic wrapper around float32. type Complex64 struct { atomicType ri uint64 } // NewComplex64 creates a Complex64. func NewComplex64(c complex64) *Complex64 { return &Complex64{ri: complex64ToUint64(c)} } func (c *Complex64) String() stri...
package routinghelpers import ( "context" "testing" routing "gx/ipfs/QmRjT8Bkut84fHf9nxMQBxGsqLAkqzMdFaemDK7e61dBNZ/go-libp2p-routing" ) func TestLimitedValueStore(t *testing.T) { d := LimitedValueStore{ ValueStore: new(dummyValueStore), Namespaces: []string{"allow"}, } ctx := context.Background() for i...
package main import ( "fmt" "time" ) func countWeekday(fromYear, toYear int, weekday time.Weekday) int { var cnt int for y := fromYear; y <= toYear; y++ { for m := 1; m <= 12; m++ { d := time.Date(y, time.Month(m), 1, 0, 0, 0, 0, time.UTC) if d.Weekday() == weekday { cnt++ } } } return cnt } f...
package main import ( "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" "log" "fmt" "bytes" "net/http" "io/ioutil" ) var s3Objects []*s3.Object var...
package netlib import ( "net" ) func InterfaceCheckIPContains(ip string) bool { // if _ip := net.ParseIP(ip); nil != _ip { if list, err := InterfaceAddrs(); nil == err { for _, item := range list { switch result := item.(type) { case *net.IPNet: if result.Contains(_ip) { return true } ...
package go_recommend_me // Parmeters for the algorithm type ModelParameters struct{ NumUsers int NumItems int // k or the dimensionality of the joint latent factor space // ie kind of determining the space size for the latent factors Dimensionality int //number of known ratings TrainingSize int // Step si...
package octopus import ( "math" "runtime" "sync" "sync/atomic" "time" ) type cachedWorker struct { pool *WorkPool jobChannel chan Future stop chan bool } func newCacheWorker(cachedpool *WorkPool) *cachedWorker { return &cachedWorker { pool : cachedpool , jobChannel : make(chan Future) , stop : make(c...
package main import ( "encoding/json" "fmt" ) type person struct { Name string `json:"name"` Age int `json:"age"` } func main() { str := `{"name":"张三", "age":15}` var p person json.Unmarshal([]byte(str), &p) fmt.Println(p.Name, p.Age) }
package rudp import "net" type udpSrv struct { net.Conn } func (us udpSrv) recvUDP() ([]byte, error) { buf := make([]byte, maxUDPPktSize) n, err := us.Read(buf) return buf[:n], err } // Connect returns a Conn connected to conn. func Connect(conn net.Conn) *Conn { return newConn(udpSrv{conn}, PeerIDSrv, PeerIDN...
package main import ( "fmt" ) func main() { A := []int{6, 1, 1, 3, 2, 9, 0, 5, 7} sorted := countingSort(A, 10) fmt.Println("A after counting sort:", sorted) } /** countingSort sorts input array *A* using counting sort Time complexity: O(len(A) + k) */ //parameter A: input array ...
// +build: darwin dragonfly freebsd linux nacl netbsd openbsd package main import ( "os/exec" ) func System(cmd Command) error { c := exec.Command("bash", "-c", string(cmd)) if err := c.Start(); err != nil { return err } if err := c.Wait(); err != nil { return err } return nil }
package instapi import ( "context" "net/http" "net/url" "time" "github.com/instapi/client-go/types" ) // AssignRole assigns a account role for the given user. func (c *Client) AssignRole(ctx context.Context, account, email, role string, options ...RequestOption) error { _, _, err := c.doRequest( ctx, http....
package main import "fmt" const s string = "ROBIN IS AWESOME" const constantNumber = 591726 //structs, and they are mututable! type person struct { name string age int } func DEMO() { fmt.Println("Constant", s, constantNumber) fmt.Println("Hello") } //variadic function that accepts variable args func add(nums....
package timers import ( "sync" "time" ) // EarlyPeriodicTimer is a timer will periodically invoke a given task. However, // it also has the option to start the task ahead of time. When a task has been // prematurely started, the timer will reset. type EarlyPeriodicTimer struct { timerMu sync.Mutex timer *time.T...
package clusterdata // Copyright (c) Microsoft Corporation. // Licensed under the Apache License 2.0. import ( "reflect" "testing" "github.com/sirupsen/logrus" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/fake" "github.c...
package golify type golifyIntegerObject struct { Value int64 Err *golifyErr } func (g golifyIntegerObject) MoreThan(min int64, errCode int, errMsg string) golifyIntegerObject { if g.Err != nil { return g } if g.Value > min { return golifyIntegerObject{ Value: g.Valu...
package leetcodego import "testing" func Test_romanToInt(t *testing.T) { res := romanToInt("DCXXI") if res != 621 { t.Error(res) } }
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //416. Partition Equal Subset Sum //Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets su...
package keeper import ( "github.com/irisnet/irishub/app/v1/asset/internal/types" "github.com/irisnet/irishub/tests" "testing" "github.com/irisnet/irishub/app/v1/auth" "github.com/irisnet/irishub/app/v1/bank" "github.com/irisnet/irishub/app/v1/params" "github.com/irisnet/irishub/codec" sdk "github.com/irisnet/...
package main import ( "testing" zs "github.com/zerostick/zerostick/daemon" //_ "github.com/zerostick/zerostick/daemon" ) func TestWifi(t *testing.T) { wifi := &zs.Wifi{ SSID: "flaf", Password: "flaf", Priority: 1, UseForSync: false, } wifi.EncryptPassword() if wifi.Password != "" { t.Error...
package retry_test import ( "sync" "testing" "time" "github.com/hamba/testutils/retry" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) const timeDeltaAllowed = float64(25 * time.Millisecond) func TestRun(t *testing.T) { mockT := new(MockTestingT) mockT.On("Log", []interface{}{"test...
// Copyright 2020 The SwiftShader Authors. 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 b...
package cate import ( "MI/models" "MI/pkg/logger" "MI/service/cate" "MI/utils/response" "github.com/gin-gonic/gin" "strconv" ) func Cate(c *gin.Context){ isNav := c.Query("is_nav") if isNav == "" { response.RespError(c,"参数不能为空") return } //当参数为空 返回全部类别信息 is_nav, err := strconv.Atoi(isNav) if err != ni...
package persist import ( "fmt" "log" "github.com/m-o-s-e-s/mgm/mgm" ) func (m mgmDB) queryJobs() []mgm.Job { var jobs []mgm.Job con, err := m.db.GetConnection() if err != nil { errMsg := fmt.Sprintf("Error connecting to database: %v", err.Error()) log.Fatal(errMsg) return jobs } defer con.Close() rows...
package service_test import ( "context" "fmt" "net/http" "net/http/httptest" "sync" "testing" "time" "github.com/ONSdigital/dp-api-clients-go/v2/health" "github.com/ONSdigital/dp-healthcheck/healthcheck" "github.com/ONSdigital/florence/config" "github.com/ONSdigital/florence/service" "github.com/ONSdigita...
// Copyright 2019 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://aws.amazon.com/apache2.0/ // // or in the "license"...
package utils import ( "github.com/astaxie/beego/orm" "go_blog/models" ) func GetAllTableNames() ([]string) { return []string{"blog", "category"} } func GetAllBlogs() ([]models.Blog, error) { o := orm.NewOrm() var blogs []models.Blog _, err := o.QueryTable("blog").All(&blogs) if err != nil { return nil, err...
package install import ( log "github.com/sirupsen/logrus" corev1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" "k8s.io/apiserver/pkg/authentication/serviceaccount" "k8s.io/apiserver/pkg/authentication/user" "k8s.io/apiserver/pkg/authorization/authorizer" ) // toAttributesSet converts the given user, namespac...
package streams import ( "encoding/json" "fmt" "strconv" ) type orderDataRaw struct { Rate string `json:"rate"` Type string `json:"type"` Amount string `json:"amount"` TradeID string `json:"tradeID"` Date string `json:"date"` Total string `json:"total"` } type OrderData struct { Rate float64...
package httpModel import ( "github.com/astaxie/beego/orm" "strconv" "tokensky_bg_admin/models" "tokensky_bg_admin/utils" ) const ( //减少数据,允许精度 FLOAT_PRECISE_8 float64 = 0.00000001 FLOAT_NUM_8 int = 8 //允许货币类型校验[暂缺] ) var ( //允许的货币类型 acceptSymbol map[string]struct{} ) func init() { acceptSymbol = ...
package vaultengine import ( "fmt" "log" "github.com/hashicorp/vault/api" ) // CollectPaths will retrieve all paths to secrets defined under the given path func (client *Client) CollectPaths(path string) ([]string, error) { var secretPaths []string folder, err := client.FolderRead(path) if err != nil { retur...
package controllers import ( "crypto/md5" "github.com/gin-gonic/gin" "github.com/xiaoqunSun/api-server/mysql" ) func HandlerAccount(r *gin.Engine) { r.POST("/registerAccount", func(c *gin.Context) { username := c.PostForm("username") password := c.PostForm("password") if len(username) < 6 || len(username) ...
package types type BeaconEntry struct { Round uint64 Data []byte Metadata map[string]interface{} } func NewBeaconEntry(round uint64, data []byte, metadata map[string]interface{}) BeaconEntry { return BeaconEntry{ Round: round, Data: data, Metadata: metadata, } }
package main import ( "fmt" "time" ) func main() { c := make(chan int, 10) for _, i := range [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} { c <- i } time.AfterFunc(time.Second * 1, func(){ close(c) }) for { select { case v, _ := <-c: if v == 3 { c = nil fmt.Printf("c = nil \n") } fmt.Prin...
// Package ir provides the library for constructing a SSVM intermediate representation program in SSA form. package ir type Value interface { Type() Type // the type of the value SetName(string) // sets the name of the value Name() string // returns the name of the value Identifier() string // re...
/* * Copyright (c) 2019 QLC Chain Team * * This software is released under the MIT License. * https://opensource.org/licenses/MIT */ package contract import ( "errors" "github.com/qlcchain/go-qlc/common/types" "github.com/qlcchain/go-qlc/vm/abi" cabi "github.com/qlcchain/go-qlc/vm/contract/abi" "github.com...
package scheduler import ( "github.com/Sirupsen/logrus" "github.com/pkg/errors" "github.com/rancher/longhorn-manager/types" ) type OrcScheduler struct { ops types.ScheduleOps } func NewOrcScheduler(ops types.ScheduleOps) *OrcScheduler { return &OrcScheduler{ ops: ops, } } func randomHostID(m map[string]*ty...
package provider import ( "github.com/bearname/videohost/internal/common/db" "github.com/bearname/videohost/internal/thumbgenerator/app/publisher" "github.com/bearname/videohost/internal/thumbgenerator/domain/model" log "github.com/sirupsen/logrus" "time" ) func RunTaskProvider(stopChan chan struct{}, db db.Conn...
package models import ( "time" ) type Note struct { ID int `schema:"-"` Title string `schema:"title"` Body string `schema:"body"` Tags string `schema:"tags"` NotebookID int `schema:"notebook_id"` CreatedAt time.Time `schema:"-"` UpdatedAt time.Time `schema:"-"` ...
package tsl import ( "encoding/json" "fmt" "io/ioutil" "net/http" "strings" "time" "github.com/miton18/go-warp10/base" ) // Query is a TSL query type Query struct { raw string endpoint string token string httpClient *http.Client } // Execute the query on Backend func (q *Query) Execute() (b...
package nanomsgsubscriber import ( "encoding/json" "errors" "log" "github.com/didiercrunch/doorman/shared" "github.com/go-mangos/mangos" "github.com/go-mangos/mangos/protocol/sub" "github.com/go-mangos/mangos/transport/ipc" "github.com/go-mangos/mangos/transport/tcp" ) type NanoMsgSubscriber struct { Url st...
package entity_book import validation "github.com/go-ozzo/ozzo-validation" type Book struct { id uint64 isbn string title string author string } func NewBook(isbn string, title string, author string) (*Book, error) { book := Book{ isbn: isbn, title: title, author: author, } if err := book.val...
package gravatar import ( "testing" ) func TestHash(t *testing.T) { if "0bc83cb571cd1c50ba6f3e8a78ef1346" != Hash("MyEmailAddress@example.com ") { t.Errorf("incorrect hash") } }
// Copyright 2019 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 core import ( "archive/tar" "bytes" "compress/gzip" "fmt" "github.com/callumj/weave/tools" "io" "log" "os" "path" "strings" ) type Item struct { Start int64 Length int64 Name string } type ArchiveInfo struct { Items []Item Path string } type archiveProcessCallback func(string, string, *ta...
package commands import "code.cloudfoundry.org/cli/utils/config" //go:generate counterfeiter . Config // Config a way of getting basic CF configuration type Config interface { BinaryName() string ColorEnabled() config.ColorSetting Locale() string Plugins() map[string]config.Plugin SetTargetInformation(api strin...
package cmd import ( "bytes" "errors" "fmt" "os" "strings" "time" "github.com/a8uhnf/suich/pkg/utils" "github.com/spf13/cobra" ) const ( podInfoNameTitle = "NAME" ) var ( follow = false ) // GetLogsCmd builds the logs cobra command for suich func GetLogsCmd() *cobra.Command { logsCMD := &cobra.Command{ ...
package imageextractor import ( "fmt" "image" "image/jpeg" "log" "os" "strings" "github.com/disintegration/imaging" "github.com/otiai10/gosseract" ) type ImageExtractor struct { image image.Image path string } type goserractConfig struct { Image string Whitelist string Blacklist string Language ...
package main import ( "net/http" hand "./handler" "github.com/gorilla/mux" "log" ) var router = mux.NewRouter() func main() { log.Println("Server Starting") router.HandleFunc("/register/users", hand.Handler) router.HandleFunc("/signup", hand.SignUpHandler) router.HandleFunc("/login", hand.LoginHandler) ...
package standings import ( "errors" "net/http" "strings" "github.com/gin-gonic/gin" ) // Shield gives Supporters Shield Standings func Shield(c *gin.Context) { standings, err := GetShield() if err != nil { c.AbortWithError(http.StatusInternalServerError, err) } c.JSON(http.StatusOK, gin.H{ "standings": s...
package flarmport import ( "context" "fmt" "time" "github.com/gorilla/websocket" ) // Remote connects to a remote flarm server, and returns a an object that implements flarmReader.. func Remote(addr string) (*Conn, error) { d := websocket.Dialer{ HandshakeTimeout: time.Second * 10, } conn, _, err := d.Dial(...
package controllers import ( "log" "net/http" "time" "github.com/stevenandrewcarter/terradex/internal/models" ) func UnlockProject(w http.ResponseWriter, r *http.Request) { if r.Context().Value("projectID") == nil { log.Print("Please provide a projectID in order to lock the project.") w.WriteHeader(400) r...
// Copyright 2017 Zack Guo <zack.y.guo@gmail.com>. All rights reserved. // Use of this source code is governed by a MIT license that can // be found in the LICENSE file. // +build ignore package main import ( "log" "math" ui "github.com/gizak/termui/v3" "github.com/gizak/termui/v3/widgets" ) fu...
// 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 main import ( "os" "os/signal" "github.com/siggy/bbox/bbox" ) func main() { sig := make(chan os.Signal, 1) signal.Notify(sig, os.Interrupt, os.Kill) // beat changes // keyboard => loop // keyboard => render msgs := []chan bbox.Beats{ make(chan bbox.Beats), make(chan bbox.Beats), } // tem...
// Copyright 2022 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 repository import "github.com/lfmexi/tcpgateway/session/model" // SessionRepository is the session repository type SessionRepository interface { Insert(*model.Session) error Update(*model.Session) error }
//https://leetcode-cn.com/problems/longest-palindromic-substring/ package main import "fmt" func main() { // s := "babad" // s := "cbbd" // s := "bb" // s := "" // if s == "" || len(s) < 2 { // return "" // } fmt.Println(s) start := 0 end := 0 strLen := 0 for i := 0; i < len(s); i++ { ...
package collection import ( "path/filepath" "reflect" "runtime" "testing" "github.com/forensicanalysis/artifactlib/goartifacts" "github.com/forensicanalysis/forensicstore/goforensicstore" ) func Test_collectorResolver_Resolve(t *testing.T) { windowsEnvironmentVariableSystemRoot := goartifacts.ArtifactDefiniti...
package checksum import "testing" func TestEncode(t *testing.T) { str, err := Encode("appSecret", "nonce", "time") if err != nil { t.Error(err) return } t.Log(str) }
package host import ( "crypto/md5" "fmt" "io" ) // Host struct host information about discovered network client type Host struct { id string IP string MAC string } // ID will generate unique MD5 hash of host by his properties // and cache generated hash for future usage func (h *Host) ID() string { if h.id ...
package main import ( "context" pdd "go_interview/advanced_go_programming/chapter04/rpc_hello_05/grpc_hello_03/grpc_hello_publisher" "google.golang.org/grpc" "log" ) func main() { conn, err := grpc.Dial("localhost:1234", grpc.WithInsecure()) if err != nil { log.Fatal(" conn err:", err) } defer conn.Close(...
package kubernetes import ( "context" "errors" "strings" "testing" "github.com/brigadecore/brigade/v2/apiserver/internal/api" "github.com/brigadecore/brigade/v2/apiserver/internal/lib/queue" "github.com/brigadecore/brigade/v2/apiserver/internal/meta" myk8s "github.com/brigadecore/brigade/v2/internal/kubernete...
package transport import ( "net/http" "github.com/gin-gonic/gin" s "github.com/thedevelopnik/netplan/pkg/models" ) // CreateSubnetEndpoint creates a Subnet and returns the created value. // Returns a 400 if it can't create the struct, // or a 500 if the db connection or creation fails. func (h netplanHTTP) Creat...
/* Whilst trying (and failing) have persuade my infant son to eat his dinner, I tried singing to him. Mid way through this song I realised the formulaic structure might lend itself well to code golfing! The task is to write a program or function which accepts no input and produces the following text: There's a hole ...
// Copyright (c) 2013-2016 The btcsuite developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package keystore import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/rand" "crypto/sha512" "encoding/binary" "encoding/hex" "errors" "fmt" "io" "math/big" ...
package romanLiterals import ( "fmt" "testing" "testing/quick" ) // Strings for formatting test messages const ( convertArabicToRoman = "%d gets converted to %q" convertArabicToRomanFailed = "Conversion result: %q, expected %q" convertRomanToArabic = "%q gets converted to %d" convertRomanToArabicFailed = "Conv...
package server import ( "encoding/json" "net/http" colly "github.com/gocolly/colly/v2" ) type songData struct { Title string `json:"title"` Artist string `json:"artist"` } // TestSpotify ... func TestSpotify(w http.ResponseWriter, r *http.Request) { enableCors(&w, r) query := r.URL.Query().Get("query") if...
package ginja import ( "encoding/json" "reflect" "testing" . "github.com/smartystreets/goconvey/convey" ) func NewTestApi() *Api { return &Api{} } type TestItem struct { Name string `json:"name"` } var testItem = TestItem{ Name: "A Name", } var testItemPayload = map[string]interface{}{ "data": map[string]...
package pgsql import ( "database/sql" "database/sql/driver" "net" ) // InetFromIPNet returns a driver.Valuer that produces a PostgreSQL inet from the given Go net.IPNet. func InetFromIPNet(val net.IPNet) driver.Valuer { return inetFromIPNet{val: val} } // InetToIPNet returns an sql.Scanner that converts a Postgr...
package main import ( "log" "net/http" "github.com/SanderV1992/golang_simple_blog/news" "github.com/SanderV1992/golang_simple_blog/page" "github.com/SanderV1992/golang_simple_blog/site" "github.com/SanderV1992/golang_simple_blog/database" ) const ( defaultPort = "8080" databaseType = "mysql" ) func main()...
package transformer import ( "github.com/golang/protobuf/ptypes" "github.com/satori/go.uuid" "github.com/tppgit/we_service/core" "github.com/tppgit/we_service/dto/worder" "github.com/tppgit/we_service/entity/order" "github.com/tppgit/we_service/entity/service" "github.com/tppgit/we_service/entity/user" "github...
package pgsql import ( "testing" ) func TestFloat4Array(t *testing.T) { testlist2{{ valuer: Float4ArrayFromFloat32Slice, scanner: Float4ArrayToFloat32Slice, data: []testdata{ {input: []float32(nil), output: []float32(nil)}, {input: []float32{}, output: []float32{}}, {input: []float32{1, 0}, output: ...
package main import ( "bufio" "fmt" "os" "strings" "./Interprete" "./Structs" ) var disco [27]Structs.Disco func main() { menu() } func menu() { finalizar := 0 fmt.Println("Bienvenido a la consola de comandos... ('x' para finalizar)") reader := bufio.NewReader(os.Stdin) fmt.Print("Enter comands: ") c...
package main import ( "bufio" "fmt" "io" "log" "os" "os/exec" "regexp" "strings" "sync" ) func main() { if len(os.Args) < 2 { fmt.Println("usage: klogs <pod-name>") fmt.Println("example: klogs api") os.Exit(1) } name := os.Args[1] pods, err := getPods(name) if err != nil { panic(err) } log.Pri...
/* * Copyright 2018 Haines Chan * * This program is free software; you can redistribute and/or modify it * under the terms of the standard MIT license. See LICENSE for more details */ package config import ( "encoding/json" "fmt" "github.com/containernetworking/cni/pkg/types" "github.com/hainesc/anchor/pkg/...
package ws import ( "encoding/json" "fmt" "log" "github.com/gorilla/websocket" ) type Client struct { id string socket *websocket.Conn send chan []byte message *Message } func (c *Client) work(){ go c.read() go c.write() } func (c *Client) read () { defer c.close() for { _, message, err := c....
package mkhttpclient import ( "bytes" "context" "encoding/json" "fmt" "io" "io/ioutil" "mime/multipart" "net/http" "net/url" "time" "github.com/zhongxuqi/mklibs/common" "github.com/zhongxuqi/mklibs/mklog" ) // const ... const ( ContentTypeJSON = "application/json" ContentTypeForm = "application/x-www-f...
package fsm import ( "fmt" "strings" "testing" ) func TestMermaidOutput(t *testing.T) { fsmUnderTest := NewFSM( "closed", Events{ {Name: "open", Src: []string{"closed"}, Dst: "open"}, {Name: "close", Src: []string{"open"}, Dst: "closed"}, {Name: "part-close", Src: []string{"intermediate"}, Dst: "clos...
/* Copyright © 2022 SUSE LLC 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 distrib...
package processor import ( "log" "github.com/chapterzero/gomposer/provider" "io" "math/rand" "net/http" "fmt" "strings" "os" "time" "archive/zip" "path/filepath" "sync" ) const tempDirectory = "/tmp" var i int = 2; type DownloadResult struct { status int filePath string err error depend...
package main import "fmt" import "io/ioutil" func main() { // case1(정석) // var b []byte // var err error // b, err = ioutil.ReadFile("./hello.txt") // if err == nil { // fmt.Printf("%s", b) // } // case2 if b, err := ioutil.ReadFile("./hello.txt"); err == nil { // if 조건문 안에서 변수를 생성할 시, else, if else 문...
package main import "fmt" func main() { fmt.Println(canPlaceFlowers([]int{ 0, 0, 0, 0, 1, }, 2)) fmt.Println(canPlaceFlowers([]int{ 1, 0, 0, 0, 0, 0, 1, }, 2)) fmt.Println(canPlaceFlowers([]int{ 0, 0, 1, 0, 1, }, 1)) fmt.Println(canPlaceFlowers([]int{ 0, }, 1)) } func canPlaceFlowers(flowerbed []...
package apikey const ( // PermFlush Permission to restart/reload the system including flushing/forcing the queues PermFlush string = "flush" // PermGenerateInvites Permission to generate invites remotely PermGenerateInvites string = "invite" // PermAPIKeys Permission to create api keys PermAPIKeys string = "apik...
package packet import ( "encoding/json" ce "github.com/halivor/common/golang/util/errno" ) type Rsp struct { ErrCode int `json:"error_code"` ErrMsg string `json:"error_message"` Data interface{} `json:"data,omitempty"` } type RspRaw struct { ErrCode int `json:"error_code"` ErrMsg...
package model import "time" type Book struct { Id int64 `xorm:"pk autoincr int(64)" json:"id" form:"id" example:"1"` // 0: 気になる // 1: 購入済 // 2: 読了 Status int16 `xorm:"int(16)" json:"status" enums:"0,1,2"` Title string `xorm:"varchar(40)" json:"title" form:"title" validate:"required" example:"本のタイトル"...
// Package google implements OpenID Connect for Google and GSuite. // // https://www.pomerium.com/docs/identity-providers/google // https://developers.google.com/identity/protocols/oauth2/openid-connect package google import ( "context" "fmt" oidc "github.com/coreos/go-oidc/v3/oidc" "github.com/pomerium/pomerium...
package shared import ( "context" "go.mercari.io/datastore" ) var _ datastore.Middleware = &MiddlewareBridge{} type MiddlewareBridge struct { ocb OriginalClientBridge otb OriginalTransactionBridge oib OriginalIteratorBridge mws []datastore.Middleware Info *datastore.MiddlewareInfo } type OriginalClientB...
package utils import ( "os" cli "github.com/jawher/mow.cli" logging "github.com/op/go-logging" ) var ( formatter = logging.MustStringFormatter( `%{color}%{time:15:04:05.000} %{shortpkg}.%{shortfunc} [%{level}]%{color:reset} %{message}`) formatterNoColor = logging.MustStringFormatter( `%{time:15:04:05.000} %...
package api import ( "errors" "reflect" "strconv" "strings" "github.com/fatih/structs" "github.com/oleiade/lane" "github.com/sapk/sca/pkg/tools" log "github.com/sirupsen/logrus" "github.com/zabawaba99/firego" ) //API interface for sca backend type API struct { APIKey string BaseURL string Refr...