text
stringlengths
11
4.05M
package main import ( "testing" ) func Test_CLI(t *testing.T) { versionCommand := VersionCommand{} if err := versionCommand.Execute([]string{}); err != nil { t.Fail() } }
// Copyright 2018 The gVisor 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 agree...
package store import ( "testing" "github.com/skoltai/limithandling/domain" "github.com/stretchr/testify/assert" ) func TestAddUser(t *testing.T) { store := NewMemoryStore() r := NewSimpleUserRepository(store) user := domain.User{Username: "admin", Email: "admin@admin.com"} id := r.Create(user) got, _ := r.G...
package tests import ( "testing" "github.com/stretchr/testify/assert" ) func existsTestCheckIfDocumentExists(t *testing.T, driver *RavenTestDriver) { var err error store := driver.getDocumentStoreMust(t) defer store.Close() { session := openSessionMust(t, store) assert.NoError(t, err) idan := &User{} ...
package logger import ( "log" ) var console *consoleLog type consoleLog struct { log *log.Logger } func (f *consoleLog) info(logs ...interface{}) { f.log.SetPrefix("[api-debug] info ") f.log.Println(logs...) } func (f *consoleLog) error(logs ...interface{}) { f.log.SetPrefix("[api-debug] error ") f.log.Print...
package middlewares import ( "github.com/gin-gonic/gin" "github.com/sirupsen/logrus" ginlogrus "github.com/toorop/gin-logrus" ) // Setup is a function for setting up middlewares func Setup(engine *gin.Engine) { logger := logrus.New() engine.Use(gin.Recovery()) engine.Use(ginlogrus.Logger(logger)) }
package alert import ( "github.com/CityOfNewYork/prisma-cloud-remediation/events" ) const ( DetachInternetGateway = "DetachInternetGateway" DeleteInternetGateway = "DeleteInternetGateway" DeleteSubnet = "DeleteSubnet" DeleteVpc = "DeleteVpc" Virginia = "us-east-1" ) // FalseAl...
// Package mta provides a convenient way of exploring the structure of `mta.yaml` file objects // such as retrieving a list of resources required by a specific module. package mta import ( "bytes" "fmt" yamlv2 "gopkg.in/yaml.v2" "gopkg.in/yaml.v3" ) // GetModules returns a list of MTA modules. func (mta *MTA) Get...
package cmd import ( "github.com/NinjaAung/nere/modules" "github.com/spf13/cobra" ) // createCmd represents the create command var createCmd = &cobra.Command{ Use: "create [repo name]", Short: "This command will create a repository for the user", Long: `create will make a repository with any provided attribut...
package runtime // List data type (Sequence) type List struct { // Otherwise behaves like a ConsCell *ConsCell // Retain a pointer to the last element in the list Last *List } var EmptyList = &List{} func (lst *List) Type() Type { return ListType } func (lst *List) Eval(env Env) (Value, error) { if lst.Empty(...
package store import "github.com/p4thf1nderr/lms/internal/app/model" // BookRepository ... type BookRepository interface { Create(*model.Book) error Index() ([]model.Book, error) }
package commands import ( "eurogo/flights/skyscanner" "log" ) type AirportCommand struct { Args airportPositionalArgs `positional-args:"1" required:"1"` } type airportPositionalArgs struct { Query string `positional-arg-name:"<query>"` } func (cmd *AirportCommand) Execute(args []string) error { provider := sk...
package postgres import ( "database/sql" "strings" ) func Open(connectionString map[string]string) (*sql.DB, error) { return sql.Open("postgres", createConnectionString(connectionString)) } func createConnectionString(values map[string]string) string { // https://www.postgresql.org/docs/10/libpq-connect.html#id-...
package main import ( "flag" "fmt" "log" "math" "net/url" "os" "strconv" "sync" "sync/atomic" "syscall" "time" "github.com/gorilla/websocket" "github.com/olekukonko/tablewriter" ) type Record struct { Number int Connections int Errors int Duration float64 } var open int64 var concurren...
package engine import ( "fmt" "strconv" "time" ) type engine struct { storage map[string]valueStoreInterface } type Engine interface { Get(key string) (*string, error) Set(key string, value string) error Del(keys []string) (int64, error) Exists(keys []string) (int64, error) Incr(key string) (int64, error) ...
package router import ( "github.com/gogf/gf/frame/g" "github.com/gogf/gf/net/ghttp" "golang-coding/app/api" ) func init() { s := g.Server() s.Group("/", func(group *ghttp.RouterGroup) { group.GET("/", api.Hello.Index) group.GET("/ping", api.Hello.Ping) }) }
package confirm_test import ( "net/http" "net/http/httptest" "testing" "time" "github.com/jrapoport/gothic/core/context" "github.com/jrapoport/gothic/hosts/rest" "github.com/jrapoport/gothic/hosts/rest/user/confirm" "github.com/jrapoport/gothic/mail/template" "github.com/jrapoport/gothic/test/tconf" "github...
package api import ( "encoding/json" "errors" "github.com/gorilla/mux" "log" "net/http" ) func RegisterRoutes(router *mux.Router) error { router.HandleFunc("/api/profile/{uuid}", getProfile).Methods(http.MethodGet, http.MethodOptions) router.HandleFunc("/api/profile/{uuid}", updateProfile).Methods(http.MethodP...
package certificateservices import ( "context" "github.com/superchalupa/sailfish/src/ocp/view" domain "github.com/superchalupa/sailfish/src/redfishresource" eh "github.com/looplab/eventhorizon" ) func AddAggregate(ctx context.Context, v *view.View, baseUri string, ch eh.CommandHandler) (ret eh.UUID) { ret = eh...
package utils import ( "encoding/csv" "os" ) func ReportToCSV(filename string, data [][]string) { file, err := os.Create(filename) CheckError(err, "[report-ReportToCSV] failed to open csv file") defer file.Close() writer := csv.NewWriter(file) defer writer.Flush() for _, el := range data { err := writer.W...
package main import ( "fmt" "net/http" "os" "golang.org/x/net/html" "book/ch05" ) func main() { if len(os.Args) < 2 { fmt.Fprintln(os.Stderr, "usage: parse URL\n") os.Exit(1) } resp, err := http.Get(os.Args[1]) if err != nil { fmt.Fprintf(os.Stderr, "parse: %v\n", err) os.Exit(1) } defer resp.Bod...
package glinks import ( "bufio" "log" "os" "strings" "time" ) type VmstatData struct { Stats map[string]int Time time.Time } func (d VmstatData) SampleTime() int64 { return d.Time.Unix() } func VmstatLoad() VmstatData { vmstatFile := "/proc/vmstat" file, err := os.Open(vmstatFile) // for testing on no...
package bst type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func postorderTraversal(root *TreeNode) []int { result := new([]int) search(root, result) return *result } func search(root *TreeNode, result *[]int) { if root == nil { return } search(root.Left, result) search(root.Right, res...
package lotus import ( "context" "github.com/kenlabs/pando/pkg/registry" "github.com/kenlabs/pando/pkg/registry/discovery" "github.com/libp2p/go-libp2p-core/peer" . "github.com/smartystreets/goconvey/convey" "math/big" "testing" ) const testMinerAddr = "t01000" func TestDiscoverMock(t *testing.T) { Convey("t...
// problem #108 (https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) package leetcode func SortedArrayToBST(nums []int) *TreeNode { if len(nums) == 0 { return nil } m := len(nums) / 2 root := TreeNode{Val: nums[m]} insertLeft(&root, nums[:m]) insertRight(&root, nums[m+1:]) return &root...
package dynamic_bosh_config_test import ( "testing" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/pborman/uuid" bosh "github.com/pivotal-cf/on-demand-service-broker/system_tests/test_helpers/bosh_helpers" "github.com/pivotal-cf/on-demand-service-broker/system_tests/test_helpers/service_he...
package game import ( "board" "fmt" "player" "visualizer" ) type Game struct { board *board.Board p0 *player.Player p1 *player.Player visualizer *visualizer.Visualizer } func (g *Game) Init(NRows int, NCols int, p0 player.Player, p1 player.Player, v visualizer.Visualizer) error { if NCols <...
package graphics import ( "github.com/Gregmus2/simple-engine/common" "github.com/go-gl/glfw/v3.3/glfw" "github.com/pkg/errors" ) func NewWindow() (*glfw.Window, error) { if err := glfw.Init(); err != nil { return nil, errors.Wrap(err, "failed to initialize glfw") } glfw.WindowHint(glfw.Resizable, glfw.False)...
package message import ( "github.com/sudachen/coin-exchange/exchange" "time" ) type Kline struct { Timestamp time.Time Interval int32 TradeNum int32 Open float32 Close float32 High float32 Low float32 Volume float32 } type Candlestick struct { Origin exchange.Exchange Pair exchange.CoinPair ...
package kanji import ( "bufio" "log" "os" "strings" "testing" ) func TestIsForPersonalNames(t *testing.T) { f, err := os.Open("./testdata/golden_jinmei.txt") if err != nil { t.Fatalf("unexpected error, %v", err) } defer f.Close() s := bufio.NewScanner(f) s.Scan() line := s.Text() if !strings.HasPrefix(...
package ezrpc import ( "bytes" "errors" "strings" "time" "github.com/Wuvist/go-thrift/thrift" "github.com/nats-io/nats" ) type OnewayRequest interface { Oneway() bool } type Client struct { cfg *Config Conn *nats.Conn Service string DirectKey string } func NewClient(service string, conn *na...
package datasource type DataSource interface { Value(key string) (any, error) } type DataStore interface { DataSource Store(key string, value any) error } type LocalDataSource struct { } func NewLocalDataSource(db, cache DataStore) *LocalDataSource { return &LocalDataSource{} } func (lds *LocalDataSource) Valu...
// Use strings.Builder // Builder: Design a html builder // Builder Facet: Design a PersonBuilder, PersonJobBuilder, PersonAddressBuilder // Builder Parameter: Design an EmailBuilder => func SendEmail(action func(b *EmailBuilder) {}) // Functional Builder: Design PersonBuilder combining Facet with Builder Parameter for...
/** * All Rights Reserved * This software is proprietary information of Akurey * Use is subject to license terms. * Filename: user.routes.go * * Author: rnavarro@akurey.com * Description: Declares all User routes */ package routes import ( "database/sql" "github.com/gorilla/mux" "controllers" ) const ( USER_PA...
package gocosmos import ( "database/sql" "database/sql/driver" "encoding/binary" "errors" "net" "strings" "time" "github.com/btnguyen2k/consu/olaf" ) var idGen *olaf.Olaf func _myCurrentIp() (string, error) { if addrs, err := net.InterfaceAddrs(); err == nil { for _, address := range addrs { if ipnet,...
package web import ( "database/sql" "fmt" "time" "../config" // _ "github.com/go-sql-driver/mysql" ) var db *sql.DB func init() { db, _ = sql.Open("mysql", config.DB) // mysql image starts need time. for { err := db.Ping() if err == nil { break } fmt.Println(err) time.Sleep(2 * time.Second) ...
package main import "fmt" func main() { //divide by x fmt.Println(Divide(100, 0)) } //Divide testing go doc func Divide(x, y float64) float64 { return (x / y) } //now im going to create an automated test and test dividing by 0
// Copyright (C) 2017 Google 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 t...
package main /* 旋转链表, 将每个节点向右移k位置 */ type ListNode struct { Val int Next *ListNode } func rotateRight(head *ListNode, k int) *ListNode { if head == nil { return head } tail := head length := 1 //计算链表长度 for tail.Next != nil { tail = tail.Next length++ } //连成环 tail.Next = head for i := 0; i < len...
package model // Service describes a backend service. // // The fields of this struct have the meaning described in v2.0.0 of the OONI // bouncer specification defined by // https://github.com/ooni/spec/blob/master/backends/bk-004-bouncer.md. type Service struct { // Address is the address of the server. Address str...
package model import ( "errors" "github.com/gogf/gf/database/gdb" ) type UserRoles struct { Roles []string `json:"roles"` } // { // roles: ['admin'], // introduction: 'I am a super administrator', // avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif', // name: 'Super Adm...
package lc // Time: O(n^2) // Benchmark: 72ms 5.8mb | 23% 97% // Optimizations include: // - skipping over current height * (length-i) is less than max // - breaking second for loop if we encounter height that is equal or taller. func maxAreaB(height []int) int { var max int for i := 0; i < len(height)-1; i++ { i...
// Copyright 2015 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package cache import ( "github.com/allegro/bigcache" "github.com/kosotd/go-microservice-skeleton/config" "github.com/kosotd/go-microservice-skeleton/utils" "github.com/pkg/errors" "sync" ) var cache *bigcache.BigCache var once sync.Once var initialized int func InitBigCache() { once.Do(func() { defaultConfig...
package handlers /* 文件夹相关操作 */ //AgentCreateFolder 创建文件夹 /* 参数 folderID 文件夹ID folderLabel 文件夹标签 folderCreatePath 文件夹创建路径 */ func AgentCreateFolder(folderID, folderLabel, folderCreatePath string) (bool, error) { return true, nil } //AgentRemoveFolder 移除文件夹 /* folderID 文件夹ID */ func AgentRemoveFolder(folderI...
package currenttime import ( "time" "github.com/gin-gonic/gin" ) // GetTime Get current time as time server func GetTime(c *gin.Context) { c.JSON(200, gin.H{ "message": time.Now().Unix(), }) }
package solutions func lexicalOrder(n int) []int { result := []int{1} number := 1 for i := 1; i < n; i++ { number = next(number, n) result = append(result, number) } return result } func next(i int, n int) int { if i * 10 <= n { return i * 10 } if i + 1 <= n ...
package main import ( "fmt" "go/token" "github.com/go-toolsmith/strparse" "github.com/go-toolsmith/pkgload" "golang.org/x/tools/go/packages" ) func zmain() { d := strparse.Decl("func foo() {}") fmt.Println(d) fmt.Println(strparse.BadDecl) fmt.Println(d == strparse.BadDecl) } func fmain() { fset := tok...
package mesos_master import ( "github.com/wndhydrnt/proxym/types" ) type MesosMasterServiceGenerator struct { config *Config leaderRegistry *leaderRegistry } func (m *MesosMasterServiceGenerator) Generate() ([]*types.Service, error) { host := m.leaderRegistry.get() if host.Ip == "" { return []*types....
package reporter import ( "bufio" "bytes" "encoding/json" "fmt" "html/template" "log" "os" "strings" "time" "github.com/sromku/go-gitter" ) // Exporter performs conversion from log file to html type Exporter struct { ExporterParams location *time.Location } // ExporterParams for locations type ExporterP...
package models import( "encoding/json" ) /** * Type definition for LogicalVolumeTypeEnum enum */ type LogicalVolumeTypeEnum int /** * Value collection for LogicalVolumeTypeEnum enum */ const ( LogicalVolumeType_KSIMPLEVOLUME LogicalVolumeTypeEnum = 1 + iota LogicalVolumeType_KLVM ...
package httpclient import ( "bytes" "io" "io/ioutil" "net/http" "time" "github.com/airbloc/logger" "github.com/pkg/errors" ) type logTransport struct { transport http.RoundTripper logger logger.Logger } func (t logTransport) RoundTrip(req *http.Request) (*http.Response, error) { timer := time.Now() re...
package framework import ( "fmt" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" configv1 "github.com/openshift/api/config/v1" ) const ( ClusterVersionName = "version" ) func addCompomentOverride(overrides []configv1.ComponentOverride, override configv1.ComponentOverride) ([...
package models import( "encoding/json" ) /** * Type definition for PureTypeEnum enum */ type PureTypeEnum int /** * Value collection for PureTypeEnum enum */ const ( PureType_KSTORAGEARRAY PureTypeEnum = 1 + iota PureType_KVOLUME ) func (r PureTypeEnum) MarshalJSON() ([]byte, erro...
package main import ( "fmt" ) func main() { c := map[string]int{} for i := 0; i < 100; i++ { go func () { for j := 0; j < 100000; j++ { c[fmt.Sprintf("%d", j)] = j } }() } }
package controllers import ( "beegoBlog/models" "beegoBlog/utils" //"github.com/astaxie/beego" "strconv" ) /** * 文章列表 */ func (this *AdminController) List() { this.Data["Page_title"] = "文章列表" this.Data["Is_list"] = true page, _ := this.GetInt(":page") cnt := posts.Count() var getStart int64 this.Data["No...
// Copyright (C)2018 by Lei Peng <pyp126@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify,...
package logs import ( "fmt" "testing" "time" ) func TestFormat(t *testing.T) { now := time.Now() a, d, h := formatTimeHeader(now) fmt.Println(string(a), d, h) }
package models import "github.com/garyburd/redigo/redis" var c redis.Conn func init() { var err error c, err = redis.Dial("tcp", ":6379") if err != nil { panic(err) } }
package migrations import( . "github.com/ssok8s/ssok8s/pkg/services/sqlstore/migrator" ) func addSsoReviewerMigrations(mg *Migrator){ ssoReviewerTable := Table{ Name:"sso_reviewer", Columns:[]*Column{ {Name: "id", Type: DB_BigInt, IsPrimaryKey: true, IsAutoIncrement: true}, {Name: "username", Type: DB_NV...
package red_black import ( "fmt" ) type RBTree struct { Value int Red bool Parent *RBTree Left *RBTree Right *RBTree } // This New function makes sure every node has it's parent func New(t *RBTree) *RBTree { ch := BreadthWalker(t) for { node, ok := <-ch if !ok { return t } if node.Left != n...
package unimatrix func NewDestinationActivitiesOperation(realm string) *Operation { return NewRealmOperation(realm, "destination_activities") }
package database import ( "math/rand" "strconv" "sync/atomic" "time" ) // 生成universal distribute id var ( randString = `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ` randLen = len(randString) tmBegin = time.Date(2010, 2, 9, 1, 0, 0, 0, time.Local).Unix() pid uint64 machineid u...
package result //memory the test result date var ProcessNum = 0 var TestNum = 0 var CaseNum = 0 var TotalResult []TestResult var PreResult TestResult type TestResult struct { Person ResultType Process ResultType Test ResultType CaseResult CaseResultType } type ResultType struct{ Name strin...
package fixed import ( "testing" "github.com/stretchr/testify/assert" ) func TestParseDays(t *testing.T) { d, err := ParseDays(" sunday ") assert.NoError(t, err) assert.Equal(t, []Day{Sunday}, d) d, err = ParseDays("sun") assert.NoError(t, err) assert.Equal(t, []Day{Sunday}, d) d, err = ParseDays("so") a...
package main import ( "bufio" "bytes" "flag" "fmt" "log" "net" "net/http" "net/url" "regexp" "github.com/elazarl/goproxy" "github.com/inconshreveable/go-vhost" ) func orPanic(err error) { if err != nil { panic(err) } } func main() { verbose := flag.Bool("v", true, "should every proxy request be logg...
package main import ( "fmt" ) func main() { for i := 10; i <= 100; i++ { if i%4 == 0 { fmt.Println("Muslera") } else if i%4 == 1 { fmt.Println("Falcao") } else { fmt.Println("Lemina") } } }
package compute_test import ( "errors" "github.com/genevieve/leftovers/gcp/compute" "github.com/genevieve/leftovers/gcp/compute/fakes" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" gcpcompute "google.golang.org/api/compute/v1" ) var _ = Describe("SslCertificates", func() { var ( client *fakes.SslCer...
// Copyright 2017 Baidu, 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 in writing...
package daemon import ( "github.com/hyperhq/hyper/engine" ) func (daemon *Daemon) CmdAuth(job *engine.Job) error { cli := daemon.DockerCli status, err := cli.SendCmdAuth(job.Stdin) if err != nil { return err } v := &engine.Env{} v.Set("status", status) if _, err := v.WriteTo(job.Stdout); err != nil { retu...
// Copyright 2019 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package vm import ( "context" "fmt" "io/ioutil" "os" "path/filepath" "strings" "time" "chromiumos/tast/common/testexec" "chromiumos/tast/local/bundles/cros/vm/dlc"...
package quotes import ( "os" "runtime" "testing" ) func TestParse(t *testing.T) { _, err := Parse() if err != nil { t.Fatalf("%s", err) } } func TestGetPath(t *testing.T) { path := getPath() var wantedPath string if runtime.GOOS == "windows" { wantedPath = os.Getenv("GOPATH") + "\\src\\github.com\\bruno...
package main import "fmt" func main() { ages := map[string]int{ "merlin": 2, "ikaros": 4, } ages2 := map[string]int{ "merlin": 2, "ikaros": 4, } ages3 := map[string]int{ "merlin": 2, } ages4 := map[string]int{ "merlin": 2, "ikaros": 5, } fmt.Println(equal(ages, ages2)) fmt.Println(equal(ages,...
package model type Article struct { HugoJsonPost HugoJsonPost // Content string Md5Value string Segments *[]string }
package main import "fmt" func main() { s := "Hello World" fmt.Println(s) fmt.Printf("%T\n", s) bs := []byte(s) fmt.Println(bs) fmt.Printf("%T\n", bs) for i := 0; i < len(s); i++ { // UTF-8 Code fmt.Printf("%#U", s[i]) } for i := 0; i < len(s); i++ { // UTF-8 HEX fmt.Printf("%#...
package main import ( "fmt" "net/http" "github.com/gorilla/mux" "github.com/gorilla/rpc" "github.com/gorilla/rpc/json" logging "github.com/ipfs/go-log/v2" ) func init() { logging.SetLogLevel("*", "debug") } func main() { rpcServer := rpc.NewServer() rpcServer.RegisterCodec(json.NewCodec(), "application/j...
package main import ( "crypto/rand" "crypto/rsa" "crypto/x509" "crypto/x509/pkix" "encoding/pem" "fmt" "io/ioutil" "math/big" "time" "github.com/3scale-ops/marin3r/pkg/util/pki" "github.com/spf13/cobra" ) var ( key string signerCertPath string signerKeyPath string commonName string ho...
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package wmp import ( "context" "time" "chromiumos/tast/common/fixture" "chromiumos/tast/common/policy/fakedms" "chromiumos/tast/ctxutil" "chromiumos/tast/errors" "ch...
package main import ( "os" "github.com/mfpierre/kubectl-glance/pkg/cmd" "github.com/spf13/pflag" ) func main() { flags := pflag.NewFlagSet("kubectl-glance", pflag.ExitOnError) pflag.CommandLine = flags if err := cmd.RootCmd.Execute(); err != nil { os.Exit(1) } }
/* Copyright 2019 The Skaffold 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...
package main import ( "fmt" m "math" "github.com/MaxHalford/gago" ) // Sphere function minimum is 0 reached in (0, ..., 0). // Any search domain is fine. func Sphere(X []float64) float64 { sum := 0.0 for _, x := range X { sum += m.Pow(x, 2) } return sum } func main() { // Instantiate a population ga := g...
package undocker import "time" type ImageConfig struct { Architecture string `json:"architecture"` Config Config `json:"config"` Container string `json:"container"` ContainerConfig ContainerConfig `json:"container_config"` Created time.Time `json:"create...
package store import ( "encoding/json" "io/ioutil" "os" "path/filepath" ) type Codec interface { Encoder(v interface{}) ([]byte, error) Decoder(p []byte, v interface{}) error } type Storage struct { basePath string codec Codec } type JSONCodec int func (*JSONCodec) Encoder(v interface{}) ([]byte, error)...
package dao import ( "context" "reflect" "github.com/pkg/errors" "github.com/utahta/momoclo-channel/dao/hook" "google.golang.org/appengine/datastore" ) type ( // PersistenceHandler represents persist operations PersistenceHandler interface { Kind(context.Context, interface{}) string Put(context.Context, i...
package h2mux import "sync" // ReadyList multiplexes several event signals onto a single channel. type ReadyList struct { // signalC is used to signal that a stream can be enqueued signalC chan uint32 // waitC is used to signal the ID of the first ready descriptor waitC chan uint32 // doneC is used to signal tha...
package v1 type UserHandler struct { }
package model // Tag - タグ モデル type Tag struct { Base Content string `json:"content" gorm:"unique;not null"` }
package sql import ( "context" "github.com/gobuffalo/pop/v5" "github.com/gofrs/uuid" "github.com/ory/x/sqlcon" "github.com/ory/kratos/selfservice/flow/settings" ) var _ settings.FlowPersister = new(Persister) func (p *Persister) CreateSettingsFlow(ctx context.Context, r *settings.Flow) error { return sqlcon...
package store import ( "encoding/json" "github.com/krantius/logging" "github.com/krantius/raft" ) type Store interface { raft.Store Dump() []byte } type InMemory struct { m map[string]string } func New() *InMemory { return &InMemory{ m: make(map[string]string), } } func (s *InMemory) Set(key string, val...
package main import ( "fmt" "github.com/lixianmin/logo" "os" "os/signal" "syscall" "time" ) func main() { var theLogger = logo.NewLogger() // 开启异步写标记,提高日志输出性能 theLogger.AddFlag(logo.LogAsyncWrite) // 控制台日志 const flag = logo.FlagDate | logo.FlagTime | logo.FlagShortFile | logo.FlagLevel theLogger.SetFuncC...
package graph import ( "context" "errors" domain "server/domain/model" ) // chi middlewareで事前にjwtをcontextに格納 func (r *Resolver) getUIDFromContext(ctx context.Context) (string, error) { jwt, ok := ctx.Value("jwt").(string) if !ok { return "", errors.New("no jwt in context") } uid, err := r.AuthUsecase.Verify(...
package gcunreleased //1. 字符串与截取的字串共享,暂时性泄露 var s0 string //包级变量 func f(s string) { s0 = s[:50] //s0和s共享一个内存块, 到这里只有50个字节需要使用,s其他部分无法释放,需要s0在其他地方被重新修改为止 } func demo() { s := "abcedfghijkcclskjsuhdksls" f(s) } /* 解决办法,转化成字节切片处理,然后再转化回来 s0 = string([]byte(s[:50])) */ //2. 子切片造成的暂时性内存泄露 var ss []int func g(s1 ...
package repository import ( "fmt" pb "github.com/i-coder-robot/go-micro-action-user/proto/user" "github.com/jinzhu/gorm" "github.com/lecex/core/uitl" "github.com/micro/go-micro/v2/util/log" ) type User interface { Create(user *pb.User) (*pb.User, error) Exist(user *pb.User) bool Get(user *pb.User) (*pb.User, ...
package counter import ( "sync" "testing" ) func testCorrectness(t *testing.T, counter Counter) { wg := &sync.WaitGroup{} for i := 0; i < 100; i++ { wg.Add(1) if i%3 == 0 { go func(counter Counter) { counter.Read() wg.Done() }(counter) } else if i%3 == 1 { go func(counter Counter) { cou...
// Copyright 2023 The gVisor 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 agree...
package extension import ( "context" "fmt" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" errorutil "k8s.io/apimachinery/pkg/util/errors" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" "github.com/tilt-dev/tilt/inte...
package acceptance import ( "os" "testing" "github.com/databrickslabs/terraform-provider-databricks/internal/acceptance" ) func TestMwsAccWorkspaces(t *testing.T) { cloudEnv := os.Getenv("CLOUD_ENV") if cloudEnv != "MWS" { t.Skip("Acceptance tests skipped unless CLOUD_ENV=MWS is set") } acceptance.Test(t, [...
package cparser_test import ( "reflect" "ntoolkit/commands" "ntoolkit/commands/cparser" "ntoolkit/errors" "ntoolkit/events" "ntoolkit/futures" "ntoolkit/parser" "ntoolkit/parser/tools" ) type LookCommandFactory struct { } func (factory *LookCommandFactory) Parse(tokenList *parser.Tokens, context interface{}...
/* - Crie um map com key tipo string e value tipo []string. - Key deve conter nomes no formato sobrenome_nome - Value deve conter os hobbies favoritos da pessoa - Demonstre todos esses valores e seus índices. - Solução: https://play.golang.org/p/nD3TW8VQmH */ package main import "fmt" func main() { x := map...
package model type Account struct { Username string `json:"username" validate:"gte=6" binding:"required"` Password string `json:"password" validate:"gte=6" binding:"required"` } func NewAccount(username, password string) Account { e := Account{Username: username, Password: password} return e }