text
stringlengths
11
4.05M
package providers import ( "github.com/sirupsen/logrus" "github.com/openshift/installer/pkg/types" ) // Destroyer allows multiple implementations of destroy // for different platforms. type Destroyer interface { Run() (*types.ClusterQuota, error) } // NewFunc is an interface for creating platform-specific destro...
package odor // Config contains the configuration for odor. type Config struct { LogLevel string `json:"logLevel" env:"LOG_LEVEL"` Address string `json:"address" env:"ADDRESS"` NfqueueID int `json:"nfqueueID" env:"NF_QUEUE_ID"` Filters map[string][]string `json:"filte...
package gans import ( "image" "image/color" "github.com/unixpickle/weakai/neuralnet" ) const GridSpacing = 1 var GridSpaceColor = color.RGBA{R: 0x80, G: 0x80, B: 0x80, A: 0xff} // GridSample samples images from a generator and arranges // them in a grid on an image. // Tensor images may either have a depth of 1...
package testsuite import ( "context" "errors" "fmt" "testing" "time" "go.mercari.io/datastore" "google.golang.org/api/iterator" ) func queryCount(ctx context.Context, t *testing.T, client datastore.Client) { defer func() { err := client.Close() if err != nil { t.Fatal(err) } }() type Data struct ...
/* Copyright 2017 The Kubernetes 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, ...
package main import ( "fmt" "math/rand" "time" ) // Spaceline Days Trip type Price // ====================================== // Virgin Galactic 23 Round-trip $ 96 // Virgin Galactic 39 One-way $ 37 // SpaceX 31 One-way $ 41 // Space Adventures 22 Round-trip $ 100 // Space Adven...
package main import ( "fmt" ) func main() { m := map[string]int{ "aaa": 10, "bbb": 20, } for k, v := range m { fmt.Println(k, v) } }
/** * Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. * For example, Given nums = [0, 1, 3] return 2. */ func missingNumber(nums []int) int { miss := 0 for i := 0; i < len(nums); i++ { miss ^= (i + 1) ^ nums[i] } return mi...
package main import ( "fmt" "log" ) func domain() { log.Println("================= DOMAIN =================") if err := checkEnv(); err != nil { fmt.Println(err) return } domain, err := c.GetDomainControlEmails("432481") // domain, err := c.ListValidationTypes() // domain, err := c.ListDomains("88217") /...
package httpmock import ( "bytes" "io/ioutil" "net/http" "strings" ) // MockResponse is to mock the HTTP response // to use with the MockClient type MockResponse struct { URI string Body string StatusCode int } type RoundTripFunc func(req *http.Request) *http.Response func (f RoundTripFunc) Roun...
package proxy import ( "flag" "fmt" "network" "os/exec" ) var ( OS = network.GetOS() // TODO: make all these switch cases, if we ever program for OS X platform PROXY_PORT = "7878" // mitmproxy runs on port 8080; HTTP server for managing iptables will be this PROXY_C...
package main import ( "context" "log" "time" ) func handleResults(ctx context.Context, resultCh chan int) { for { select { case res := <-resultCh: log.Printf("res: %v", res) case <-ctx.Done(): err := ctx.Err() if err == nil { log.Panicf("error should not be nil") } log.Printf("err is: %v"...
package main import ( "flag" "github.com/gin-gonic/gin" ) var ( name = flag.String("name", "oald", "dict name") dir = flag.String("dir", "../data/", "dict data path") dictMap map[string]Dict dictGuess map[string]GuessFunc ) func init() { registerDictGuesses() } func main() { flag.Par...
package flow import ( "log" "time" "github.com/guilhermesteves/aclow" ) type EnsuringDatabaseStructure struct { app *aclow.App } func (n *EnsuringDatabaseStructure) Address() []string { return []string{"ensuring_database_structure"} } func (n *EnsuringDatabaseStructure) Start(app *aclow.App) { n.app = app go...
package main import ( "flag" "fmt" "github.com/bmarini/cli/commander" ) func main() { cli := commander.NewCLI() cmd := Command{} cli.AddCommand(cmd) cli.Run() } type ClientConfig struct { verbose bool } type Command struct{} func (c Command) DefineFlags(f *flag.FlagSet) interface{} { var cfg ClientConfig...
// Copyright 2022-present Open Networking Foundation. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applica...
package main import ( "github.com/spf13/cobra" "github.com/openshift/installer/cmd/openshift-install/agent" "github.com/openshift/installer/pkg/asset" "github.com/openshift/installer/pkg/asset/agent/agentconfig" "github.com/openshift/installer/pkg/asset/agent/configimage" "github.com/openshift/installer/pkg/ass...
// Copyright (C) 2019-2020, Xiongfa Li. // @author xiongfa.li // @version V1.0 // Description: package mysql import ( _ "github.com/go-sql-driver/mysql" "github.com/xfali/gobatis" "github.com/xfali/neve-core/appcontext" "github.com/xfali/neve-example/internal/pkg/cache" "github.com/xfali/neve-example/internal/pk...
package services import ( "bytes" "encoding/binary" "models" "net" "log" ) func CreateOnionTunnelBuild(onionTunnelBuild models.OnionTunnelBuild) ([]byte) { // Message Type messageType := uint16(560) // Convert messageType to Byte array messageTypeBuf := new(bytes.Buffer) binary.Write(messageTypeBuf, binar...
package middleware import ( "fmt" "net/http" ) func VerifyAuth(next http.Handler) http.Handler { return http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) { if request.Method != "OPTIONS" { bearerToken := request.Header.Get("Authorization") if isAuth, usuario := VerifyToken(bearerT...
package main import "fmt" func main() { fmt.Println("I'm version v0.2.0") }
package main import ( "fmt" "log" "os" "strconv" "time" ) // ReadConfig constitutes config from env variables type ReadConfig struct { } const DefaultMaxReconnect = 120 const DefaultReconnectDelay = time.Second * 2 func (ReadConfig) Read() (QueueWorkerConfig, error) { cfg := QueueWorkerConfig{ AckWait: ...
package adabas import ( "math" "regexp" "strconv" "strings" "unicode/utf8" "github.com/SoftwareAG/adabas-go-api/adatypes" ) // FieldQuery parse result of the field part of the query type FieldQuery struct { Prefix rune Name string PeriodicIndex uint32 MultipleIndex uint32 } // NewFieldQuer...
package main import ( "fmt" "github.com/Marneus68/spac/packager" "os" ) func main() { if len(os.Args) != 3 { fmt.Println("Not enough arguments provided.\n") PrintUsage() os.Exit(1) } d, err := os.Stat(os.Args[1]) if os.IsNotExist(err) { fmt.Println("Directory " + os.Args[1] + " doesn't exist.\n") Pr...
package swag import ( "fmt" "go/ast" goparser "go/parser" "go/token" "log" "math/rand" "net/http" "regexp" "strconv" "strings" "text/template" "time" "golang.org/x/tools/go/packages" "github.com/go-openapi/jsonreference" "github.com/go-openapi/spec" "github.com/pkg/errors" ) // Operation describes a...
package main import ( "fmt" "log" "net/http" "time" "context" "html/template" "strconv" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo/options" ) func getClient() *mongo.Client { clientOptions := options.Client().A...
package items import ( "admigo/model" "fmt" ) type ItemModel struct { Id int `json:"id,omitempty"` Nm string `json:"nm"` Description string `json:"description"` Price string `json:"price"` Additional string `json:"additional"` Thumb string `json:"thumb"` } func (item_ed *Ite...
package netsize import ( "testing" "time" kbucket "github.com/libp2p/go-libp2p-kbucket" pt "github.com/libp2p/go-libp2p/core/test" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ks "github.com/whyrusleeping/go-keyspace" ) func TestNewEstimator(t *testing.T) { bucketSize := 20 pi...
package main import ( "errors" "fmt" "github.com/Symantec/Dominator/imageserver/client" "github.com/Symantec/Dominator/lib/filesystem" "github.com/Symantec/Dominator/lib/objectclient" "github.com/Symantec/Dominator/lib/srpc" "github.com/Symantec/Dominator/proto/imageserver" "net/rpc" "os" ) func addReplaceIm...
package main import ( ll "glinkedlist" "testing" ) func TestLinkedListHeadandTail(t *testing.T) { l := ll.Stack{} seedData := seedLinkedList(&l, []string{}) // Test the Head matches the first seedData item if l.Head.Data != seedData[0] { t.Errorf("Error in linked list Head data, expected %s, got %s", s...
package main import ( twitch "github.com/gempir/go-twitch-irc/v2" ) const residentSleeperEmoteID = "245" func startConnection() { // connect to twitch anonymously client := twitch.NewClient("justinfan123", "oauth:123123123123") client.OnPrivateMessage(func(message twitch.PrivateMessage) { for _, emote := rang...
package main import ( "math" "math/rand" "sort" "strconv" "strings" "github.com/veandco/go-sdl2/sdl" ) const ( MenuOrientationAuto = iota MenuOrientationHorizontal MenuOrientationVertical MenuSpacingNone = "menu spacing none" MenuSpacingSpread = "menu spacing fill" MenuCloseNone = iota MenuCloseClic...
package main import ( "fmt" "io" "net/http" "os" "os/exec" "io/ioutil" ) // Считыватель файлов. Принимает имя файла и выдаёт его содержимое func readFile(iFileName string) string { // Считываем файл lData, err := ioutil.ReadFile(iFileName) var lOut string // Объявляем строчную переменную...
package mikrotik import ( "errors" "strings" "github.com/PuerkitoBio/goquery" . "github.com/KonishchevDmitry/go-rss" . "github.com/KonishchevDmitry/rsspipes" ) func init() { Register("/mikrotik-releases.rss", getFeed) } func getFeed() (feed *Feed, err error) { const url = "https://mikrotik.com/download/chan...
package geo import ( "math" "testing" ) func Deg2Rad(x float64) float64 { return x * math.Pi / 180 } func DistTest(algorithm string, t *testing.T) { locations := make(map[string]([2]float64)) locations["Google HQ"] = [2]float64{37.422045, -122.084347} locations["San Francisco"] = [2]float64{37.77493, -122.419...
package main import ( "fmt" "math" ) // Solution to problem 2 in Project Euler: http://projecteuler.net/problem=2 // // Each new term in the Fibonacci sequence is generated by adding the previous // two terms. By starting with 1 and 2, the first 10 terms will be: // // 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... // // B...
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package armhelpers import ( "context" "github.com/Azure/azure-sdk-for-go/services/preview/msi/mgmt/2015-08-31-preview/msi" "github.com/Azure/go-autorest/autorest/to" log "github.com/sirupsen/logrus" ) // CreateUserAs...
package cache import ( "encoding/base64" "github.com/codenotary/immudb/pkg/api/schema" "github.com/stretchr/testify/require" "io/ioutil" "log" "os" "testing" ) func TestNewFileCache(t *testing.T) { dirname, err := ioutil.TempDir("", "example") if err != nil { log.Fatal(err) } os.Mkdir(dirname, os.ModePer...
package main import ( "proxy/pkg/api" "proxy/pkg/server" ) func main() { go api.Run() server.Run(":8080") }
package main import "fmt" func main() { // Define slice ids := []int{33,76,59,48,19,23} // Loop through ids for i, id := range ids { fmt.Printf("%d - ID: %d\n",i,id) } // Not using index for _, id := range ids { fmt.Printf("ID: %d\n", id) } // Add ids together sum := 0 for _, id := range ids { su...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //810. Chalkboard XOR Game //We are given non-negative integers nums[i] which are written on a chalkboard. Alice and Bob take turns erasing exactly on...
package main import ( "fmt" ) type Employee struct { ID int FirstName string LastName string Address string } func main() { employee := Employee{LastName: "Doe", FirstName: "John"} fmt.Println(employee) employeeCopy := &employee employeeCopy.FirstName = "David" fmt.Println(employee) }
package multiInter type I2 interface { M2() }
package main import ( "ReviewGenerator/reviewer" "ReviewGenerator/translator" "ReviewGenerator/utils" "fmt" "github.com/go-telegram-bot-api/telegram-bot-api" "github.com/sirupsen/logrus" "net/http" "os" "strings" "unicode/utf8" ) func init() { logrus.SetFormatter(&utils.Formatter{}) logrus.SetReportCaller...
package httputil import ( "github.com/PuerkitoBio/goquery" "net/http" ) var httpClient = &http.Client{} //get请求地址,返回document对象 func Get(url string) (doc *goquery.Document, err error) { reqest, e := http.NewRequest("GET", url, nil) if e != nil { err = e return } reqest.Header.Add("User-Agent", "Mozilla/5.0 ...
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net" "net/http" "os" "path" "path/filepath" "strings" "time" ) type Config struct { Log string `json:"log"` HttpPort int `json:"http_port"` UdpPort int `json:"udp_port"` UpdateToken string `json:"update_token"` ApiToke...
package main import "fmt" func multiplicar(x, y int) int { return x * y } func exec(funcao func(int, int) int, p1, p2 int) int { return funcao(p1, p2) } func main() { resultado := exec(multiplicar, 3, 5) fmt.Println(resultado) }
package main import "fmt" import "time" func worker(done chan bool, num int) { fmt.Print("starting work at ", num, "\n") time.Sleep(time.Duration(5)*time.Second); fmt.Print("finished work\n") done <- true } func main() { done := make(chan bool, 1) for i:=0; i<=5; i++ { go worker(done,i) } <- done; }...
package main import "fmt" import "os" func main() { defer fmt.Println("!") // defer will not be run when using os.Exit - fmt.Println will never be called os.Exit(3) // use it to immediately exit with a given status }
package cmd import ( "github.com/Files-com/files-cli/lib" "github.com/spf13/cobra" "fmt" "os" files_sdk "github.com/Files-com/files-sdk-go" "github.com/Files-com/files-sdk-go/file" ) var ( Files = &cobra.Command{ Use: "files [command]", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []s...
/* Copyright 2021 CodeNotary, Inc. 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 applicable law or agreed to i...
package handlers import ( log "github.com/sirupsen/logrus" "net/http" "github.com/stellar/gateway/protocols" "github.com/stellar/gateway/server" "github.com/zenazn/goji/web" ) // HandlerRemoveAccess implements /remove_access endpoint func (rh *RequestHandler) HandlerRemoveAccess(c web.C, w http.ResponseWriter, ...
package fetcher type Url struct { Url string TimeStamp string }
package elasticsearch import ( "elktools/cmd/utils" "github.com/desertbit/grumble" ) func init() { Register("tasks", initPendingTasks) } func initPendingTasks(name string) { pendingTasksCommand := &grumble.Command{ Name: name, Help: "GET _cat/pending_tasks", HelpGroup: defaultApp.App.Config().Na...
package requests import "time" var _ = time.Time{} type CreateTodo struct { ListID string ListName string Status string CardID string BoardID string BoardName string Source string } type UpdateTodo struct { ListID string ListName string Status string CardID string BoardID stri...
package primitives import ( "github.com/akosgarai/opengl_playground/examples/model-loading/pkg/vertex" "github.com/go-gl/mathgl/mgl32" ) type Rectangle struct { Points [4]mgl32.Vec3 Normal mgl32.Vec3 Indicies []mgl32.Vec3 } // NewSquare creates a rectangle with origo as middle point. // The normal points t...
package main import "fmt" type Cat struct { Name string Age int Color string Slice []int } func main() { var cat Cat cat.Name = "test" cat.Age = 11 cat.Color = "test" fmt.Println(cat) //cat.Slice[0] = 1//直接使用会报错,必须要分配指向的空间 cat.Slice = make([]int,10) fmt.Println(cat) }
package slack import ( "net/http" "testing" ) func getAuditLogs(rw http.ResponseWriter, r *http.Request) { rw.Header().Set("Content-Type", "application/json") response := []byte(`{"entries": [ { "id": "0123a45b-6c7d-8900-e12f-3456789gh0i1", "date_create": 1521214343, "action": "u...
package domain import ( "github.com/stretchr/testify/assert" "net/http" "testing" ) func TestGetUserNotUserFound(t *testing.T) { user, err := UserDao.GetUser(0) // assertではあるべき姿を記述して、そうならない場合のエラーメッセージを第3引数に渡す。(演算子によるけど) assert.Nil(t, user, "we were not expecting a user wih id 0") assert.NotNil(t, err, "we wer...
package problem0189 import "testing" func TestSolve(t *testing.T) { nums := []int{1, 2, 3, 4, 5, 6, 7} rotateNewPlace(nums, 3) t.Log(nums) nums = []int{-1, -100, 3, 99} rotateNewPlace(nums, 2) t.Log(nums) nums = []int{1, 2, 3, 4, 5, 6, 7} rotate(nums, 3) t.Log(nums) nums = []int{-1, -100, 3, 99} rotate(...
package handler import ( "encoding/json" "net/http" "strconv" "github.com/gorilla/mux" "github.com/markus-azer/products-service/pkg/entity" "github.com/markus-azer/products-service/pkg/product" ) //Validation specifies data serialization/deserialization protocol. // DisallowUnknownFields https://maori.geek.nz...
// Copyright Jetstack Ltd. See LICENSE for details. package kubeconfig import ( "github.com/jetstack/vault-helper/pkg/cert" "github.com/sirupsen/logrus" ) type Kubeconfig struct { configPath string certKey64 string certCA64 string cert64 string cert *cert.Cert Log *logrus.Entry } func New(logger *l...
package models type Movie struct { ID int64 `json:"id"` Name string `json:"name"` Year int `json:"year"` Genre string `json:"genre"` Poster string `json:"poster"` }
package resolver import ( "github.com/taktakty/netlabi/models" genModels "github.com/taktakty/netlabi/models/generated" "context" ) type portResolver struct{ *Resolver } func (r *queryResolver) GetPort(ctx context.Context, input genModels.GetIDInput) (*models.Port, error) { var port models.Port port.ID = input....
package pie_test import ( "fmt" "github.com/elliotchance/pie/v2" "github.com/stretchr/testify/assert" "testing" ) var stringsUsingTests = []struct { ss []float64 transform func(float64) string expected []string }{ { nil, func(s float64) string { return "foo" }, nil, }, { []float64{}, ...
// Copyright 2014 The Sporting Exchange Limited. All rights reserved. // Use of this source code is governed by a free license that can be // found in the LICENSE file. // Package network handles the network config file. package network import ( "bytes" "encoding/xml" "fmt" "io/ioutil" "log" "os" "regexp" ) v...
package ciolite import ( "bytes" "fmt" "net/http" "net/http/httptest" "net/url" "os" "testing" "time" ) // TestNewCioLiteWithLogger tests the construction of CioLite func TestNewCioLite(t *testing.T) { t.Parallel() NewTestCioLite(t) } // TestNewCioLiteWithLogger tests the construction of CioLite and *TestL...
package agent import ( "context" "encoding/json" "fmt" "log" "net/http" "net/http/httputil" "net/url" "strings" "github.com/linqiurong2021/go-gateway/config" "github.com/linqiurong2021/go-gateway/etcd" "go.etcd.io/etcd/clientv3" ) // Agent 代理服务 type Agent struct { ProxyConfList []*etcd.EtcdProxyConfItem ...
package global import ( "github.com/casbin/casbin/v2" "github.com/casbin/casbin/v2/model" "github.com/casbin/xorm-adapter/v2" _ "github.com/go-sql-driver/mysql" ) // casbin 地址 https://casbin.org/docs/en/model-storage var CasbinEnforcer * casbin.Enforcer func InitCasbin( dsn string ) { adapter,_ := xormadapt...
package service import ( "context" "fmt" "github.com/go-ocf/cloud/grpc-gateway/pb" cqrsRA "github.com/go-ocf/cloud/resource-aggregate/cqrs" projectionRA "github.com/go-ocf/cloud/resource-aggregate/cqrs/projection" pbRA "github.com/go-ocf/cloud/resource-aggregate/pb" "github.com/go-ocf/kit/log" ) type resource...
package specerror import ( "fmt" rfc2119 "github.com/opencontainers/runtime-tools/error" ) // define error codes const ( // DefaultRuntimeLinuxSymlinks represents "While creating the container (step 2 in the lifecycle), runtimes MUST create default symlinks if the source file exists after processing `mounts`." D...
package slice import "strings" func RemoveDuplicates(strSlice []string) []string { allKeys := make(map[string]bool) var list []string for _, item := range strSlice { if _, value := allKeys[item]; !value { allKeys[item] = true list = append(list, item) } } return list } func ContainsElement(list []stri...
package main import ( "ethos/syscall" "ethos/ethos" "ethos/efmt" "log" ) import "math" func main () { me := syscall.GetUser() path := "/user/" + me + "/myDir/" fd, status := ethos.OpenDirectoryPath(path) if status != syscall.StatusOk { log.Fatalf ("Error opening %v: %v\n", path, status) } data ...
/* You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete. Given the integer n, return the number of complete rows of the staircase you will build. Example 1: Input: n = 5 Output: 2 ...
package gcp import ( "context" "fmt" "strings" "github.com/pkg/errors" "google.golang.org/api/compute/v1" "google.golang.org/api/googleapi" "github.com/openshift/installer/pkg/types/gcp" ) // getInstanceNameAndZone extracts an instance and zone name from an instance URL in the form: // https://www.googleapis...
package mysqlImpl import ( "github.com/HNB-ECO/HNB-Blockchain/HNB/db/common" "database/sql" "encoding/base64" "encoding/binary" "errors" "fmt" _ "github.com/go-sql-driver/MySQL" "strings" "time" ) type blkStore struct { db *sql.DB } func NewMySQLStore(ipport, username, passwd string) (*blkStore, error) { ...
package main import ( "net/http" "log" //"github.com/gorilla/mux" _ "github.com/go-sql-driver/mysql" "database/sql" "fmt" "html/template" "io" ) var t *template.Template var err error var db *sql.DB //var people []person func init(){ t=template.Must(template.ParseFiles("insertapi.gohtml","getpersonapi.goht...
package html_test import ( "bytes" "github.com/elliotchance/gedcom" "github.com/elliotchance/gedcom/html" "github.com/stretchr/testify/require" "testing" ) func TestNewIndividualEvents(t *testing.T) { doc, err := gedcom.NewDocumentFromString(` 0 @I492@ INDI 1 NAME Eva Ellen /Preece/ 2 SOUR @S14@ 3 DATA 4 TEXT R...
package wcpp import ( "fmt" "../../util" algos "../analysis" "../report" "../traceReplay" ) type ListenerAsyncSnd struct{} type ListenerAsyncRcv struct{} type ListenerSync struct{} type ListenerDataAccess struct{} type ListenerDataAccessDefault struct{} type ListenerDataAccessDefaultWRD struct{} type ListenerGo...
// Package grpccache provides caching for gRPC calls with HTTP // semantics. package grpccache
package nes import ( "encoding/gob" "fmt" ) const CPUFrequency = 1789773 // interrupt types const ( _ = iota interruptNone interruptNMI interruptIRQ ) // addressing modes const ( _ = iota modeAbsolute modeAbsoluteX modeAbsoluteY modeAccumulator modeImmediate modeImplied modeIndexedIndirect modeIndire...
package parser import ( "testing" "github.com/SealNTibbers/GotalkInterpreter/scanner" "github.com/SealNTibbers/GotalkInterpreter/testutils" "github.com/SealNTibbers/GotalkInterpreter/treeNodes" ) func TestNumberParser(t *testing.T) { inputString := `5.1` literalNode := InitializeParserFor(inputString).(*treeNo...
package main import "fmt" func result(grade float64) string { if grade >= 6 { return "Success" } return "Failed" } func main() { fmt.Println(result(6.2)) }
// // valid.go // Copyright (C) 2019 Grigorii Sokolik <g.sokol99@g-sokol.info> // // Distributed under terms of the MIT license. // package config import ( "encoding/json" ) type ValidInt struct { Valid bool Value int } func (v *ValidInt) UnmarshalJSON(b []byte) error { if err := json.Unmarshal(b, &v.Value); er...
package main import ( "crypto/rand" "encoding/base64" "log" ) func main() { b := make([]byte, 32) n, err := rand.Read(b) log.Println(n, err, b) //it will create random elements array of byte s := base64.StdEncoding.EncodeToString(b) log.Printf("s: %v", s) } func createRandomNumber() { }
package main // import ( // "log" // "net/http" // "os" // "strconv" // "github.com/fabioberger/coinbase-go" // "github.com/go-martini/martini" // ) // var o *coinbase.OAuth // func main() { // m := martini.New() // m.Use(martini.Logger()) // m.Use(martini.Recovery()) // m.Use(martini.Static("public")) //...
package main import ( "fmt" "time" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/sqlite" ) //Store device info type Device struct { Mac string `gorm: "primary_key;not null;unique"` Id int64 `gorm: "AUTO_INCREMENT"` Name string `gorm: "size:255"` Online bool...
package main import ( "io/ioutil" "log" "encoding/json" "fmt" "flag" "github.com/johncming/scel" ) var scelPath string func init() { flag.StringVar(&scelPath, "p", "", "scel path") flag.Parse() } func readScel() ([]byte, error) { return ioutil.ReadFile(scelPath) } func main() { data, err := readScel(...
package http import ( "errors" "net/http" "strings" "github.com/micromdm/nanomdm/log" "github.com/micromdm/nanomdm/mdm" "github.com/micromdm/nanomdm/service" ) // CheckinHandlerFunc decodes an MDM check-in request and adapts it to service. func CheckinHandlerFunc(svc service.Checkin, logger log.Logger) http.Ha...
package initialization import ( "MP1/errorchecker" "MP1/tcp" "bufio" "fmt" "os" "regexp" "strconv" "strings" ) // InitializeNode parses the specified process id from the command line, and returns a corresponding node, // as well as a list of potential nodes to send messages to. func InitializeNode() (node tcp...
package main import "fmt" import ( "math" "math/cmplx" "runtime" ) // A var statement can be at package or function level var test bool // A var declaration can include initializers, one per variable. var i, j int = 10, 11 //If an initializer is present, the type can be omitted; the variable will take the type of...
package mgr import ( "errors" "fmt" "io" "io/ioutil" "path/filepath" "strconv" "strings" "sync/atomic" "time" "os" "github.com/qiniu/log" "github.com/qiniu/logkit/cleaner" "github.com/qiniu/logkit/conf" "github.com/qiniu/logkit/parser" "github.com/qiniu/logkit/reader" "github.com/qiniu/logkit/sender"...
/* You are given four numbers. The first three are a, b, and c respectively, for the sequence: Tn=a*n^2 + bn + c You may take input of these four numbers in any way. The output should be one of two distinct outputs mentioned in your answer, one means that the fourth number is a term in the sequence (the above equati...
// +build windows package sys import ( "os" "github.com/haruno-bot/haruno/logger" "golang.org/x/sys/windows" ) // FixConsole 修复console的系统差异 func FixConsole() { in := windows.Handle(os.Stdin.Fd()) var inMode uint32 if err := windows.GetConsoleMode(in, &inMode); err == nil { var mode uint32 // Disable thes...
package assessment import ( md "github.com/ebikode/eLearning-core/model" ) // Payload Request data type Payload struct { ApplicationID uint `json:"application_id,omitempty"` QuestionID string `json:"question_id,omitempty"` SelectedAnswer string `json:"selected_answer,omitempty"` } // ValidationFields Err...
package web import ( "net/http" ) // StatusError is a sentinel error sent to RenderWithError to indicate that // a specific HTTP return code should be returned. type StatusError struct { Err error Code int } func (se *StatusError) Error() string { if se.Err != nil { return se.Err.Error() } return http.Statu...
package rrdp import ( "time" "github.com/cpusoft/goutil/belogs" "github.com/cpusoft/goutil/hashutil" "github.com/cpusoft/goutil/jsonutil" "github.com/cpusoft/goutil/osutil" "github.com/cpusoft/goutil/rrdputil" model "rpstir2-model" ) // connectRrdpUrlCh: whether connect to notifyurl, will tell others to remov...
package clusters import ( envoy_cluster "github.com/envoyproxy/go-control-plane/envoy/config/cluster/v3" envoy_endpoint "github.com/envoyproxy/go-control-plane/envoy/config/endpoint/v3" ) type StaticClusterConfigurer struct { Name string LoadAssignment *envoy_endpoint.ClusterLoadAssignment } var _ Clus...
package zedUpload_test import ( "fmt" "os" "testing" "github.com/lf-edge/eve/libs/zedUpload" ) const ( azureUploadFile = uploadFile azureDownloadDir = "./test/output/azureDownload/" ) var ( // parameters for AZURE datastore azureContainer = os.Getenv("TEST_AZURE_CONTAINER") azureAccountName = os.Getenv(...
package config import ( "encoding/base64" "github.com/pomerium/pomerium/pkg/cryptutil" ) // A PublicKeyEncryptionKeyOptions represents options for a public key encryption key. type PublicKeyEncryptionKeyOptions struct { ID string `mapstructure:"id" yaml:"id"` Data string `mapstructure:"data" yaml:"data"` // ba...