text
stringlengths
11
4.05M
package main import "fmt" func main() { first := 123 var firstPtr *int = &first fmt.Printf("Type of firstPtr: %T and value %v\n", firstPtr, firstPtr) *firstPtr += 200 fmt.Println("New value of first:", first) //Pointer zero value var zeroPtr *int //*zeroPtr++ if zeroPtr == nil { fmt.Println("Old Value in...
package tests_test import ( "testing" ecombase "github.com/codedv8/go-ecom-base" ) func TestTreeNode(t *testing.T) { node := &ecombase.LinkedTreeNode{ Key: "F", Data: "xxx", } ok, err := node.Add("A", "Whatever") if ok == false { t.Error("ok was false for A") } if err != nil { t.Error("Returned err...
package pool import ( "errors" "fmt" "github.com/barakb/go-rpc" "io" "net" "os" "time" ) var marshaller *rpc.Marshaller type tcpTransport struct { rpc.Logger bindAddr string listenAddress net.Addr timeout time.Duration consumer chan RPC connectionPool *ConnectionPool server ...
package main import ( "encoding/json" "flag" "fmt" "io/ioutil" "log" "github.com/thoas/stats" "github.com/unrolled/render" ) type env struct { Metrics *stats.Stats Render *render.Render } var fPort string var fFixtures string func init() { // parse command line flags flag.StringVar(&fFixtures, "fixture...
package port import ( "github.com/mirzaakhena/danarisan/domain/repository" "github.com/mirzaakhena/danarisan/domain/service" ) // BuatArisanOutport ... type BuatArisanOutport interface { service.TransactionDB service.IDGenerator repository.FindOnePesertaRepo repository.SaveArisanRepo repository.SavePesertaRepo...
package advicedb import ( "context" "errors" "log" "os" "time" "github.com/jackc/pgx/v4/pgxpool" "github.com/joho/godotenv" ) type Advice struct { UserId string Advice string CreatedAt time.Time } var _ = loadLocalEnv() var ( db = GetEnv("POSTGRES_DB") username = GetEnv("POSTGRES_USER") pas...
// 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 ds /** Remove all elements from a linked list of integers that have value val. Example: Input: 1->2->6->3->4->5->6, val = 6 Output: 1->2->3->4->5 */ /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ type ListNode struct { Val int Next *Lis...
package main import "fmt" func characterReplacement(s string, k int) int { n := len(s) if n <= k { return n } maxLength := k var remaining int for c := 0; c < n; c++ { if c > 0 && s[c] == s[c-1] { continue } remaining = k l, r := c, c for r < n { if s[r] == s[c] { r++ } else if remainin...
package ferraris import ( "log" "strings" ) // Power returns the current power measurement in Watts func (f Ferraris) Power() float64 { if f.stop == 0 { return 0 } return (1000 / float64(f.RotationsPerKiloWattHour)) / f.stop.Hours() } // Print screen output func (f Ferraris) Print() { log.Printf("%10v %2v %4...
package models import ( "go.mongodb.org/mongo-driver/bson/primitive" "time" ) type User struct { ID primitive.ObjectID `json:"id,omitempty" bson:"_id,omitempty"` LastName string `json:"lastName,omitempty" bson:"lastName,omitempty"` UpdatedAt time.Time `json:"updatedAt,o...
package database import ( pb "github.com/autograde/aguis/ag" ) // Database contains methods for manipulating the database. type Database interface { GetRemoteIdentity(provider string, rid uint64) (*pb.RemoteIdentity, error) CreateUserFromRemoteIdentity(*pb.User, *pb.RemoteIdentity) error AssociateUserWithRemoteI...
package main import ( "encoding/json" "net/http" "github.com/xsymphony/ac" "github.com/xsymphony/fin" ) var automaton *ac.Automaton type replaceSensitiveRequest struct { Sentence string `json:"sentence"` Symbol string `json:"symbol"` } func replaceWord(c *fin.Context) { var req replaceSensitiveRequest if...
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package cmd import ( "testing" "github.com/google/uuid" "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/Azure/aks-engine/pkg/api" ) func TestNewGenerateCmd(t *testing.T) { t.Parallel() command := ne...
package otpauth import ( "crypto" ) func GenOTP(a crypto.Hash, s []byte, f int64) (int64, error) { h, err := HMAC(a, s, Itob(f)) if err != nil { return 0, err } o := h[len(h)-1] & 0xf b := ((int64(h[o]) & 0x7f) << 24) | ((int64(h[o+1]) & 0xff) << 16) | ((int64(h[o+2]) & 0xff) << 8) | (int64(h[o+3]) & 0...
package core type Player struct { platform int handler func(...interface{}) params []interface{} } func (Player *Player) NewClient(player int) *Player { Player.platform = player return Player } func (Player *Player) RecHandleFunc(hFuc handlerFunc,params ...interface{}) { Player.handler = hFuc } func (Player ...
package rpmmd_mock import ( "github.com/osbuild/osbuild-composer/internal/rpmmd" "github.com/osbuild/osbuild-composer/internal/store" "github.com/osbuild/osbuild-composer/internal/worker" ) type fetchPackageList struct { ret rpmmd.PackageList checksums map[string]string err error } type depsolve str...
package main import ( "fmt" "math/rand" "os" "strconv" ) // Roll a die until first is hit, immediately followed by second // Return the number of rolls to end the game // x and y must be in {min,...,max} func playGame(first int, second int, min int, max int) int { last := -1 for nRolls := 1; ; nRolls++ { roll...
package usecase import ( "bytes" "context" "fmt" "io" "io/ioutil" "mime/multipart" "net/http" "path/filepath" "../domain" "../utils" "cloud.google.com/go/storage" "github.com/google/uuid" "gopkg.in/mgo.v2/bson" ) //VideoService ... type VideoService struct{} //UploadVideo ... func (vs *VideoService) Up...
/* Tencent is pleased to support the open source community by making Basic Service Configuration Platform 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 obtain...
package producer import ( "context" "errors" "fmt" "log" "time" "github.com/cenkalti/backoff" "github.com/streadway/amqp" ) type ProducerMQ struct { conn *amqp.Connection channel *amqp.Channel uri string done chan error exchangeName string exchangeType string queue ...
// Package maps 实现映射 // REF: http://ifeve.com/go-concurrency-concurrent-map/ package maps import ( "reflect" ) // GenericMap 通用的Map type GenericMap interface { // Get 获取给定键值对应的元素值若没有对应元素值则返回nil Get(key interface{}) interface{} // Put 添加键值对,并返回与给定键值对应的旧的元素值若没有旧元素值则返回(nil, true) Put(key interface{}, elem interfac...
package context var panicHandlerKey = &struct{ bool }{} func (c *ctx) panicHandle(panicErr interface{}) { sc := c defer func() { if panicErr = recover(); panicErr != nil { if sc != nil { sc = sc.parent } if sc != nil { sc.panicHandle(panicErr) } else { panic(panicErr) } } }() for ...
package main import ( "log" "os" "path/filepath" "text/template" ) type Version struct { OS string AnsibleVer string } func main() { os_names := []string{"trusty", "xenial"} ansible_versions := []string{"1.9", "2.0", "2.1", "2.2"} tpl := template.Must(template.ParseFiles("Dockerfile.tpl")) var me...
package main import "fmt" type Pet interface { Name() string Age() uint8 } type Dog struct { name string age uint8 } func (dog Dog) Name() string { return dog.name } func (dog Dog) Age() uint8 { return dog.age } func main() { myDog := Dog{"Little D", 3} _, ok1 := interface{}(&myDog).(Pet) _, ok2 := inter...
package multibase import ( "bytes" "math/rand" "testing" ) func TestMap(t *testing.T) { for s, e := range Encodings { s2 := EncodingToStr[e] if s != s2 { t.Errorf("round trip failed on encoding map: %s != %s", s, s2) } } for e, s := range EncodingToStr { e2 := Encodings[s] if e != e2 { t.Errorf(...
package p2p import ( "context" "errors" "time" "github.com/bluele/gcache" "github.com/qlcchain/go-qlc/common" "github.com/qlcchain/go-qlc/common/types" "github.com/qlcchain/go-qlc/ledger" "github.com/qlcchain/go-qlc/ledger/process" "github.com/qlcchain/go-qlc/p2p/protos" ) const ( checkCacheTimeInterval =...
package utils /* import ( "context" "math/big" "sync" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/ethclient" "github.com/golang/glog" "sub_account_service/blockchain/lib" ) // Gobal var of All the nonce in api server var MyNonce *Nonce type Nonce struct { m map[s...
package peer import ( "bytes" "testing" ) func TestID(t *testing.T) { var ( publicKey1 = []byte("12345678901234567890123456789012") publicKey2 = []byte("12345678901234567890123456789011") publicKey3 = []byte("12345678901234567890123456789013") address = "localhost:12345" id1 = CreateID(address, publi...
package handlers import ( "fmt" "log" "strconv" "strings" "time" "github.com/openfaas/faas/gateway/metrics" "github.com/prometheus/client_golang/prometheus" ) // HTTPNotifier notify about HTTP request/response type HTTPNotifier interface { Notify(method string, URL string, originalURL string, statusCode int,...
package planets import "context" type Service interface { CountMovies(ctx context.Context, planetName string) (int, error) }
package server import ( "context" "fmt" "math/rand" "net/http" "time" "github.com/go-co-op/gocron" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "google.golang.org/grpc" "github.com/go-sink/sink/internal/app/config" "github.com/go-sink/sink/internal/app/handlers" "github.com/go-sink/sink/internal/ap...
package main import ( "net" "google.golang.org/grpc" "context" "math/rand" "time" "fmt" "sms-grpc/main/util" "sms-grpc/main/sms" "encoding/json" ) type SmsServer struct{} func (s *SmsServer) SendSms(ctx context.Context, in *sms.SmsRequest) (*sms.SmsReply, error) { rnd := rand.New(rand.NewSource(time.Now()....
package golum import ( "fmt" "os" "testing" ) func TestCreateOneHistogram(t *testing.T) { file := "data/labeled_iris.csv" cols := []string{"sepal_length"} df, err := GetDFFromCSV(file, cols) if err != nil { t.Error(err.Error()) } if err := CreateHistograms(&df, nil); err != nil { t.Error(err.Error()) } ...
package pipeline import ( "sync" "sync/atomic" "github.com/sherifabdlnaby/prism/app/component" "github.com/sherifabdlnaby/prism/app/pipeline/node" "github.com/sherifabdlnaby/prism/app/pipeline/persistence" "github.com/sherifabdlnaby/prism/pkg/job" "github.com/sherifabdlnaby/prism/pkg/response" "go.uber.org/za...
// Package lissajous generates GIF animations of random Lissajous figures with given parameters. Exercises 1.5, 1.12 package lissajous import ( "image" "image/color" "image/gif" "io" "math" "math/rand" ) var palette = []color.Color{color.Black, color.RGBA{G: 255, R: 0, B: 0, A: 100}} const ( blackIndex = 0 //...
package game_map import ( "fmt" "github.com/steelx/go-rpg-cgm/combat" ) type CEAttack struct { name string countDown float64 owner *combat.Actor Targets []*combat.Actor Scene *CombatState Finished bool Character *Character Storyboard *Storyboard...
package main import ( "encoding/json" "fmt" "log" "math/rand" "net/http" "time" "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/ironarachne/culturegen" "github.com/ironarachne/random" ) func getCulture(w http.ResponseWriter, r *http.Request) { id := chi.URLParam(r, "id") var newCu...
package main import "logging" import "sensor" import "sensor/reader" import "actuator" /* Device configuration is currently hard-coded here. * That is: * - Fan curves information * - Sensors information (file path, command line, ...) * - Actuators informations (file path, command line, ...) */ func ...
package main import ( "fmt" "time" ) func StartApp8() { test8001() fmt.Println("================================") s := []int{7, 2, 8, -9, 4, 0} //信道是带有类型的管道,你可以通过它用信道操作符 <- 来发送或者接收值。 c := make(chan int) go sum(s[:len(s)/2], c) go sum(s[len(s)/2:], c) //“箭头”就是数据流的方向 x, y := <-c, <-c fmt.Println(x, y) fm...
package main import "fmt" func main() { //DECLARE a BOOLEAN variable var x bool fmt.Println("Zero value of BOOLEAN :: ", x) x = true fmt.Println("Modified value of 'x' :: ", x) a := 7 b := 42 fmt.Println("Some boolean operators ::") fmt.Println("a == b", a == b) fmt.Println("a != b", a != b) fmt.Println("...
package dao import ( "log" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" ) var ( DB *gorm.DB ) func InitDB() (err error) { dsn := "root:123456@(127.0.0.1:3306)/db_todo?charset=utf8mb4&parseTime=True&loc=Local" DB, err = gorm.Open("mysql", dsn) if err != nil { log.Panicf("open database...
package service import ( "context" "errors" "github.com/golang/mock/gomock" "github.com/polundrra/shortlink/internal/repo" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" "testing" ) type LinkServiceSuit struct { suite.Suite mockCtrl *gomock.Controller repoMock *repo.MockLinkRepo S...
package files import ( "fmt" "io/ioutil" "net/http" "net/http/httptest" "net/url" "testing" ) func TestWebFile(t *testing.T) { http.HandleFunc("/my/url/content.txt", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello world!") }) s := httptest.NewServer(http.HandlerFunc(func(w http.Respon...
package main import ( "fmt" "os" "os/signal" "strconv" "sync" "syscall" "time" ) var ( // dataCh = make(chan Person) idx = 0 maxCount = 20 ) var dataCh chan Person func main() { // dataCh = make(chan Person) // var wg sync.WaitGroup // startT := time.Now() // fmt.Println("Start deal with data"...
package main import ( "errors" "fmt" "io" "os" "path/filepath" "s3upload/helpers" "strings" "github.com/aws/aws-sdk-go/service/s3/s3manager" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" "github.com/n...
package fileupload import ( "fmt" "io" "mime/multipart" "net/http" "os" "path/filepath" "github.com/majid-cj/go-docker-mongo/util" "github.com/thoas/go-funk" ) // AllowedImages .... var AllowedImages = []string{"image/jpeg", "image/jpg", "image/png"} // UploadFile ... type UploadFile struct{} // UploadFile...
package handler import ( "github.com/go-redis/redis" "go-admin/config" ) var RedisClient = new(redis.Client) func init() { RedisNewClient(config.RedisConnConfig.Addr, config.RedisConnConfig.Password, config.RedisConnConfig.DB) } func RedisNewClient(addr string, password string, db int) { //timeout := time.Durat...
package table import ( "encoding/json" "errors" "fmt" "html/template" "io/ioutil" "net/http" "strconv" "strings" "time" "github.com/GoAdminGroup/go-admin/modules/config" "github.com/GoAdminGroup/go-admin/modules/db" "github.com/GoAdminGroup/go-admin/modules/db/dialect" errs "github.com/GoAdminGroup/go-a...
// Start an HTTP GraphQL API server, which is loaded multiple Databases for serving package main import ( "log" "net/http" "time" graphql "github.com/graph-gophers/graphql-go" "github.com/tonyghita/graphql-go-example/handler" "loader" ) func main(){ // Tweakable Arugments var ( port = ":8000" readHeaderTi...
package end import ( "testing" . "github.com/bborbe/assert" io_mock "github.com/bborbe/io/mock" "github.com/bborbe/server/renderer" ) func TestImplementsRenderer(t *testing.T) { r := NewEndRenderer() var i (*renderer.Renderer) = nil err := AssertThat(r, Implements(i).Message("check implements renderer.Rendere...
package main import "fmt" type Test1 struct { is int } func main() { i := 5 Test(func(test1 Test1) bool { return i == test1.is }) } func Test(f func(Test1) bool) { t := Test1{2} fmt.Println(f(t)) }
//go:build !ASCII // +build !ASCII package es // 对应C里面的UNICODE宏定义启用,这里是默认使用 var ( EverythingSetSearch = everythingSetSearchW EverythingGetSearch = everythingGetSearchW EverythingQuery = everythingQueryW EverythingGetResul...
// ImgChangeInfo package DaeseongLib import ( _ "fmt" "image" "image/gif" "image/jpeg" "image/png" "io/ioutil" "os" "path/filepath" "strings" "syscall" "unsafe" ) var ( kernel32B = syscall.NewLazyDLL("kernel32.dll") GetModuleFileNameProc = kernel32B.NewProc("GetModuleFileNameW") ) func GetMo...
package resources import ( "encoding/json" "net/http" "github.com/gorilla/mux" "github.com/shwetha-pingala/HyperledgerProject/InvoiveProject/go-api/models" ResourcesModel "github.com/shwetha-pingala/HyperledgerProject/InvoiveProject/go-api/models/v1/resources" "github.com/shwetha-pingala/HyperledgerProject/Inv...
package handlers import ( rest "github.com/danteay/ginrest" "github.com/gin-gonic/gin" ) // PingHandler is a simple get endpoint that can be used for healt check func PingHandler() func(c *gin.Context) { return func(c *gin.Context) { u := c.Request.RequestURI r := rest.New(u, "").SetGin(c) r.Res(200, rest.P...
package main import ( "crypto/tls" "crypto/x509" "flag" "fmt" "io" "io/ioutil" "log" "math/rand" "runtime" "sync" "time" "github.com/gholt/brimtime" gp "github.com/pandemicsyn/oort/api/groupproto" vp "github.com/pandemicsyn/oort/api/valueproto" "github.com/pkg/profile" "github.com/spaolacci/murmur3" ...
package common /* Generated using mavgen - https://github.com/ArduPilot/pymavlink/ Copyright 2020 queue-b <https://github.com/queue-b> Permission is hereby granted, free of charge, to any person obtaining a copy of the generated software (the "Generated Software"), to deal in the Generated Software without restricti...
package main // code snippets were taken from: https://outcrawl.com/image-recognition-api-go-tensorflow/ import ( "bufio" "bytes" "context" "encoding/json" "io/ioutil" "os" "path/filepath" "strconv" "time" "github.com/google/uuid" "github.com/sdeoras/token/proto" "github.com/sirupsen/logrus" tf "github....
package scheduler import ( "time" ) //DurationWatcher is the interface type DurationWatcher interface { Duration() time.Duration Watch() chan time.Duration } //Schedule will schedule the execution of the function f, exery Duration(), it will automatically change Duration() //if a change is made to the desired Dur...
// 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 fakes import "github.com/cloudfoundry-incubator/notifications/models" type ClientsRepo struct { Clients map[string]models.Client UpsertError error FindError error } func NewClientsRepo() *ClientsRepo { return &ClientsRepo{ Clients: make(map[string]models.Client), } } func (...
package compile import( "github.com/Evedel/fortify/src/dictionary" ) func toClang(SyntaxTree dictionary.TokenNode) (Result string) { tn := SyntaxTree tnid := tn.This.Id if tnid == dictionary.Program { for ttch := range SyntaxTree.List { Result += toClang(SyntaxTree.List[ttch]) } } else { tnchid := tn.L...
package resource import ( corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" wfv1 "github.com/argoproj/argo/pkg/apis/workflow/v1alpha1" ) func DurationForPod(pod *corev1.Pod) wfv1.ResourcesDuration { summaries := Summaries{} for _, c := range append(pod.Spec.InitContainers, pod.Spec.Containers.....
package main import ( "fmt" "log" "os" "github.com/joho/godotenv" "github.com/taglme/nfc-goclient/pkg/client" ) func main() { err := godotenv.Load() if err != nil { log.Fatal("Error loading .env file") } privateRSAKey, err := client.PrivateRSAKeyFromB64String(os.Getenv("SECRET")) if err != nil { log.Fa...
package btrfs import ( "bufio" "errors" "fmt" "os" "os/exec" "path" "strings" "syscall" ) type FsMagic int64 const ( FsMagicBtrfs = FsMagic(0x9123683E) FsMagicBtrfs32Bit = FsMagic(-1859950530) ) var ( ErrPrerequisites = errors.New("prerequisites for driver not satisfied (wrong filesystem?)") ) func...
package main import ( "fmt" ) type User struct { FirstName string LastName string } func (u *User) FullName() string { fullname := fmt.Sprintf("%s %s", u.FirstName, u.LastName) return fullname } func NewUser(firstName, lastName string) *User { return &User{ FirstName: firstName, LastName: lastName, } }...
// Package transmitter provides functionality for transmitting // arbitrary webhook messages on Discord. // // Existing webhooks are used for messages sent, and if necessary, // new webhooks are created to ensure messages in multiple popular channels // don't cause messages to be registered as new users. package transm...
package role import ( "errors" "time" "xorm.io/builder" "yj-app/app/yjgframe/db" "yj-app/app/yjgframe/utils/excel" "yj-app/app/yjgframe/utils/page" ) // Entity is the golang structure for table sys_role. type EntityFlag struct { RoleId int64 `json:"role_id" xorm:"not null pk autoincr comment('角色ID') BI...
package config import "github.com/dank/go-csgsi" // GameSetup creates and returns a Game object func GameSetup() *csgsi.Game { return csgsi.New(0) }
package service import ( "enter-module/core/common" "enter-module/core/config" "enter-module/core/info" "enter-module/core/util" "database/sql" ) var sqlConf = config.InitDBInfo() // 用户登录 func UserLogIn(userInfo info.LogInUserInfo) string { db, err := sql.Open(sqlConf.SqlDriverName, sqlConf.DataSourceName) if...
package main import ( "bufio" "fmt" "io" "os" "github.com/golang/glog" "github.com/rivo/uniseg" ) func main() { br := bufio.NewReader(os.Stdin) for { line, c := br.ReadString('\n') if c == io.EOF { break } if c != nil { glog.Fatal(c) } fmt.Println(line) gr := uniseg.NewGraphemes(line) f...
package trident import ( "errors" "time" "trident.li/keyval" pf "trident.li/pitchfork/lib" ) type TriGroup interface { pf.PfGroup Add_default_attestations(ctx pf.PfCtx) (err error) GetVouch_adminonly() bool GetAttestations() (output []TriGroupAttestation, err error) GetAttestationsKVS() (kvs keyval.KeyVals, ...
// write to file // read from file package main import ( "encoding/json" "fmt" "io/ioutil" "os" "path/filepath" ) var DIR = func() string { p := filepath.Join("testdata") fi, err := os.Lstat(p) if err != nil { panic(err) } if !fi.IsDir() { panic("is not directory " + p) } return p }() func readJSON()...
//go:generate sh -c "protoc --go_out=plugins=grpc:. *.proto" package proto
// Copyright 2018 Diego Bernardes. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package flare import ( "context" "encoding/json" "fmt" "github.com/go-kit/kit/log" "github.com/go-kit/kit/log/level" "github.com/pkg/errors" "github....
package main func blue(str string) string { return "\033[1;34m" + str + "\033[0m" } func yellowWithBlueBG(str string) string { return "\033[1;33;44m" + str + "\033[0m" }
package main import ( "fmt" "net" ) const addr = "localhost:8888" func main() { conns := &connections{ addrs: make(map[string]*net.UDPAddr), } fmt.Printf("serving on %s\n", addr) // construct a udp addr addr, err := net.ResolveUDPAddr("udp", addr) if err != nil { panic(err) } // listen on our specif...
package gortex import ( "fmt" "github.com/vseledkin/gortex/assembler" ) // Long Short Term Memory cell type MultiplicativeNestedLSTM struct { Wmx *Matrix Umh *Matrix Wf *Matrix Uf *Matrix Bf *Matrix Wi *Matrix Ui *Matrix Bi *Matrix Wo *Matrix Uo *Matrix Bo *Matrix Wc *Matrix Uc *Matrix Bc *Matri...
package mock import ( "context" "testing" addr "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/network" "github.com/ipfs/go-cid" "github.com/minio/blake2b-simd" ) // Build for fluent initialization of a mock runtime. type Ru...
package src import ( "gopkg.in/go-playground/validator.v8" "reflect" "regexp" ) func TopicsValidate(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { topics,ok:= topStruct.Interface().(*To...
package templates import ( "database/sql/driver" "embed" "fmt" "html/template" "github.com/cswank/quimby/internal/schema" ) var ( //go:embed static/* Static embed.FS //go:embed templates/* tpls embed.FS templates map[string]tmpl deviceFuncs = template.FuncMap{ "format": func(v driver.Value, decimals ...
package main import "fmt" type User struct { name string monthlySalary int64 time int64 } var userArr [3]User func main() { var name string var money, time int64 // Initializing [3]Users for i := range userArr { fmt.Scan(&name) userArr[i].name = name fmt.Scan(&money) userArr[i].mont...
package mysqldb import ( "time" ) // SemSendStatus 邮件发送状态 type SemSendStatus int32 const ( // Pending 待定 Pending SemSendStatus = 0 // Sending 发送中 Sending SemSendStatus = 1 // SendSucceed 发送成功 SendSucceed SemSendStatus = 2 // SendFailed 发送失败 SendFailed SemSendStatus = 3 ) // Language 语言 type Language string...
package affine_test import ( "testing" "github.com/mkamadeus/cipher/cipher/affine" ) func TestEncrypt(t *testing.T) { plain := "kripto" expected := "CZOLNE" encrypted, err := affine.Encrypt(plain, 7, 10) if err != nil || encrypted != expected { t.Fatalf("affine encryption failed, expected %v, found %v", ex...
package seev import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document03300101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:seev.033.001.01 Document"` Message *CorporateActionInstructionV01 `xml:"CorpActnInstr"` } func (d *Document033...
package main import ( "fmt" "github.com/gorilla/handlers" "github.com/paddycakes/arranmore-api/internal/sensor" transportHTTP "github.com/paddycakes/arranmore-api/internal/transport/http" "log" "net/http" "os" ) // App - the struct which contains things // like pointers to database connections type App struct ...
package httpd // xlattice_go/httpd/name2Hash.go import ( xd "github.com/jddixon/xlOverlay_go/datakeyed" "sync" ) /** * Maintains data structures mapping path names to NodeIDs, which * are used to retrieve data from a MemCache, an in-memory cache of * byte slices. */ type Name2Hash struct { // must implement xo...
/** * Copyright (C) 2019, Xiongfa Li. * All right reserved. * @author xiongfa.li * @date 2019/2/22 * @time 10:42 * @version V1.0 * Description: */ package test import ( "container/list" "fmt" "github.com/xfali/gomem/commonPool" "testing" "time" ) func TestCommonPool(t *testing.T) { p...
package main func ClosurePrint() { for i :=0; i<3; i++{ defer func() {println(i)}() } } /** * Output: * 3 * 3 * 3 */ // 解释: 因为是闭包,在for迭代语句中,每个defer语句延时执行的函数引用都是同一个i迭代变量, // 在循环结束后这个变量的值为3,因此最终输出的结果都是3 /** * Output: * 2 * 1 * 0 */ // 修复思路: 在每轮迭代中为每一个defer语句 的闭包函数生成独有的变量。可以用下面两种方式: func ClosurePrint...
package ykoath import ( "fmt" ) type tv struct { tag byte value []byte } type tvs []tv // read will read a number of tagged values from a buffer func read(buf []byte) (tvs tvs) { var ( idx int length int tag byte value []byte ) for { if len(buf)-idx == 0 { return tvs } // read th...
/* twitter@hector_gool */ package main import ( "fmt" "strings" ) func main() { fmt.Printf("\n En Mayúsculas: %v \n", PasarAMayusculas("pera","uva")) fmt.Printf("\n En Mayúsculas: %v \n", PasarAMayusculas()) fmt.Printf("\n En Mayúsculas: %v \n", PasarAMayusculas("manzana")) frutas := []string{"mango", "sand...
package main import ( "github.com/edaniels/golinters/deferfor" "golang.org/x/tools/go/analysis/singlechecker" ) func main() { singlechecker.Main(deferfor.Analyzer) }
//+build srv1 package main import ( "fmt" "log" "math/rand" "net/http" "time" dd "github.com/gchaincl/dd-go-opentracing" "github.com/gorilla/mux" opentracing "github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go/ext" ) func init() { tracer := dd.NewTracer() tracer.(*dd.Tracer).De...
package main import ( "strconv" "strings" ) // Ex004 takes a string of comma-seperated numbers and returns a slice of int func Ex004(input string) []int { // create a map with the size of n numbers := strings.Split(input, ",") length := len(numbers) var num = make([]int, length) for index, v := range numbers...
package ecal import ( "flag" "fmt" "io/ioutil" "log" "math/rand" "os" "os/user" "strings" "testing" "time" "github.com/cfsalguero/ecal/proto" "gopkg.in/v1/yaml" ) type APIServers struct { APIHostname string `yaml:"ecal-host"` APIKey string `yaml:"ecal-key"` APISecret string `yaml:"ecal-secret"`...
package bitbucket import ( "bytes" "encoding/json" "errors" "io/ioutil" "net/http" "net/url" "github.com/DaoCloud/go-bitbucket/oauth1" ) var ( // Returned if the specified resource does not exist. ErrNotFound = errors.New("Not Found") // Returned if the caller attempts to make a call or modify a resource ...
package utils type XY struct { X int Y int }
package lib_test import ( "accountapi/lib" "testing" ) func TestErrors(t *testing.T) { e := lib.NewErrorInvalidEnum() if !lib.IsErrorInvalidEnum(e) { t.Error("ErrorInvalidNum not recognised.") t.Fail() } eAPI := lib.NewErrorAPI(429, "test_api_error") if !lib.IsErrorAPI(eAPI) { t.Error("ErrorAPI not reco...
package datasetapi import ( "bytes" "context" "io/ioutil" dstypes "github.com/lexis-project/lexis-backend-services-interface-datasets.git/client/data_set_management" models "github.com/lexis-project/lexis-backend-services-api.git/models" "github.com/lexis-project/lexis-backend-services-api.git/restapi/operation...