text
stringlengths
11
4.05M
package filters_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" . "github.com/bosh-prometheus/bosh_exporter/filters" ) var _ = Describe("AZsFilter", func() { var ( filter []string azsFilter *AZsFilter ) BeforeEach(func() { filter = []string{"fake-az-1", "fake-az-3"} }) JustBefo...
package db // DB is the interface of database type DB interface { Connect(connStr string) InsertOne(doc interface{}) (interface{}, error) InsertMany(docs []interface{}) error Update(filter, data interface{}) (interface{}, error) Upsert(filter, data interface{}) (interface{}, error) UpdateMany(filter, data interf...
package server import ( "database/sql" "encoding/json" "fmt" "github.com/golang/glog" "io/ioutil" "net/http" "net/url" "strconv" "strings" ) type responseConfigJM struct { Success string `json:"success"` Code int `json:"code"` Data interface{} `json:"data"` Message string `json:"message"` } ...
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package armhelpers import ( "context" "fmt" "github.com/Azure/aks-engine/pkg/api" "github.com/pkg/errors" log "github.com/sirupsen/logrus" ) type validationResult struct { image api.AzureOSImageConfig errorDat...
package slacker import ( "regexp" "github.com/shomali11/proper" ) func (s *Slacker) regexMatch(regex, text string) (*proper.Properties, bool) { re, err := regexp.Compile(regex) if err != nil { return nil, false } values := re.FindStringSubmatch(text) if len(values) == 0 { return nil, false } valueInde...
package day2 import ( "fmt" "io/ioutil" "os" "regexp" "strconv" "strings" ) //DayTwoOne Day two task one func DayTwoOne() { input, err := ioutil.ReadFile("./2/input.txt") if err != nil { fmt.Println(err) os.Exit(1) } pwdData := strings.Split(string(input), "\n") amountOfCorrectPwds := 0 for i := 0...
package main import ( "encoding/binary" "flag" "fmt" "log" "os" "runtime/pprof" "time" "google.golang.org/grpc" ) func SequentialPayload(n int64) []byte { if n%8 != 0 { panic(fmt.Sprintf("n == %v must be a multiple of 8; has remainder %v", n, n%8)) } k := uint64(n / 8) by := make([]byte, n) j := uint...
package main import ( "math/rand" ) func intBetween(rand *rand.Rand, min, max int) int { return rand.Intn(max-min) + min } var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") func stringWithLength(rand *rand.Rand, length int) string { b := make([]rune, length) for i := range b { b[i] ...
func findShortestSubArray(nums []int) int { m:=make(map[int][]int) for i,v:=range nums{ if _,ok:=m[v];ok{ m[v][0]++ m[v][2]=i }else{ m[v] = []int{1,i,i} } } max:=0 ml:=50000 for _,v:=range m{ if v[0]>max || (v[0]==max && v[2]-v[...
package schema import ( "errors" "fmt" "strings" "time" "golang.org/x/crypto/bcrypt" "gopkg.in/mgo.v2/bson" ) // Errors var ( ErrUserAlreadyExist = errors.New("User already exist") ErrUserNotExist = errors.New("User does not exist") ErrUserNotValid = errors.New("User is not valid") ) // User repres...
package main import ( "fmt" "os" ) func main() { for { fmt.Println("Logenhancer - Please select an option") fmt.Println("1 - BlockLog") fmt.Println("2 - AlertLog") fmt.Println("3 - Close") fmt.Println("Your choice: ") filename := "" fmt.Scanf("%s", &filename) switch filename { case "1": runBl...
package service import ( "CloudRestaurant/dao" "CloudRestaurant/model" "CloudRestaurant/param" "CloudRestaurant/tool" "encoding/json" "fmt" "github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi" "log" "math/rand" "strconv" "time" ) type MemberService struct { } func (ms *MemberService)GetUserInfo(use...
package watcher const CreateState = "CREATE" const ModifyState = "MODIFY" const RemoveState = "REMOVE" type Event struct { Type string `json:"type"` Name string `json:"name"` Values *FileData `json:"data"` }
package main import ( "io" "os" "os/exec" "syscall" "github.com/Microsoft/go-winio" ) const sshAgentPipe = "//./pipe/openssh-ssh-agent" func openAgentSocket() (io.ReadWriteCloser, error) { conn, err := winio.DialPipe(sshAgentPipe, nil) if err != nil { err = &os.PathError{Path: sshAgentPipe, Op: "open", Err...
package global import "go.mongodb.org/mongo-driver/bson/primitive" var NilUser User type User struct { ID primitive.ObjectID `bson:"_id,omitempty"` Username string `bson:"username,omitempty"` Password string `bson:"password,omitempty"` }
package workqueue import ( "context" "github.com/apex/log" "gopkg.in/tomb.v2" "git.scc.kit.edu/sdm/lsdf-checksum/internal/lifecycle" "git.scc.kit.edu/sdm/lsdf-checksum/meda" "git.scc.kit.edu/sdm/lsdf-checksum/workqueue" "git.scc.kit.edu/sdm/lsdf-checksum/workqueue/scheduler" ) //go:generate confions config P...
package proxy type application struct { } // HandleRequest handles current request func (a *application) HandleRequest(url, method string) (int, string) { if url == "/myProfile" && method == "GET" { return 200, "OK" } //... if url == "/create/product" && method == "POST" { return 201, "Product Created" } ...
package main import ( "context" "encoding/json" "errors" "io" "log" "net/http" "os" "github.com/olivere/elastic/v6" "github.com/sirupsen/logrus" ) var client *ElasticClient func init() { var err error client, err = NewElasticClient(ElasticClientConfig{ Addr: "http://192.168.1.234:9200", User: ...
package sgf import ( "fmt" "math/rand" "os" "testing" "time" ) func init() { rand.Seed(time.Now().UTC().UnixNano()) } func TestIllegality(t *testing.T) { fmt.Printf("TestIllegality\n") root, err := Load("test_kifu/illegality.sgf") if err != nil { t.Errorf(err.Error()) return } node := root.GetEnd() ...
package main import "fmt" func greeting(name string) string { return "Hello " + name } func getsum(x int, y int) int { return x + y } func main() { var name = "weiqi" fmt.Println(greeting(name)) fmt.Println(getsum(1, 5)) }
package remote import ( "fmt" aerror "opendev.org/airship/airshipctl/pkg/errors" ) type RemoteDirectError struct { aerror.AirshipError } func NewRemoteDirectErrorf(format string, v ...interface{}) error { e := &RemoteDirectError{} e.Message = fmt.Sprintf(format, v...) return e }
/* Copyright 2015 Google Inc. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file or at https://developers.google.com/open-source/licenses/bsd */ package cups /* #cgo LDFLAGS: -lcups #include <cups/cups.h> #include <stdlib.h> // free #include "cups.h" ...
package main import ( "crypto/sha256" "encoding/hex" "strconv" "time" "github.com/fiatjaf/makeinvoice" "github.com/tidwall/sjson" ) func makeMetadata(params *Params) string { metadata, _ := sjson.Set("[]", "0.0", "text/identifier") metadata, _ = sjson.Set(metadata, "0.1", params.Name+"@"+s.Domain) metadata...
package state import ( "bytes" "time" "encoding/json" "github.com/HNB-ECO/HNB-Blockchain/HNB/consensus/algorand/types" ) // database keys var ( stateKey = []byte("stateKey") ) type State struct { // LastBlockNum=0 at genesis (ie. block(H=0) does not exist) LastBlockNum uint64 LastBlockTotalTx int64 L...
package status import "github.com/ant0ine/go-json-rest/rest" // Response is a response struct for /status endpoint type Response struct { Status string `json:"status"` } func handler(w rest.ResponseWriter, r *rest.Request) { status := &Response{"Ok"} w.WriteJson(status) }
// Copyright 2018 The eballscan Authors // This file is part of the eballscan. // // The eballscan is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your optio...
//////////////////////////////////////////////////////////////////////////////// // // // Copyright 2021 Broadcom. The term Broadcom refers to Broadcom Inc. and/or // // its subsidiaries. ...
package main import ( "github.com/labstack/echo/v4" "log" "sync/atomic" "time" ) func main() { e := echo.New() didTheMove := new(atomic.Bool) channel := make(chan struct{}, 1) e.GET("/status", func(c echo.Context) error { startListeningTime := time.Now() // just for info select { case <-channel: l...
// 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 in wr...
// Copyright 2020 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 utilites type Vehicle interface { getDoors() int }
package crashparser //Fieldset for python crash stdout file parsing. type LogFile struct { Filename string `json:"filename"` Exceptions []CrashResult `json:"exceptions"` } //Fieldset for python crash stdout parsing. type CrashResult struct { ExceptionLine int `json:"line"` ExceptionType string `...
package controller import ( "github.com/GoAdminGroup/go-admin/context" "github.com/GoAdminGroup/go-admin/modules/logger" "github.com/GoAdminGroup/go-admin/plugins/admin/modules/guard" "github.com/GoAdminGroup/go-admin/plugins/admin/modules/response" ) // Delete delete the row from database. func (h *Handler) Dele...
package k8s_client import ( "bytes" "context" "fmt" "io/ioutil" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "strings" "testing" "time" ) func TestNewForConfig(t *testing.T) { c, err := KubeRestConfigGetter() if err != nil { t.Fatal(err) } client, _ := NewForConfig(c) ctx, cancel := context.WithCanc...
package overrides import ( "io" "github.com/golang/glog" "k8s.io/kubernetes/pkg/admission" kapi "k8s.io/kubernetes/pkg/api" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" buildadmission "github.com/openshift/origin/pkg/build/admission" overridesapi "github.com/openshift/origin/...
/* @Time : 2019/4/16 17:47 @Author : yanKoo @File : redisMap @Software: GoLand @Description: */ package server import ( pb "api/talk_cloud" "encoding/json" "errors" "fmt" "github.com/gomodule/redigo/redis" "log" "server/common/src/cache" "strconv" ) func GetUserState(uIdKey []interface{}, rd redis.Conn) (map...
package config type DemoConfig struct { SessionEncKey string SessionCookieName string }
package artifact import ( "io" "io/ioutil" "net/url" "os" "path/filepath" "github.com/square/p2/pkg/auth" "github.com/square/p2/pkg/gzip" "github.com/square/p2/pkg/uri" "github.com/square/p2/pkg/util" ) // Interface for downloading a single artifact. type Downloader interface { // Downloads the artifact re...
package auth import ( "github.com/kataras/golog" "github.com/smartystreets/assertions" "testing" "time" ) func TestRedisSetFunctionality(t *testing.T) { logger := golog.New() manager := Init(logger) db := manager.Database err := db.Set("niconicocsc", "TestRedisSetFunctionality", "2eyJhbGciOiJIUzI1NiIsInR5cCI6...
package awss3 import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3/s3manager" "github.com/gammazero/workerpool" "github.com...
package pgsql import ( "context" "database/sql" "fmt" "github.com/syahidfrd/go-boilerplate/domain" ) type pgsqlAuthorRepository struct { db *sql.DB } // NewAuthorRepository will create new an authorRepository object representation of domain.AuthorRepository interface func NewPgsqlAuthorRepository(db *sql.DB) d...
package entity import ( "time" "github.com/Surafeljava/gorm" ) type Admin struct { ID uint AdminId string `gorm:"type:varchar(50);not null"` AdminPwd string `gorm:"type:varchar(50);not null"` } type UserType struct { gorm.Model UsrId string UsrPwd string } type Case struct { ID uint Ca...
package main import ( // #include "math.h" "C" "fmt" ) func main() { fmt.Println("Welcome from Go") fmt.Println("Let's call some functions from our C library") fmt.Printf("C: math_add(2, 3)=%d\n", C.math_add(2, 3)) fmt.Printf("C: math_sub(5, 2)=%d\n", C.math_sub(5, 2)) }
package reverseproxy import ( "testing" "encoding/json" "net/http" "io/ioutil" "bytes" "strconv" "crypto/md5" ) type staticJsonQuery struct {} func (staticJsonQuery) GetSubNodes(jsonData []interface{}) (nodes []interface{}, err error) { testJsonStr := `[{"id": 1}, {"id": 2}]` var testJson []interface{} json...
package main import ( "time" "github.com/muesli/cache2go" ) var knownUserIds = cache2go.Cache("visitors") func AddKnownUser(userId string) { if IsNewUser(userId) { knownUserIds.Add(userId, time.Hour*24*15, userId) } } func IsNewUser(userId string) bool { exists, _ := knownUserIds.Value(userId) return exist...
package main import ( "fmt" ) func decimalToBinary(val uint64) []uint64 { bits := []uint64{} for val != 0 { mod := val % 2 bits = append(bits, mod) val = val / 2 } for i := 0; i < len(bits); i++ { fmt.Print(bits) } return bits }
package suggestion_service import ( "ms/sun_old/base" "ms/sun/shared/helper" "ms/sun/servises/view_service" "ms/sun/shared/config" "ms/sun/shared/x" "time" ) const TOP_TAGS_LIMIT = 30 func Tags_RepeatedlyJobs() { //top tags go func() { defer helper.JustRecover() for { if config.DEBUG_DELAY_RUN_STARTUP...
package gherkin import ( "bytes" "fmt" ) type step struct { line string orig string keys []string mldata []map[string]string isPending bool errors bytes.Buffer hasErrors bool } func (s step) String() string { return s.line } func StepFromString(in string) step{ return ste...
package configuration import ( "gopkg.in/yaml.v2" "io/ioutil" "log" ) /* - Load yml file - Read it into struct - store it into map with host as key and servers as value array [{}, {}, {}] */ type Config struct { Hosts map[string][]string `yaml:"Hosts"` } func read(filename string) []byte{ data,err :=...
package pastebin import ( "io/ioutil" "net/http" "net/url" "strings" ) const endpoint = "https://pastebin.com/api/api_post.php" type Client interface { Paste(title, body, private, expire string) string } type clientImpl struct { apiKey string } func NewClient(apiKey string) Client { return &clientImpl{apiKe...
package bingSpellCheck import "fmt" const ( // ErrorResponseType is used as a value for SpellCheckResponse.Type and // indicates a request error occured ErrorResponseType = "ErrorResponse" // SpellCheckResponseType is used as a value for SpellCheckResponse.Type and // indicates a successful request SpellCheckRe...
package main import ( "flag" "log" "net" "strconv" "time" ) const ( defaultIP = "192.168.4.1" ) var ( robotIP string // IP address of robot robotPort int // Port on robot robotName string // Hostname of robot serverPort int // Port on which to listen projectVersion = "dev" projectBuild = "d...
package mysqldb import "strings" const ( // maxQuerySize 最大正整数 maxQuerySize = 2147483647 ) // sqlEscape 转移 SQL 语句 func sqlEscape(s string) string { s = strings.Replace(s, "%", "\\%", -1) s = strings.Replace(s, "_", "\\_", -1) s = strings.Replace(s, "\\", "\\\\", -1) return s }
package linkedlists func deletedups(l *ListNode) *ListNode { vals := make(map[int]bool) var prev *ListNode cur := l for cur != nil { val := cur.value if _, ok := vals[val]; ok { prev.next = cur.next cur = cur.next } else { vals[val] = true prev = cur cur = cur.next } } return l } func c...
// +build integration package main // To run locally on OS X // $ docker-machine create -d virtualbox testing // $ eval $(docker-machine env testing) // $ export DOCKER_IP=$(docker-machine ip testing) // $ export CONSUL_IP=$(docker-machine ip testing) // $ docker rm -f docker-flow-proxy // $ docker run --rm -v $PWD:/...
package main import ( "bytes" "flag" "fmt" "go/scanner" "image" "io" "io/ioutil" "os" "os/exec" "path/filepath" "regexp" ) var ( doWrite = flag.Bool("w", false, "doWrite result to (source) file instead of stdout") doDiff = flag.Bool("d", false, "display diffs instead of rewriting files") whiteNoise = ...
/* @Time : 2019/4/15 17:53 @Author : yanKoo @File : message_test @Software: GoLand @Description: */ package msg import ( pb "api/talk_cloud" "log" "server/common/src/db" "testing" ) func testAddMsg(t *testing.T) { /*if err := AddMsg(&pb.ImMsgReqData{ Id:333, ReceiverType:0, ReceiverId:334, ResourcePath:...
package ibmcloud import ( "context" "fmt" "net/http" "os" "strings" "sync" "time" "github.com/IBM/go-sdk-core/v5/core" "github.com/IBM/networking-go-sdk/dnsrecordsv1" "github.com/IBM/networking-go-sdk/dnssvcsv1" "github.com/IBM/networking-go-sdk/dnszonesv1" "github.com/IBM/networking-go-sdk/zonesv1" "git...
package main import ( "fmt" "strconv" ) func main() { inputString := "there are some (12) digits 5566 in this 770 string 239" var numStrArray []string total := 0 strNum := "" for _, x := range inputString { _, err := strconv.Atoi(string(x)) if err != nil && strNum != "" { numStrArray = append(numStrA...
package gorpc import ( "bufio" "compress/flate" "encoding/gob" "fmt" "io" "net" "runtime" "sync" "sync/atomic" "time" ) // Server handler function. // // clientAddr contains client address returned by net.TCPConn.RemoteAddr(). // Request and response types may be arbitrary. // All the request types the clie...
package main func BeforeFork() func AfterFork() func main() { }
package query import ( "github.com/juju/errgo" // "github.com/mezis/klask/index" ) // A comparison filter (less than, greater than, or both) type query_filter_between_t struct { name string less_than interface{} greater_than interface{} } func (self *query_filter_between_t) parse(name string, parsed ...
package common import ( "fmt" "net/http" "github.com/GoAdminGroup/go-admin/modules/config" "github.com/GoAdminGroup/go-admin/modules/language" "github.com/gavv/httpexpect" ) func operationLogTest(e *httpexpect.Expect, sesID *http.Cookie) { fmt.Println() printlnWithColor("Operation Log", "blue") fmt.Println(...
package main import ( "bytes" "context" "crypto/tls" "encoding/base64" "flag" "fmt" "io" "io/ioutil" "net" "net/http" "net/http/httputil" "net/url" "strconv" "time" "github.com/mattn/go-colorable" "github.com/natefinch/lumberjack" "github.com/rs/zerolog" "github.com/rs/zerolog/hlog" "github.com/rs/...
package basecmds import ( _ "embed" "github.com/Nv7-Github/Nv7Haven/eod/types" "github.com/bwmarrin/discordgo" ) //go:embed help/about.txt var helpAbout string //go:embed help/basics.txt var helpBasics string //go:embed help/advanced.txt var helpAdvanced string //go:embed help/setup.txt var helpSetup string f...
package middlewares import ( "net/http" "github.com/opentracing/opentracing-go" "github.com/sirupsen/logrus" "fmt" "github.com/opentracing/opentracing-go/ext" "net" "strconv" "github.com/openzipkin/zipkin-go-opentracing/thrift/gen-go/zipkincore" "github.com/oshankkumar/GatewayOmega/utils" ) func ZipkinTracin...
package template import ( "context" "fmt" "log" "github.com/argoproj/pkg/errors" "github.com/spf13/cobra" "github.com/argoproj/argo/cmd/argo/commands/client" workflowtemplatepkg "github.com/argoproj/argo/pkg/apiclient/workflowtemplate" ) // NewDeleteCommand returns a new instance of an `argo delete` command...
package hash import ( "crypto/hmac" "crypto/sha256" "encoding/binary" "errors" "io" "golang.org/x/crypto/argon2" "golang.org/x/crypto/blake2b" "golang.org/x/crypto/hkdf" ) const ( // MACSize represents the size of a 16 byte MAC. MACSize = 16 // KeySize represents the size of a 32 byte key. KeySize = 32 ...
package main_test import ( "testing" "net/http" "os/exec" "os" "fmt" "gopkg.in/Shopify/sarama.v1" "bufio" "errors" "github.com/bsm/sarama-cluster" "math/rand" "time" ) const sourceMsg = `World` const expectedReply = `Hello World` const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" func...
package controllers import ( "encoding/json" "net/http" "github.com/astaxie/beego/validation" "github.com/raykanavheti/LetsworkBackend/controllers/util" "github.com/raykanavheti/LetsworkBackend/models" ) //ProfileController interface type ProfileController struct{} // CreateProfile creates a new Profile for a ...
package word import ( "bytes" "strings" ) // CamelCase convert `a_b_c` to `aBC` func CamelCase(v string) string { buf := bytes.NewBuffer([]byte{}) length := len(v) for i := 0; i < length; i++ { if v[i] != '_' { buf.WriteByte(v[i]) } else { i++ if i > length { continue } if v[i] >= 'a' && v...
// 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 pathfileops import ( "fmt" "testing" ) func TestFileMgr_ChangePermissionMode_01(t *testing.T) { filePath := "../../filesfortest/modefilesfortest/modeFileTest_01.txt" fMgr, err := FileMgr{}.NewFromPathFileNameExtStr(filePath) if err != nil { t.Errorf("Error returned from FileMgr{}.NewFromPathF...
/* (Intermediate): Adjacency Matrix In graph theory, an adjacency matrix is a data structure that can represent the edges between nodes for a [graph](http://en.wikipedia.org/wiki/Graph_(mathematics)) in an N x N matrix. The basic idea is that an edge exists between the elements of a row and column if the entry at tha...
package main import ( "redisDB" ) func processRedisResTask_goroutine(svr *echoServer) { for { resTask := <- svr._resTaskChan if resTask.ID == redisDB.TaskID_ResLogin { _sendLoginResponse(svr, int(resTask.UID), resTask.Result) } } } func _sendLoginResponse(svr *echoServer, sessionIndex int, result int16)...
package kademlia import ( "log" "testing" "time" ) func otherNode(myId string, myPort int, contact *Contact) { node := NewKademlia(myId, "127.0.0.1", myPort) go node.Listen("127.0.0.1", myPort) time.Sleep(100 * time.Microsecond) if contact != nil { /*node.RoutingTable.AddContact(*contact) node.Network.S...
package zenrpc_mw import ( "context" "encoding/json" "strconv" "time" "github.com/go-kit/kit/metrics" "github.com/semrush/zenrpc" ) func RequestCounter(counter metrics.Counter) zenrpc.MiddlewareFunc { return func(invoke zenrpc.InvokeFunc) zenrpc.InvokeFunc { return func(ctx context.Context, method string, p...
package scan import ( "fmt" "testing" "h12.io/gspec" ) var ( c = Char b = Between merge = Merge s = Str con = Con or = Or zeroOrOne = ZeroOrOne zeroOrMore = ZeroOrMore oneOrMore = OneOrMore repeat = Repeat ) func TestExpr(t *testing.T) { expect := g...
package sqlbuilder_test // This is in a different package so we can also make sure everything works from outside of the sqlbuilder package import ( "fmt" . "github.com/jraede/go-sqlbuilder" . "github.com/smartystreets/goconvey/convey" "testing" ) type param struct { description string query *Query expec...
package main import ( "flag" "fmt" "time" ) func main() { // THIS IS SO COOL!!!!! // It defines both the type of the input and its unit // `$ ~ go run sleep.go --period 1m` sleeps 1 minute var period = flag.Duration("period", 1*time.Second, "sleep period") flag.Parse() fmt.Printf("Sleeping for %v seconds...\...
package entities // Character represents an in game character. // It has a role and some additional informations. // type Character struct { Role Role // Private fields alive bool sheriff bool } // NewCharacter creates a new character. // This character has theses properties: // // - The character has a given...
package utils import ( "database/sql/driver" "fmt" mathRand "math/rand" "os" "regexp" "strconv" "strings" "time" "github.com/exasol/exasol-driver-go/pkg/errors" ) var localImportRegex = regexp.MustCompile(`(?i)(FROM LOCAL CSV )`) var fileQueryRegex = regexp.MustCompile(`(?i)(FILE\s+(["|'])?(?P<File>[a-zA-Z0...
// GO BINARY SEARCH TREE package main import "fmt" type Node struct { data int lChild *Node rChild *Node } type BinaryTree struct { root *Node } // Initialize Tree with content func newBinaryTree(items ...int) BinaryTree { n := BinaryTree{nil } for _, num := range items { n.add(num) } return n } // 1. Se...
package leetcode func findSpecialInteger(arr []int) int { l := len(arr) quarter := l / 4 for i := 0; i < l; i++ { if arr[i] == arr[i+quarter] { return arr[i] } } return -1 }
package admin import ( "github.com/astaxie/beego" "go_blog/utils" ) type AdminController struct { beego.Controller } type AdminDirector struct { controller *AdminController modelBuilder AdminModel current string } func (self *AdminDirector) getModel() { self.modelBuilder.GetUserOrRedirectLogin(self.controlle...
// 使用 `os.Exit` 来立即进行带给定状态的退出。 package main import "fmt" import "os" func main() { // 当使用 `os.Exit` 时 `defer` 将_不会_ 执行,所以这里的 `fmt.Println` // 将永远不会被调用。 defer fmt.Println("!") // 退出并且退出状态为 3。 os.Exit(3) } // 注意,不像例如 C 语言,Go 不使用在 `main` 中返回一个整 // 数来指明退出状态。如果你想以非零状态退出,那么你就要 // 使用 `os.Exit`。
package main import ( "html/template" "log" "net/http" ) type Foo struct { Name string StaticURL string Things []*Thing } type Thing struct { Bleep string Bloop int } func loadTemplates() (*template.Template, error) { return template.New("root").ParseGlob("web/*") } type Server struct { Data ...
/* * winnow: weighted point selection * * input: * matrix: an integer matrix, whose values are used as masses * mask: a boolean matrix showing which points are eligible for * consideration * nrows, ncols: the number of rows and columns * nelts: the number of points to select * * output: * point...
package main import "fmt" // 格式 /* func 函数名(参数)(返回值){ 函数体 } */ /* func intSum(x,y int)int{ return x + y } func main(){ sum1 := intSum(1,2) fmt.Println(sum1) } */ // 可变参数 func intSum2(x...int)int{ fmt.Println(x) sum := 0 for _,v := range x{ sum += v } return sum } func main(){ ret1 := intSum2() ret2 := in...
// +build windows package systray import ( "runtime" "sync/atomic" "testing" "time" "unsafe" "golang.org/x/sys/windows" ) func TestBaseWindowsTray(t *testing.T) { systrayReady = func(){} systrayExit = func(){} runtime.LockOSThread() if err := wt.initInstance(); err != nil { t.Fatalf("initInstance faile...
package data import ( "errors" "log" pb "github.com/bgokden/veri/veriservice" ) // Insert inserts data to internal kv store func (dt *Data) Insert(datum *pb.Datum, config *pb.InsertConfig) error { if dt.Config != nil && !dt.Config.NoTarget && dt.N >= dt.Config.TargetN { return errors.New("Number of elements is...
package main import ( "fmt" ) func maxProfit(prices []int) int { max := 0 size := len(prices) for i := 0; i < size-1; i++ { if prices[i] < prices[i+1] { max += prices[i+1] - prices[i] } } return max } func main() { prices := []int{7, 1, 5, 3, 6, 4} fmt.Println(maxProfit(prices)) }
package nsqsubscriber import "github.com/bitly/go-nsq" type NSQMessage struct { *nsq.Message } func (m *NSQMessage) Body() []byte { return m.Message.Body } func (m *NSQMessage) Timestamp() int64 { return m.Message.Timestamp }
package repository import ( "github.com/Tanibox/tania-core/src/assets/domain" "github.com/Tanibox/tania-core/src/assets/storage" "github.com/gofrs/uuid" ) // RepositoryResult is a struct to wrap repository result // so its easy to use it in channel type RepositoryResult struct { Result interface{} Error error }...
package main import ( "fmt" "go_code/project1/61factorymodel/model" ) func main() { //大写的直接引用即可 stu := model.Student{ Name: "tom", Age: 12, } fmt.Println("stu:", stu) //小写的直接引用报错 cannot refer to unexported name model.student // stu1 := model.student{ // Name: "tom", // Age: 12, // } //var stu1 mo...
// Copyright The 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 writ...
package compose import ( "fmt" "time" "github.com/kudrykv/latex-yearly-planner/app/components/calendar" "github.com/kudrykv/latex-yearly-planner/app/components/page" "github.com/kudrykv/latex-yearly-planner/app/config" ) func DailyWMonth(cfg config.Config, tpls []string) (page.Modules, error) { if len(tpls) !=...
package models_test import ( "github.com/APTrust/exchange/models" "github.com/APTrust/exchange/util/testutil" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "testing" ) func TestNewStorageSummary(t *testing.T) { objIdentifier := "ncsu.edu/bag1" tarPath := "/tmp/ncsu.edu/bag1.tar" u...
package tkapi import ( "bytes" "encoding/json" "errors" "github.com/mrxiaojie/taobaoke" ) type ItemInfo struct { ReqParam ItemInfoParam } //请求参数 type ItemInfoParam struct { NumIids string Platform int Ip string } //初始化api func (t *ItemInfo) Init() { t.ReqParam.NumIids = "" //商品ID串,用,分割,最大40个,例如:123,456 ...
/* The MIT License (MIT) Copyright (c) 2019 Microsoft 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, merge, pu...