text
stringlengths
11
4.05M
package leetcode import "testing" func TestDominantIndex(t *testing.T) { if dominantIndex([]int{3, 6, 1, 0}) != 1 { t.Fatal() } if dominantIndex([]int{1, 2, 3, 4}) != -1 { t.Fatal() } }
package job import ( "bytes" "fmt" "io" "io/ioutil" "os" "os/signal" "strings" "syscall" "time" "github.com/dnephin/dobi/config" "github.com/dnephin/dobi/logging" "github.com/dnephin/dobi/tasks/client" "github.com/dnephin/dobi/tasks/context" "github.com/dnephin/dobi/tasks/image" "github.com/dnephin/dob...
// Copyright 2016 Kranz. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package context import ( "fmt" "gopkg.in/macaron.v1" "github.com/rodkranz/fakeApi/modules/base" ) // type Context struct { *macaron.Context } // HasApiError retu...
package constants const ( EMP_BASE_DIR = "/Users/adeep/workspace/icode/golang-tutorials/resources/employee" )
package sync import ( "sync" "github.com/kubernetes-sigs/aws-alb-ingress-controller/pkg/util/log" ) var logger *log.Logger func init() { logger = log.New("sync") } type RWMutex struct { m sync.RWMutex } func (r *RWMutex) RLock() { logger.DebugLevelf(3, "Requesting RLock.") r.m.RLock() logger.DebugLevelf(3,...
package main import ( "fmt" "github.com/zealic/go2node" ) func main() { channel, err := go2node.RunAsNodeChild() if err != nil { panic(err) } // Golang will output: {"hello":"child"} msg, err := channel.Read() if err != nil { panic(err) } fmt.Println(string(msg.Message)) // Node will output: {"hello...
package http import ( "context" "fmt" "io" "os" "os/exec" "testing" "github.com/ovh/venom" "github.com/stretchr/testify/require" ) func generateClientFile(t *testing.T) (string, string) { TLSClientKey, err := os.CreateTemp(os.TempDir(), "TLSClientKey.*.key") require.NoError(t, err) TLSClientKeyFileName :=...
package azure import ( "sync" "github.com/pkg/errors" typesazure "github.com/openshift/installer/pkg/types/azure" ) // Metadata holds additional metadata for InstallConfig resources that // does not need to be user-supplied (e.g. because it can be retrieved // from external APIs). type Metadata struct { session...
package entity import ( "strconv" "boiler/pkg/entity" ) // NewUser return a new User entity func NewUser(u *entity.User) *User { return &User{ ID: strconv.FormatInt(u.ID, 10), Name: u.Name, } } // NewEmail return a new Email entity func NewEmail(e *entity.Email) *Email { return &Email{ ID: strconv...
// Copyright (c) 2018 IoTeX // This is an alpha (internal) release and is not suitable for production. This source code is provided 'as is' and no // warranties are given as to title or non-infringement, merchantability or fitness for purpose and, to the extent // permitted by law, all liability for your use of the cod...
package search import ( "encoding/json" "os" ) const dataFile = "data/data.json" // Feed 定义 type Feed struct { Name string `json:"site"` URI string `json:"link"` Type string `json:"type"` } // RetrieveFeeds 读取并序列化feed数据文件 func RetrieveFeeds() ([]*Feed, error) { file, err := os.Open(dataFile) if err != nil {...
/** *@Author: haoxiongxiao *@Date: 2019/3/18 *@Description: CREATE GO FILE main */ package main import ( "testing" ) func Test_main(t *testing.T) { }
package has_cycle // ListNode provides interface for ListNode struct type ListNode interface { SetNext(*listNode) } type listNode struct { val int next *listNode } // SetNext sets $node to current listNode func (l *listNode) SetNext(node *listNode) { l.next = node } // NewListNode ... func NewListNode(val int)...
package main import ( "bytes" "encoding/json" "fmt" "log" "os" ) var data = ` { "user": "Name", "type": "deposit", "amount": 10.2 } ` // must start with Uppercase // Use field tag // Request is a bank transactions type Request struct { Login string `json:"user"` Type string `json:"type"` Amount floa...
package user import ( "github.com/BRO3886/findvity-backend/pkg" "github.com/BRO3886/findvity-backend/pkg/group" ) //Gender for user type Gender string const ( //Male enum Male Gender = "Male" //Female enum Female = "Female" //NonBinary enum NonBinary = "Non-Binary" //Undisclosed enum Undisclosed = "Prefer ...
package cmd import ( "context" "fmt" "log" "os" "strings" "github.com/grrtrr/clcv2" "github.com/pkg/errors" "github.com/spf13/cobra" "golang.org/x/sync/errgroup" ) // deleteFlags determine how to perform deletions var deleteFlags struct { recurse bool keep bool } func init() { delete.Flags().BoolVarP...
package ehttp import ( "bytes" "errors" "fmt" "net/http" "strconv" "testing" "time" "encoding/json" "io/ioutil" "github.com/enjoy-web/ehttp/swagger" "github.com/gin-gonic/gin" ) type ErrorMessage struct { Code int `json:"code"` Message string `json:"message"` Details string `json:"detail"` } co...
package dictparser import ( "regexp" "sort" "strings" ) type pair struct { Key string Value int } var regex *regexp.Regexp func init() { regex = regexp.MustCompile("[^a-zA-Z0-9А-Яа-я]+") } // Top10 - return top 10 words from dictionary func Top10(input string) []string { dictionary := map[string]int{} //...
package goSolution import "sort" func searchRange(nums []int, target int) []int { l := sort.SearchInts(nums, target) r := sort.SearchInts(nums, target + 1) if (0 > l || l >= len(nums)) || nums[l] != target { return []int{-1, -1} } else { return []int{l, r - 1} } }
package io import ( "io" ) func DebugWriter(w io.Writer) io.Writer { return &debug_writer{ w, } } type debug_writer struct { io.Writer } func (d debug_writer) Write(p []byte) (n int, err error) { return d.Writer.Write(p) }
package main import ( "fmt" "io/ioutil" "nitlev/adventofcode2020/day4/validation" "strings" ) func isSeparator(r rune) bool { return r == '\n' || r == ' ' } var mandatoryFields = []string{ "byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid", } var validFields = append(mandatoryFields, "cid") // Passport hol...
package main // Add func Add(a, b int) int { if b == 0 { return a } return Add(a^b, (a&b)<<1) } // Minus func Minus(a, b int) int { var i int = 1 for i > 0 && ((b & i) == 0) { i <<= 1 } for i > 0 { i <<= 1 b ^= i } return Add(a, b) } // Multi func Multi(a, b int) int { var ( ans int = 0 i int...
package usecase import "BottleneckStudio/keepmotivat.in/models" // UpdatePost interface ... type UpdatePost interface { UpdatePost(*models.Post) error } // UpdatePostUsecase ... type UpdatePostUsecase struct { repo models.PostRepository } // NewUpdatePostUsecase ... func NewUpdatePostUsecase(repo models.PostRepos...
package main import ( "Edwardz43/tgbot/config" "Edwardz43/tgbot/crawl/ptt" "Edwardz43/tgbot/err" "Edwardz43/tgbot/log" "Edwardz43/tgbot/log/zaplogger" "Edwardz43/tgbot/message/from" "Edwardz43/tgbot/worker" "Edwardz43/tgbot/worker/rabbitmqworker" "regexp" "strings" ) var logger log.Logger var jobWorker work...
package main import "fmt" // An IntSet is a set of small non-negative integers. // Its zero value represents the empty set. type IntSet struct { words []uint64 } func main() { w := IntSet{[]uint64{0, 1, 2, 3, 4, 5, 2, 3, 4}} fmt.Printf("Before Remove: %d\n", w) fmt.Printf("Remove Point : %d\n", w.Remove(2)) fmt...
package models import ( "time" "github.com/rs/xid" "github.com/thebigear/database" "github.com/tuvistavie/structomap" "gopkg.in/mgo.v2/bson" ) // DBTableExpressions collection name const DBTableExpressions = "expressions" // Expression structure type Expression struct { ID bson.ObjectId `json:...
package core import( "fmt" "os" "strconv" "log" "flag" ) //命令行接口 type CLI struct{ Blockchain *Blockchain } func (cli *CLI)createBlockChain(address string){ bc:=createBlockChain(address) //创建区块链 bc.DB.Close() fmt.Println("创建成功",address) } func (cli *CLI) getBalance(address string){ bc:=NewBlockchain(address...
// ˅ package main import ( "fmt" "strconv" "time" ) // ˄ // Display values with digits. type DigitObserver struct { // ˅ // ˄ // ˅ // ˄ } func NewDigitObserver() *DigitObserver { // ˅ return &DigitObserver{} // ˄ } func (self *DigitObserver) Update(number *Number) { // ˅ fmt.Println("Digit : " + ...
package model import ( "github.com/dgrijalva/jwt-go" "github.com/gin-gonic/gin" "time" ) // User table `user` type User struct { Username string `form:"username" json:"username"` Password string `form:"password" json:"password"` } // jwtCustomClaims are custom claims extending default ones. type JwtCustomClaims...
package types import ( // HOFSTADTER_START import // HOFSTADTER_END import ) /* Name: AuthBasicUserLoginRequest About: */ // HOFSTADTER_START start // HOFSTADTER_END start /* Where's your docs doc?! */ type AuthBasicUserLoginRequest struct { Password string `json:"password" xml:"password" yaml:"password" ...
package commands import ( "fmt" "os" "path/filepath" "testing" "github.com/spf13/cobra" "github.com/spf13/pflag" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestLoadXEnvCLIStringSliceValue(t *testing.T) { testCases := []struct { name string en...
package client const ( ErrMsgMissingURL = "missing required url" ErrMsgMissingAPIKey = "missing required apiKey" ErrMsgInvalidClient = "client missing required values" ErrMsgRecordsNotFound = "records not found" )
package zabbix import ( "encoding/json" "fmt" "net/http" "strings" ) func (api *API) HostGroupGet(name string) (map[string]interface{}, error) { payload := strings.NewReader(fmt.Sprintf(HostGroupGetTemplate, name, api.Session, api.ID)) req, err := http.NewRequest("POST", api.URL, payload) if err != nil { ret...
package pie import ( "math/rand" "testing" ) func BenchmarkFloatMedianSmall(b *testing.B) { benchmarkFloatMedian(b, 20) } func BenchmarkFloatMedianMedium(b *testing.B) { benchmarkFloatMedian(b, 800) } func BenchmarkFloatMedianLarge(b *testing.B) { benchmarkFloatMedian(b, 1000000) } func benchmarkFloatMedian(b *t...
/* * Copyright 2012-2019 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by a...
package database import ( "log" "github.com/solrac97gr/cryptoAPI/models" ) func SaveLog(method string, url string) { ref := DatabaseClient.NewRef("/") logRef := ref.Child("log") newLog, err := logRef.Push(FirebaseCtx, nil) if err != nil { log.Fatalln("Error pushing child node:", err) } if err := newLog.Set...
//line expr.y:17 package main import __yyfmt__ "fmt" //line expr.y:18 import ( "bytes" "errors" "fmt" "log" "unicode/utf8" ) var result_value int var result_error string //line expr.y:33 type exprSymType struct { yys int num int } const NUM = 57346 var exprToknames = []string{ "'+'", "'-'", "'*'", "'/'...
package server import ( "net/http" "reflect" "strconv" "github.com/ItsJimi/casa/logger" "github.com/ItsJimi/casa/utils" "github.com/labstack/echo" ) type addRoomReq struct { Name string } // AddRoom route create and add user to an room func AddRoom(c echo.Context) error { req := new(addRoomReq) if err := c...
package file import ( "io" "strconv" "time" ) // Single returns a single file writer. func Single(filename string) io.WriteCloser { return newSingle(filename) } // Rotate returns a rotating file writer. func Rotate(rotator Rotator) io.WriteCloser { return newRotate(rotator) } // PrefixSuffix returns a rotator ...
package interp import ( "fmt" "go.starlark.net/starlark" ) func ExecFile(filename string) error { predefined := starlark.StringDict{ "glob": starlark.NewBuiltin("glob", FnGlob), "register_object": starlark.NewBuiltin("register_object", FnRegisterObject), } thread := &starlark.Thread{Name: filenam...
package linkedlist import "fmt" type ListNode struct { Val int Next *ListNode } func newListNodes(val []int, cycle bool) *ListNode { if val == nil { return nil } l := &ListNode{ Val: val[0], } if len(val) == 1 { return l } pre := l vRemain := val[1:] for i, v := range vRemain { q := &ListNode{ ...
package facades import ( "github.com/gophergala2016/source/core/foundation" "github.com/gophergala2016/source/core/models" "github.com/gophergala2016/source/internal/services" ) type TagFacade struct { RootFacade } func NewTagFacade(ctx foundation.Context) TagFacade { return TagFacade{ RootFacade: NewRootFaca...
package main import ( "sync/atomic" "github.com/BorisBorshevsky/GolangDemos/common" "sync" ) func main() { Track(1000) } func Track(n int) { //common.TimeTrack(simpleRun, n, "simple") common.TimeTrack(mutexRun, n, "mutex") common.TimeTrack(atomicRun, n, "atomic") common.TimeTrack(semaphoreRun, n, "sem")...
package schedule import ( "time" "github.com/gorhill/cronexpr" ) type CronSchedule struct { Expression *cronexpr.Expression } // Cron returns a CronSchedule using the cron expression giving as parameter of the function. func Cron(expression string) CronSchedule { expr := cronexpr.MustParse(expression) return C...
// Copyright 2016 The Chromium Authors, 2018 Elco Industrie Automation GmbH. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package internal type SymbolType int const ( Invalid SymbolType = iota External Slack Error Dummy ) type Symb...
package controller import ( "aplicacoes/projeto-zumbie/config" "encoding/json" "fmt" "net/http" "github.com/gorilla/mux" ) // APP ... type APP struct { Versao int64 `json:"versao"` Descricao string `json:"descrisao"` Data string `json:"data"` Linguagem string `json:"linguagem"` } ...
package todo func NewList() *todoList { return &todoList{} } func NewTodo(title string) *todoModel { return &todoModel{ title: title, } }
package minedive type MinediveState int const ( MinediveStateNew MinediveState = iota + 1 MinediveStateConnecting ) const ( MinediveStateNewStr = "new" MinediveStateConnectingStr = "connecting" ) func (t MinediveState) String() string { switch t { case MinediveStateNew: return MinediveStateNewStr ca...
package main import "fmt" /* 接口定义了一个对象的行为规范,只定义规范不实现,由具体的对象来实现规范的细节 接口(interface)是一种抽象类型,是一组method的集合 定义格式如下: type 接口类型名 interface{ 方法名1(参数列表1) 返回值列表1 ... } 接口名,一般会在单词后面加上er。如Writer、Stringer 实现接口的条件 一个对象只要全部实现了接口中的方法,那么就实现了这个接口 接口类型变量 能够存储所有实现了该接口的实例 值接收者实现接口:不管结构体还是结构体指针类型都能赋值给接口变量 指针接收者实...
package rakuten import ( "context" "fmt" ) type TravelHotelChainParams struct{} type TravelHotelChainResponse struct { LargeClasses []struct { LargeClass []struct { LargeClassCode string `json:"largeClassCode"` HotelChains []struct { HotelChain struct { HotelChainCode string `json:"hotelCh...
// 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 in writing...
package block import ( "time" ) // Chain type Chain struct { Created time.Time Genesis *Block Difficulty int numberOfBlocks int } // IncrNumberOfBlocks func (c *Chain) IncrNumberOfBlocks() int { c.numberOfBlocks = c.numberOfBlocks + 1 return c.numberOfBlocks } // CreateChain func CreateChai...
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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/li...
// Good morning! Here's your coding interview problem for today. // This problem was asked by Microsoft. // Given a dictionary of words and a string made up of those words (no spaces), return the original sentence in a list. If there is more than one possible reconstruction, return any of them. If there is no possibl...
package task import ( trans "./../" "./../models" "cydex" "cydex/transfer" . "github.com/smartystreets/goconvey/convey" "testing" "time" ) func Test_XidResource(t *testing.T) { Convey("Test XidResource", t, func() { X := NewXidResource() X.Add("x1", "n1", 1*time.Second) So(X.Len(), ShouldEqual, 1) tim...
package yolopb func AllModels() []interface{} { return []interface{}{ // remote data &MergeRequest{}, &Commit{}, &Build{}, &Artifact{}, &Release{}, &Entity{}, &Project{}, // internal &Download{}, } }
package atomic import "sync/atomic" // IncWrapInt64 atomically increments a 64-bit signed integer, wrapping around zero. // // Specifically if p points to a value of math.MaxInt64 the result of calling // IncWrapInt64 will be 0. func IncWrapInt64(p *int64) int64 { for { o := atomic.LoadInt64(p) n := o + 1 if ...
package contact type Repository interface { New(*Contact) (*Contact, error) Update(*Contact) (*Contact, error) Delete(*Contact) error Get(uint) (*Contact, error) List() ([]*Contact, error) Close() }
package main import ( "fmt" "net/http" "html/template" "database/sql" _ "github.com/go-sql-driver/mysql" //"math/rand" "log" ) const conn_string = "root:imonomy@/goblog?charset=utf8" const driver_name = "mysql" var db, top_error = sql.Open(driver_name, conn_string) func indexPage(resp http.ResponseWriter, req *...
package robot import ( "fmt" "github.com/ev3go/ev3dev" ) var TOUCH int var COLOR int var IR int func saveIndex(st string, ind int) { switch st { case "lego-ev3-touch": TOUCH = ind case "lego-ev3-color": COLOR = ind case "lego-ev3-ir": IR = ind } } func GetSensors() []*ev3dev.Sensor { fmt.Println("sens...
package main import ( . "fmt" . "math" . "strconv" . "os" ) func main() { if len(Args) != 4 { Println("Usage: palette RR GG BB") return } r, err := ParseUint(Args[1], 16, 8) g, err := ParseUint(Args[2], 16, 8) b, err := ParseUint(Args[3], 16, 8) if err != nil { Println(err) return ...
package controller import ( "gopkg.in/go-playground/validator.v9" ) type AddQuestionParam struct { Name string `form:"name" json:"name" binding:"required"` NestedParam NestedParam } type NestedParam struct { Nested1 string `json:"nested1"` Nested2 int `form:"n2" json:"nested2" binding:"required,gt=0"`...
package main import ( "context" "flag" "fmt" "os" "testing" "time" runner "github.com/SentientTechnologies/studio-go-runner/internal/runner" "github.com/karlmutch/envflag" "github.com/karlmutch/errors" // MIT License ) var ( parsedFlags = false TestStopC = make(chan bool) TestRunMain string useGPU ...
package api import ( "encoding/json" "github.com/CuCTeMeH/gopher_translate/translator" "github.com/go-chi/render" "net/http" ) func postWord(w http.ResponseWriter, r *http.Request) { var word map[string]string err := json.NewDecoder(r.Body).Decode(&word) if err != nil { http.Error(w, err.Error(), http.Statu...
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package cmd import ( "fmt" "testing" "github.com/Azure/aks-engine/pkg/api/common" "github.com/Azure/aks-engine/pkg/api" "github.com/Azure/aks-engine/pkg/armhelpers" . "github.com/onsi/gomega" "github.com/pkg/erro...
package boltrepo import ( "bytes" "encoding/binary" "encoding/json" "github.com/boltdb/bolt" "github.com/scjalliance/drivestream/binpath" "github.com/scjalliance/drivestream/driveversion" "github.com/scjalliance/drivestream/resource" ) var _ driveversion.Sequence = (*DriveVersions)(nil) // DriveVersions acce...
package proc import ( "encoding/json" "fmt" "io/ioutil" "os" "os/exec" "strconv" "syscall" "time" "github.com/DemoHn/obsidian-panel/infra" "github.com/DemoHn/obsidian-panel/util" "github.com/moby/moby/pkg/reexec" ) const ( ipcPipe = 4 ) type ipcMessage struct { Status string `json:"status"` Message s...
// Copyright 2021 BoCloud // // 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 wri...
package main import "fmt" func check(param uint8) (uint8, error) { if param < 0 { return 0, fmt.Errorf("param is not nagative number param:%d", param) } return param * param, nil } func main() { m := 2 result, err := check(uint8(m)) if err != nil { fmt.Printf("Error: %v\n", err) return } fmt.Println(re...
package resolver import ( "github.com/taktakty/netlabi/testdata" "github.com/stretchr/testify/require" "strings" "testing" ) func TestHostQueries(t *testing.T) { testData := hostTestData t.Run("GetSingle", func(t *testing.T) { p := string(testData[0].ID) q := strings.Join([]string{`query {getHost(input:{id...
var _ = Resource("subtemplates", func() { DefaultMedia(SubtemplateMedia) BasePath("/api/subtemplate") Action("show", func() { Description("Get subtemplate") Routing(GET("/:subTemplateID")) Params(func() { Param("subTemplateID", Integer) }) Response(OK, SubtemplateMedia) Response(NotFound) Response(...
// Copyright 2020 The go-bindata Authors. All rights reserved. // Use of this source code is governed by a CC0 1.0 Universal (CC0 1.0) // Public Domain Dedication license that can be found in the LICENSE file. package bindata import ( "testing" ) func TestNewInputConfig(t *testing.T) { tests := []struct { desc s...
package delivery import ( "testing" "github.com/stretchr/testify/suite" ) type positionServiceTestSuite struct { baseTestSuite } func TestPositionService(t *testing.T) { suite.Run(t, new(positionServiceTestSuite)) } func (s *positionServiceTestSuite) TestChangeLeverage() { data := []byte(`{ "leverage": 21, ...
package bot func (r *Reinforcement) Init(Alpha, Gamma, RandomProb, TempDelta float64) { r.Alpha = Alpha r.Gamma = Gamma r.RandomProb = RandomProb r.TempDelta = TempDelta r.Rewards = make([][]float64, 22) for i := range r.Rewards { r.Rewards[i] = make([]float64, 3) } // If your score is 21, your best option i...
package domain import "gopkg.in/mgo.v2/bson" //Video ... type Video struct { VideoURL string `json:"video_url" bson:"video_url"` ThumbnailURL string `json:"thumbnail_url" bson:"thumbnail_url"` UserID bson.ObjectId `json:"user_id" bson:"user_id"` ChannelIDS []ChannelID `json:"channel_id...
// +build !windows package term import ( "io" "os" "os/exec" "strconv" "strings" ) // ClearLines will move the cursor up and clear the line out for re-rendering func ClearLines(out io.Writer, linecount int) { out.Write([]byte(strings.Repeat("\x1b[0G\x1b[1A\x1b[0K", linecount))) } const ( defaultTermWidth = ...
package remote import ( "testing" "github.com/stretchr/testify/assert" redfish "opendev.org/airship/airshipctl/pkg/remote/redfish" ) func TestUnknownRemoteType(t *testing.T) { rdCfg := RemoteDirectConfig{ RemoteType: "new-remote", RemoteURL: "http://localhost:8000", EphemeralNodeId: "test-node...
package main import ( "./lib" ) func main() { var a float64 = 5 var b float64 = 5 lib.Sum(a, b) }
// +build windows,!dockerless /* 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 applicabl...
package LiquidCrystal import ( "fmt" "time" "github.com/hybridgroup/gobot" "github.com/hybridgroup/gobot/platforms/i2c" ) const ( // commands LCD_CLEARDISPLAY byte = 0x01 LCD_RETURNHOME byte = 0x02 LCD_ENTRYMODESET byte = 0x04 LCD_DISPLAYCONTROL byte = 0x08 LCD_CURSORSHIFT byte = 0x10 LCD_FUNCT...
package ghosts type Banshee struct { } func (b Banshee) Name() string { return "Banshee" } func (b Banshee) Evidence() [3]string { return [3]string{"Freezing", "EMF 5", "Fingerprints"} }
package service import ( "go.uber.org/zap" "mix/test/codes" dto "mix/test/dto/core/transaction" entity "mix/test/entity/core/transaction" "mix/test/pb/core/transaction" "mix/test/utils/status" ) func (p *Transaction) createHotAccount(ctx *Context, in *transaction.CreateHotAccountInput, out *transaction.HotAccou...
package 数组 import ( "sort" ) func numSmallerByFrequency(queries []string, words []string) []int { queryFrequencyArray := getFrequencyArray(queries) wordsFrequencyArray := getFrequencyArray(words) sort.Ints(wordsFrequencyArray) result := make([]int, 0) for i := 0; i < len(queryFrequencyArray); i++ { result = a...
package main import "fmt" func main() { fmt.Println(verifyPostorder([]int{1, 6, 3, 2, 5})) fmt.Println(verifyPostorder([]int{1, 3, 2, 6, 5})) } func verifyPostorder(postorder []int) bool { var verify func(left, right int) bool verify = func(left, right int) bool { if left >= right { return true } roo...
/* Copyright 2021 The KubeVela 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, so...
package db import ( "database/sql" "fmt" "time" "github.com/danielkvist/botio/proto" // postgres driver _ "github.com/jackc/pgx/v4" ) // Postgres wraps a sql.DB client for PostgreSQL and // satisfies the DB interface. type Postgres struct { Host string Port string User stri...
package app import "github.com/bryanl/dolb/entity" // Cluster manages load balancer agent clusters. type Cluster interface { Bootstrap(lb *entity.LoadBalancer, bootstrapConfig *BootstrapConfig) (chan int, error) }
/* * Minio Cloud Storage, (C) 2016 Minio, 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 la...
package generate import ( "encoding/json" "errors" "net/url" ) // AdditionalProperties handles additional properties present in the JSON schema. type AdditionalProperties Schema // Schema represents JSON schema. type Schema struct { // SchemaType identifies the schema version. // http://json-schema.org/draft-07...
package openapi import "C" import ( "context" "encoding/json" "github.com/getkin/kin-openapi/openapi3filter" "github.com/gin-gonic/gin" "net/http" ) func ValidateRequests(path string) gin.HandlerFunc { spec := openapi3filter.NewRouter().WithSwaggerFromFile(path) errorEncoder := &openapi3filter.ValidationErr...
package dcmdata import ( "github.com/grayzone/godcm/ofstd" ) /** a class handling the DICOM dataset format (files without meta header) */ type DcmDataset struct { DcmItem OriginalXfer E_TransferSyntax /// original transfer syntax of the dataset CurrentXfer E_TransferSyntax /// current transfer syntax of the da...
package practice01 import ( "os" "fmt" ) //获取操作系统名称和path环境变量 func GetOSInfo() { var goos string= os.Getenv("GOOS") fmt.Printf("the operating system is: %s \n", goos) path := os.Getenv("PATH") fmt.Printf("the os path is: %s \n", path) }
package tomlconf import ( "fmt" ) // Game holds the config for a Game instance type Game struct { Name string AutoStart bool `toml:"auto_start"` AutoRestart int `toml:"auto_restart"` Comment string `comment:"A message to be added to the status line of this Game"` Transport ConfigHolder PreR...
package main import ( "fmt" _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx" ) var db *sqlx.DB //是一个连接池对象 func initDb() (err error) { //数据库信息 dsn := "root:root@tcp(127.0.0.1:3306)/goday10" //连接数据库 //db 全局的db db, err = sqlx.Connect("mysql", dsn) if err != nil { return } db.SetMaxOpenConns(10)...
package service import ( . "CoffeeMachineDunzo/domain" "fmt" ) type CoffeeMachineService struct { coffeeMachine *CoffeeMachine } func NewCoffeeMachineService(machine *CoffeeMachine) *CoffeeMachineService { return &CoffeeMachineService{ coffeeMachine: machine, } } func (service *CoffeeMachineService) MakeBeve...
package suites import ( "github.com/go-rod/rod" "github.com/stretchr/testify/suite" ) func NewRodSuite(name string) *RodSuite { return &RodSuite{ BaseSuite: &BaseSuite{ Name: name, }, } } // RodSuite is a go-rod suite. type RodSuite struct { *BaseSuite *RodSession *rod.Page } type BaseSuite struct { ...
package http import ( "net/http" "time" ) type Client interface { Do(r *http.Request) (*http.Response, error) } func NewDefaultClient() *http.Client { return NewClient(5 * time.Second) } func NewClient(timeout time.Duration) *http.Client { return &http.Client{ Timeout: timeout, } }
package pgsql import ( "testing" ) func TestMoney(t *testing.T) { testlist2{{ valuer: MoneyFromInt64, scanner: MoneyToInt64, data: []testdata{ {input: int64(0), output: int64(0)}, {input: int64(99), output: int64(99)}, {input: int64(120), output: int64(120)}, }, }, { data: []testdata{ {input...
package main import ( "bytes" "crypto/tls" "io" "log" "mime" "net" "net/http" "path" "sync" "time" "github.com/remogatto/ftpget" ) // A TLSRedialTransport is an http.RoundTripper that sends all the requests // over a TLS connection to one server. It will automatically reconnect to the // server as needed....
package fetchall import ( "net/http" "os" "testing" ) func TestRunFetchAll(t *testing.T) { // URLs for requesting urls := []string{"https://tanaikech.github.io/"} p := &Params{} for _, e := range urls { req, err := http.NewRequest("GET", e, nil) if err != nil { os.Exit(1) } r := &...