text
stringlengths
11
4.05M
package flow import ( "context" "fmt" "github.com/direktiv/direktiv/pkg/flow/bytedata" "github.com/direktiv/direktiv/pkg/flow/grpc" "github.com/direktiv/direktiv/pkg/refactor/core" ) func (flow *flow) NamespaceLint(ctx context.Context, req *grpc.NamespaceLintRequest) (*grpc.NamespaceLintResponse, error) { flow...
package main import ( "testing" "fmt" "reflect" "github.com/stretchr/testify/assert" ) type Sample struct { ID int Name string } func TestStruct(t *testing.T) { fmt.Println("struct test....") got := Sample{ ID: 1, Name: "haha", } want := Sample{ ID: 1, Name: "haha", } if !reflect.DeepEqua...
package config import "time" // Parameters for the elevator itself const N_FLOORS = 4 const N_BUTTONS = 3 const DOOR_OPEN_DURATION = 2 const TRAVEL_TIME = 2.5 const MOTOR_STOP_DETECTION_TIME = time.Millisecond * 3000 // For the cab order storage const N_FILE_DUPLICATES = 3 const BACKUP_FILE_PATH = "orderBackup/" //...
package beanstalkd import ( "github.com/kr/beanstalk" "sync" ) type AddrList struct { Addrs []string `toml:"addrs" json:"addrs"` } type Conns struct { sync.RWMutex conns map[string]*beanstalk.Conn } func (cs *Conns) Get(addr string) *beanstalk.Conn { cs.RLock() defer cs.RUnlock() return cs.conns[addr] } f...
package qstring type VisibilityLevel string const ( AnyoneCanFind VisibilityLevel = "anyoneCanFind" AnyoneWithLink VisibilityLevel = "anyoneWithLink" DomainCanFind VisibilityLevel = "domainCanFind" DomainWithLink VisibilityLevel = "domainWithLink" Limited VisibilityLevel = "limited" ) // VisibilityBuil...
package subConfig const ( defaultStartX = 300 defaultStartY = 300 defaultEndX = 900 defaultEndY = 900 ) //Проверяет корректны ли координаты взятые из конфига func CheckCorrectPosition(coordinate []int)[]int{ if !isCorrect(coordinate) { return []int{defaultStartX,defaultStartY,defaultEndX,defaultEndY} } r...
package main import ( "fmt" "net/http" "net/http/pprof" "github.com/gorilla/mux" ) type Routers map[string]func(w http.ResponseWriter, r *http.Request) type Server struct { daemon *Daemon listen_port int router *mux.Router } func NewServer(daemon *Daemon, listen_port int) *Server { server := &Ser...
package x0 import ( "encoding/json" "github.com/valyala/fasthttp" ) const ( PublicInstance = "https://api.x0.tf" PublicStagingInstance = "https://api.s.x0.tf" endpointInfo = "/v2/info" endpointNamespaces = "/v2/namespaces" endpointPartNamespacesResetToken = "/reset_token" endpointElem...
/* * @lc app=leetcode.cn id=58 lang=golang * * [58] 最后一个单词的长度 * * https://leetcode-cn.com/problems/length-of-last-word/description/ * * algorithms * Easy (30.72%) * Likes: 130 * Dislikes: 0 * Total Accepted: 39K * Total Submissions: 126.3K * Testcase Example: '"Hello World"' * * 给定一个仅包含大小写字母和空格 ' ...
package main import "fmt" // Person : Is a regular person type Person struct { First string Last string Age int } // DoubleZero : struct with a stuct inside type DoubleZero struct { Person // anonymous field (just the type here); all the inner types get promoted to the outter type First string...
package sinks import ( "context" "encoding/json" "errors" "fmt" "net/http" "strings" "sync" cclog "github.com/ClusterCockpit/cc-metric-collector/pkg/ccLogger" lp "github.com/ClusterCockpit/cc-metric-collector/pkg/ccMetric" "github.com/gorilla/mux" "github.com/prometheus/client_golang/prometheus" "github.c...
package trigger // Triggers is a facade used to initialize all triggers // passed during initialization. type Triggers struct { triggers []TriggerInterface triggersChan chan bool } // StartTriggers starts triggers in async mode. func (t Triggers) StartTriggers() { for _, trig := range t.triggers { trig.RunAsync(...
package oiio /* #include "stdlib.h" #include "oiio.h" */ import "C" import ( "errors" "runtime" "unsafe" ) // Description of where the pixels live for this ImageBuf type IBStorage int const ( // Derive the file format from the file path name (empty string) FileFormatAuto = "" IBStorageLocalBuffer IBStora...
package main import ( "flag" "fmt" "log" "github.com/streadway/amqp" "github.com/vdntruong/rabbitmq/consumer" "github.com/vdntruong/rabbitmq/publisher" "github.com/vdntruong/rabbitmq/util" ) type ( RabbitConfig struct { User string `envconfig:"RABBIT_USER" default:"admin"` Pass string `envconfig:"RABBIT...
package scheduler import ( "container/heap" "net/rpc" "time" "types" "github.com/golang/glog" ) var ( clustersPriorityQ types.ClustersPriorityQueue clustersPresent map[string]bool clustersActiveQ chan string clustersPodsQ map[string]chan types.InterPod clustersInfo map[string]types.Cluster Id...
package main import "fmt" /* Go supports anonymous functions, which can from closures. */ /* Anonymous functions are useful when you want to define a function inline w/o having to name it */ /* Closures: Los closures son funciones que manejan variables independientes. En otras palabras, la funcion definida en...
package controllers import ( "sdrms/enums" "sdrms/models" "strings" "strconv" "github.com/astaxie/beego/orm" "fmt" "encoding/json" "time" ) type SystemConfigController struct { BaseController } func (c *SystemConfigController) Prepare() { //先执行 c.BaseController.Prepare() //如果一个Controller的多数Action都需要权限控制...
package main import ( "fmt" "io/ioutil" "net/http" "os" "os/signal" "strconv" "syscall" "github.com/docopt/docopt-go" "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/p2p/simulations" "github.com/ethereum/go-ethereum/p2p/simulations/adapters" "github.com/ethereum/go-ethereum/swarm/ap...
// Package bitset implementes bit set operations. package bitset // Bitset represents a fixed-size sequence of bits. type Bitset struct { bit []int32 n int } const shift = 5 const mask = (1 << shift) - 1 // NewBitset creates a Bitset representing n bits. // Panics if n <= 0. func NewBitset(n int) *Bitset { if n...
package pg import ( "github.com/kyleconroy/sqlc/internal/sql/ast" ) type CreateUserMappingStmt struct { User *RoleSpec Servername *string IfNotExists bool Options *ast.List } func (n *CreateUserMappingStmt) Pos() int { return 0 }
package config import ( "os" "strings" "testing" "github.com/stretchr/testify/assert" ) const ( envPort string = "8282" envAllowedOrigins string = "allowed_origins, allowed_origins2" ) func TestMain(m *testing.M) { before() exitResult := m.Run() after() os.Exit(exitResult) } func before() { os...
package main import ( "encoding/base64" "flag" "fmt" "io/ioutil" "log" "net/http" "strings" "time" yaml "gopkg.in/yaml.v2" ) var ( configFile = flag.String("config", "/etc/nginx-ldap-auth/config.yaml", "Configuration file") config = Config{ Web: "0.0.0.0:5555", Path: "/", Message: "LDAP L...
package main import "fmt" func main() { for i := 1; i < 100; i++ { if i%2 == 1 { fmt.Println(i, ": Odd") } else { fmt.Println(i, ": Even") } } } // 1 : Odd // 2 : Even // 3 : Odd // 4 : Even // 5 : Odd // 6 : Even // 7 : Odd // 8 : Even // 9 : Odd // 10 : Even // 11 : Odd // 12 : Even // 13 : Odd // 14...
package zfs import ( "testing" "encoding/json" ) func TestPoolType(t *testing.T) { p := NewPool() t.Log(p) } func Test_PoolOpen(t *testing.T) { pool, err := PoolOpen(*testPool) if err != nil { t.Fatal(err) } t.Log(pool.Features) pool.Close() } func Test_PoolProperties(t *testing.T) { t.Run("read propert...
package controller import ( "errors" "io" "os" "path/filepath" "strings" "tagallery.com/api/config" "tagallery.com/api/logger" "tagallery.com/api/model" "tagallery.com/api/mongodb" "tagallery.com/api/util" ) // GetUnprocessedImages returns unprocessed images from a file directory. // Subdirectories are ign...
package main import ( "fmt" "os" "log" // "portal/config" _ "portal/database" "portal/router" ) // Define init work // Loggin to file func init() { logErr, err := os.OpenFile("error.log", os.O_RDWR|os.O_CREATE, 0755) // logWarn, err := os.OpenFile("warnning.log", os.O_RDWR|os.O_CREATE, 0755) // logInfo, err ...
// 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 main import ( "errors" "fmt" ) type MyError1 struct { Number int Message string } func (e *MyError1) Error() string { return fmt.Sprintf("[%d] %s", e.Number, e.Message) } type MyError2 string func (e *MyError2) Error() string { return string(*e) } func main() { var myError1 *MyError1 var myError2...
package config import ( "encoding/json" "io/ioutil" "fmt" "os" ) type ConfigData struct { ApiToken string `json: apitoken` BaseUrl string `json: baseurl` MongoUrl string `json: mongourl` MongoDb string `json: mongodb` MongoCollection string `json: mongocollection` MongoUser string `json: mongouser` M...
package main import ( "fmt" "log" // "sort" //"flag" "io" "os" "./readers" "./movi" "./output" //"github.com/juanmasg/rtpx/rtpx" //"github.com/juanmasg/rtpx/rtpx/routers" "./rtpx" "./rtpx/routers" "golang.org/x/net/webdav" "net/http" //"net/url" //"git...
package main import ( "context" "crypto/tls" "crypto/x509" "fmt" "io/ioutil" "math" "net" "net/http" "time" "github.com/go-kit/kit/log" "github.com/go-kit/kit/log/level" "github.com/grpc-ecosystem/go-grpc-middleware" "github.com/grpc-ecosystem/go-grpc-prometheus" "github.com/improbable-eng/thanos/pkg/cl...
package clair import ( "encoding/json" "fmt" "net/http" ) func Versions() (interface{}, error) { Config() response, err := http.Get(uri + "/versions") if err != nil { return nil, fmt.Errorf("requesting Clair version: %v", err) } defer response.Body.Close() var versionBody interface{} err = json.NewDecode...
package handler import ( "net/http" "github.com/labstack/echo" ) func (h *Handler) Version(c echo.Context) error { version := map[string]string{ "version": h.conf.AppVersion, } return c.JSON(http.StatusOK, version) }
package m3u8 import ( "fmt" "net/url" "path" "stayreal/httputils" "stayreal/ioutils" "time" ) //callbacks type OnNewM3u8 func(puller *StreamPuller, m3u8Info *M3u8Info) type OnNewTs func(puller *StreamPuller, tsInfo *TsInfo) type OnPullError func(puller *StreamPuller, err error) type StreamPuller struct { key ...
package quiz import ( "testing" "fmt" "runtime" "strings" ) func Test(t *testing.T) *tester { return &tester{t} } type tester struct { *testing.T } func (t *tester) Expect(target interface{}) *expectation { return &expectation{t: t, target: target} } type expectation struct { t *tester target interface{} ...
/* We see a lot of challenges here asking for a function to create a sequence from the OEIS. While these challenges are fun, as a programmer I see an opportunity for automation. Your challenge is to make a program that takes the index of a sequence (e.g. A172141) and some integer n (e.g. 7), and pulls the appropriate...
package raft import ( "math/rand" "time" ) func getRandomTimeout(lowerBound, upperBound time.Duration) time.Duration { timeRange := upperBound - lowerBound variance := rand.Int63n(timeRange.Milliseconds()) return lowerBound + time.Duration(variance)*time.Millisecond } // Returns a strict majority func majority(...
package main // CLIENT import ( "fmt" "io" "io/ioutil" "log" "net" "os" "strings" ) func main() { conn, err := net.Dial("tcp", "Localhost:3000") if err != nil { log.Fatalln(err) } go func(conn net.Conn) { buffer := make([]byte, 1400) for { //Приём dataSize, err := conn.Read(buffer) data := buff...
package extensions import ( "context" "fmt" "strings" "unicode" core "github.com/semi-technologies/contextionary/contextionary/core" "github.com/semi-technologies/contextionary/errors" "github.com/sirupsen/logrus" ) type Vectorizer interface { Corpi(corpi []string, overrides map[string]string) (*core.Vector,...
package storeutil import "fmt" type ListenerRegistry struct { listeners map[interface{}]func() } func NewListenerRegistry() *ListenerRegistry { return &ListenerRegistry{ listeners: make(map[interface{}]func()), } } func (r *ListenerRegistry) Add(key interface{}, listener func()) { if key == nil { key = new(...
package raftkv import ( "labgob" "labrpc" "log" "raft" "sync" ) const Debug = 0 func DPrintf(format string, a ...interface{}) (n int, err error) { if Debug > 0 { log.Printf(format, a...) } return } type Op struct { Name string // Either "Get", "Put", or "Append" ClientId int64 RequestId int64 Ke...
package main import ( "context" "encoding/json" "fmt" "io/ioutil" "net/http" "strings" "time" "../../internal/db" "github.com/google/uuid" "github.com/rs/zerolog/log" ) func (cmd *EstimateCmd) GenerateEstimates(ctx context.Context, dbHandle *db.Handle) error { start := time.Now() // TODO: get our prope...
package stats_test import ( "testing" "github.com/facebookgo/ensure" "github.com/facebookgo/stats" ) // Ensure calling End works even when a BumpTimeHook isn't provided. func TestHookClientBumpTime(t *testing.T) { (&stats.HookClient{}).BumpTime("foo").End() } func TestPrefixClient(t *testing.T) { const ( pre...
package main import ( "fmt" game "../Game" ) func main() { fmt.Println("Game started!") good := 0 bad := 0 for i := 0; i < 1; i++ { if game.Start() { good++ } else { bad++ } } fmt.Printf("good rate = %.3f%%, bad rate = %.3f%%\n", float64(good)/float64(good+bad)*100, float64(bad)/float64(go...
package model import ( "gopkg.in/mgo.v2" ) type Model interface { Save(session *mgo.Session) }
package main import ( "fmt" "strconv" ) func reverse(num int) int { str := strconv.Itoa(num) runes := []rune(str) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } i, _ := strconv.Atoi(string(runes)) return i } func findPali(lim int) int { for i := lim - 1; i ...
package base import ( "backend/article" "backend/base/ws" "backend/middlewares/casbin" "backend/middlewares/jwt" "backend/middlewares/recover" "backend/user" "backend/utils/setting" "github.com/gin-gonic/gin" ginSwagger "github.com/swaggo/gin-swagger" _ "github.com/swaggo/gin-swagger/example/basic/docs" "gi...
package models func (l *CommentListing) GetChildren() []Comment { return l.Data.Children } func (ldc Comment) GetId() string { return ldc.Data.Name } func (ldc Comment) GetParentId() string { return ldc.Data.ParentId } func (ldc Comment) IsRoot() bool { return string(ldc.Data.Pa...
// +build !windows package fetch func (c *Client) fetchDump(verPlayer, verStudio string, dump, meta io.Writer) error { return NoSupportError }
package collections import ( "reflect" "testing" ) func TestLowerCaseData(t *testing.T) { type args struct { w WorkWith } tests := []struct { name string args args want WorkWith }{ {"base-case", args{WorkWith{"Test", 0}}, WorkWith{"test", 0}}, } for _, tt := range tests { t.Run(tt.name, func(t *te...
package configure import ( contextpkg "context" "fmt" "os/exec" "regexp" "strings" "github.com/devspace-cloud/devspace/pkg/devspace/build/builder/helper" cloudconfig "github.com/devspace-cloud/devspace/pkg/devspace/cloud/config" "github.com/devspace-cloud/devspace/pkg/devspace/config/versions/latest" v1 "git...
// 1、切片的引入 // (1)切片是引用类型 // (2)切片使用类似于数组(len、range、) // (3)切片长度可以动态变化 // (4)切片定义 跟数组一定要分清~~~ // var 切片名 [] 数据类型 // 举例:var arr []int package main import ( "fmt" ) func main() { // 数组 var intArr [5]int = [...]int{1, 23, 55, 7, 6} // 声明定义一个切片~ slice := intArr[1:3] // 引用intArr数组中下表从1到3的数字,其中不包含index3 // [1:3] ...
// Copyright 2019 The OpenSDS 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 agre...
package main import "testing" func TestNewEntity(t *testing.T) { entity := NewEntity("") if entity == nil { t.Fail() } } func TestEntityMove(t *testing.T) { entity := NewEntity("") entity.Move(NewPoint(5, 5)) if entity.position.x != 5 || entity.position.y != 5 { t.Fail() } }
package projection import "github.com/satori/go.uuid" type Account struct { ID uuid.UUID Identities []uuid.UUID }
// Package avltree 实现AVL实现的平衡搜索树 package avltree const ( avlBlanced = 0 avlLeftHeavy = 1 avlRightHeavy = -1 ) // Comparation 比较函数类型 type Comparation = func(a, b interface{}) int // Node Avl 树节点 type Node struct { data interface{} factor int // 平衡因子 hidden bool // 是否已删除 left, right *Node ...
package fuzzempty // FuzzEmpty is an empty placeholder fuzzing function func FuzzEmpty(data []byte) int { return 0 } // FuzzAnotherEmpty is another empty placeholder fuzzing function func FuzzAnotherEmpty(data []byte) int { return 0 }
package main import ( "github.com/rohandas-max/admybrand/database" "github.com/rohandas-max/admybrand/router" ) func main() { database.Connection() routes := router.Router() routes.Run(":4000") }
package helper import ( "bufio" "strconv" ) func ReadLine(r *bufio.Reader) (string, error) { var ( isPrefix bool = true err error = nil line, ln []byte ) for isPrefix && err == nil { line, isPrefix, err = r.ReadLine() ln = append(ln, line...) } return string(ln), err } func Slice_Atoi(strArr [...
package singleton import "sync" var ( instance Singleton once sync.Once ) // Singleton provides singleton's interface type Singleton interface { DoWork() SetName(name string) SetAge(age int) GetName() string GetAge() int } type singleton struct { name string age int } // DoWork does a work via singleton (...
package docker import ( "context" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/client" ) func RunContainer() { ctx := context.Background() cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation()) if err != nil { ...
package main import "fmt" func main() { var x interface{} x = 100 switch x.(type) { case int: fmt.Println("Integer!") case string: fmt.Println("String") } }
package configuration_test import ( "errors" "fmt" "github.com/efark/data-receiver/configuration" "os" "path" "strings" "testing" ) var baseFilepath = "./test_config" var jsonContent = `{"services": {"test_service": {"extractor": {"type": "HeaderExtractor"}, "authenticator": {"type": "Signer", "parameters": {"...
package tools import ( "io/ioutil" "os" "sort" "testing" ) func TestReadFile(t *testing.T) { cases := []struct { in string out []string }{ {"first line\nsecond line\nthird line", []string{"first line", "second line", "third line"}}, {"first line\nsecond line\nthird line\n", []string{"first line",...
package handler import ( "context" analysispb "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/analysis/v1" generalpb "github.com/jinmukeji/proto/v3/gen/micro/idl/ptypes/v2" ) // UpdateAnalyzeStatus 更新分析的状态 func (j *AnalysisManagerService) UpdateAnalyzeStatus(ctx context.Context, req *analysispb.UpdateAn...
// miscellaneous utility functions used for the landing page of the application package drafts import ( "glsamaker/pkg/models" "glsamaker/pkg/models/users" "html/template" "net/http" ) // renderIndexTemplate renders all templates used for the landing page func renderDraftsTemplate(w http.ResponseWriter, user *us...
package ws import ( "github.com/gorilla/websocket" ) const ( // CreateEvent is the event name for creating a new game room CreateEvent = "create" // JoinEvent is the event for joining an existing game room JoinEvent = "join" // DataEvent is the event for sending data inside a game room DataEvent = "data" // J...
package data import( "fmt" ) const insert_user=` insert into useritem(openid,session_key,nickname,avatarurl,gender,lang,city,province,country,email,phone,addresses) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) ` const map_string=` {"openId":"%s",""} ` const mat_return_weichat=` {"userId":%d,"nickname":"%s","avataru...
package main import ( "io" "log" "net/http" ) func main() { //设置路由 访问规则 http.HandleFunc("/", sayHello) /* 第一个参数是rootpath 第二个参数是指定接收什么参数运行*/ err := http.ListenAndServe(":8080", nil) //传入nil 是默认的handler if err != nil { log.Fatal(err) } } func sayHello(w http.ResponseWriter, r *http.Request) { io...
package events import ( "encoding/json" "fmt" "io/ioutil" "net/http" "os" "time" ) type Events struct { Events []Event } type Event struct { ID string `json:"_id"` Name string `json:"name"` EntityID string `json:"entity_id"` Version int64 `json:"version"` Payload string `...
package oauth import ( "encoding/json" "fmt" "net/url" "github.com/MrCHI/gowechat/util" "github.com/MrCHI/gowechat/wxcontext" ) const ( redirectOauthURL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%v&redirect_uri=%v&response_type=%v&scope=%v&state=%v&component_appid=%v#wechat_redirect" a...
package routers import ( "ss-backend/controllers" "github.com/astaxie/beego" ) func init() { beego.Router("/", &controllers.MainController{}) ns := beego.NewNamespace("/v1", beego.NSRouter("/product", &controllers.ProductController{}, "get:Get", ), beego.NSRouter("/product", &controllers.ProductC...
package keeper import ( sdk "github.com/ColorPlatform/color-sdk/types" "github.com/ColorPlatform/color-sdk/x/staking/types" ) // SetCouncilMember set a council member func (k Keeper) SetCouncilMember(ctx sdk.Context, member types.CouncilMember) { store := ctx.KVStore(k.storeKey) b := types.MustMarshalCouncilMembe...
package config const ( RestServiceName = "com.salpadding.api.srv" )
package apis import ( "github.com/deepinbytes/go-blog/app" "github.com/deepinbytes/go-blog/models" "github.com/go-ozzo/ozzo-routing" "strconv" ) type ( // articleService specifies the interface for the article service needed by articleResource. articleService interface { Get(rs app.RequestScope, id int) (*mod...
/* Package fishbone automatically rewrites the behavior based on KeysOnly + Get by Key when Run or GetAll Query, contributing to reducing the amount of charge. If you use Run or GetAll with Query, you will be charged for Small Operations + Entity Reads as you retrieve all Entities from Datastore. We decompose this auto...
package kcpNetwork import ( "context" kcp "github.com/xtaci/kcp-go/v5" "github.com/yaice-rx/yaice/network" "strconv" "sync" "sync/atomic" ) type Server struct { sync.Mutex type_ network.ServeType connCount int32 listener *kcp.Listener cancel context.CancelFunc ctx context.Context } func New...
package main import ( "fmt" "geerpc" "log" "net" "sync" "time" ) func startServer(addr chan string) { // pick a free port l, err := net.Listen("tcp", ":0") if err != nil { log.Fatal("network error:", err) } log.Println("start rpc server on", l.Addr()) addr <- l.Addr().String() geerpc.Accept(l) } func ...
package main import ( "bufio" "encoding/json" "flag" "fmt" "github.com/confluentinc/confluent-kafka-go/kafka" log "github.com/sirupsen/logrus" "os" "strings" ) var requestMaxSize = flag.Int("MaxRequestSize", 1000000, "sarama.MaxRequestSize") var brokerList = flag.String("BrokerList", "", "Comma seperated list...
// Considerando os tópicos que já aprendemos até agora: slices, structs ,condicionais e laços de repetição, crie um programa que traga as informações sobre apartamentos de um prédio. Passos: // 1) Crie uma estrutura que representa um apartamento, com campos para representar seu número, o nome da sua proprietária e se t...
package main import ( // "io" "fmt" "math" // "unsafe" ) func interp() { ip = start /* fmt.Printf(" startup r1 %v r2 %v wa %v wb %v wc %v xl %v xr %v xs %v cp %v ia %v\n", reg[r1], reg[r2], reg[wa], reg[wb], reg[wc], reg[xl], reg[xr], reg[xs], reg[cp],int32(reg[ia])) fmt.Printf("start interp m...
package sql import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" config "github.com/alexhornbake/go-crud-api/config" log "github.com/alexhornbake/go-crud-api/lib/logging" ) var DB *sql.DB // This is OK to detect not ready during initialization. // How reliable is the connection pool? and how does i...
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "os" "os/exec" "syscall" "github.com/opencontainers/runtime-spec/specs-go" "github.com/pelletier/go-toml" ) const ( configFilePath = "/etc/nvidia-container-runtime/config.toml" hookDefaultFilePath = "/usr/bin/nvidia-container-runtime-hook"...
package propertypublickey import ( "fmt" vocab "github.com/go-fed/activity/streams/vocab" "net/url" ) // ActivityStreamsPublicKeyProperty is the functional property "publicKey". It is // permitted to be a single nilable value type. type ActivityStreamsPublicKeyProperty struct { activitystreamsPublicKeyMember voca...
package main import ( "flag" "fmt" "os" "./network/bcast" "./network/localip" "./network/peers" . "./config" "./control" "./esm" com "./network/communication" "./driver/elevio" ) func initialize_elevator_system() (int,string){ port := os.Args[1] var id string flag.StringVar(&id, "id", "", "id of this pee...
package machine import ( "path/filepath" "github.com/pkg/errors" "github.com/sirupsen/logrus" "sigs.k8s.io/yaml" "github.com/openshift/installer/pkg/asset" "github.com/openshift/installer/pkg/asset/ignition" "github.com/openshift/installer/pkg/asset/installconfig" "github.com/openshift/installer/pkg/asset/tl...
package main import ( "math/rand" "os" "time" "github.com/erocheleau/uabot/scenariolib" "github.com/k0kubun/pp" ) const ( // USERAGENT This is the user agent the bot appears to be using. USERAGENT string = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/...
package main import ( "regexp" "github.com/google/uuid" "golang.org/x/crypto/bcrypt" ) type Role int8 const ( UserRole Role = 0 AdminRole Role = 1 ) type User struct { ID uuid.UUID `json:"id"` Name string `json:"name"` Email string `json:"email"` Password []byte `json:"password"` R...
package summultiples // SumMultiples returns the sum of the multiples of all the natural numbers up to the limit func SumMultiples(limit int, divs ...int) int { var sum int var numbersSummed = make([]bool, limit) for _, divisor := range divs { for i := divisor; i < limit; i += divisor { if !numbersSummed[i] { ...
package shell import ( "testing" "github.com/stretchr/testify/assert" ) func TestGetURLShouldUseSlashWhenNoArgs(t *testing.T) { e := newEnv() u, err := getURL(e, nil) assert.Nil(t, err) assert.Equal(t, "http://localhost:3000/", u.String()) } func TestGetURLShouldUseURLFromArgsWhenPresent(t *testing.T) { e :=...
// Copyright 2019 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package cmd import ( "io/ioutil" "os" "testing" _ "github.com/mattn/go-sqlite3" "github.com/stretchr/testify/assert" ) func TestReverseSimple(t *testi...
package main import ( "database/sql" "net/http" _ "github.com/lib/pq" ) func containerReplicasByBarge(r *http.Request) *Response { query := ` SELECT "barge", SUM("replicas") AS "count" FROM "Providers" WHERE "replicas" > 0 AND "barge" NOT LIKE '%test%' GROUP BY "barge" ORDER BY "count" DESC ; ` var results ...
package recover import ( "backend/utils/logging" "backend/utils/response" "github.com/gin-gonic/gin" "net/http" ) func Recover(c *gin.Context) { defer func() { if r := recover(); r != nil { //打印错误堆栈信息 logging.Error("panic: %v\n", r) //debug.PrintStack() //封装通用json返回 //c.JSON(http.StatusOK, Resul...
package main import ( "fmt" ) // 589. N叉树的前序遍历 // https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/ func main() { tree := &Node{ Val: 1, Children: []*Node{ {3, []*Node{ {5, nil}, {6, nil}, }}, {2, nil}, {4, nil}, }, } fmt.Println(preorder(tree)) fmt.Println(preorder2(tree...
// REF: https://github.com/google/logger package main import ( "errors" "flag" "os" "github.com/google/logger" ) var LogFile *os.File func init() { var verbose = flag.Bool("verbose", false, "print info level logs to stdout") var logPath string if wd, err := os.Getwd(); err != nil { panic(err) } else { ...
// Copyright 2020 Readium Foundation. All rights reserved. // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file exposed on Github (readium) in the project repository. package licensestatuses import ( "database/sql" "errors" "log" "strings" "time" "github.com/re...
package pg import ( "github.com/kyleconroy/sqlc/internal/sql/ast" ) type AlterDomainStmt struct { Subtype byte TypeName *ast.List Name *string Def ast.Node Behavior DropBehavior MissingOk bool } func (n *AlterDomainStmt) Pos() int { return 0 }
/** * Author: Admiral Helmut * Created: 12.06.2019 * * (C) **/ package dbprovider import ( "database/sql" "fmt" "github.com/efi4st/efi4st/classes" "github.com/efi4st/efi4st/dbUtils" "github.com/efi4st/efi4st/utils" _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx" "log" "sort" "strconv"...
package cache import ( "testing" ) func TestSet(t *testing.T) { Set("foo", "bar", 1) value, ok := Get("foo") if ok { ret := value.(string) if ret != "bar" { t.Error("get data wrong:%s", ret) } } else { t.Error("get nil data") } }
package main import ( "fmt" "os" ) // PathError records an error and the operation and file path that caused it type PathError struct { Op string Path string Err error } func (e *PathError) Error() string { return e.Op + " " + e.Path + ": " + e.Error() } func main() { _, err := os.Open("no/such/file") fm...