text
stringlengths
11
4.05M
package pgsql import ( "testing" "time" ) func TestTstzRangeArray(t *testing.T) { dublin, err := time.LoadLocation("Europe/Dublin") if err != nil { t.Fatal(err) } tokyo, err := time.LoadLocation("Asia/Tokyo") if err != nil { t.Fatal(err) } testlist2{{ valuer: TstzRangeArrayFromTimeArray2Slice, scan...
package _1_double_foreach import ( "fmt" ) // https://zhuanlan.zhihu.com/p/75441551 func WorkChan() { workers := 3 // 定义3个工作者数量 flag := make(chan struct{}) // 定义一个工作完成 chan 旗 wait := make(chan struct{}) // 定义一个全部完成的标记 chan worker := func(fn func()) { // 创建一个干完活的方法,也就是向通道发送一条信息 fn() flag <- str...
// ˅ package main import "fmt" // ˄ type Display struct { // ˅ // ˄ // Column width columns int // Number of rows rows int // ˅ // ˄ } // Show all func (self *Display) Show(iDisplay IDisplay) { // ˅ for i := 0; i < iDisplay.GetRows(); i++ { fmt.Println(iDisplay.GetLineText(i)) } // ˄ } // ˅ // ...
package filter const ( MetricWhitelist = "metricWhitelist" MetricBlacklist = "metricBlacklist" MetricTagWhitelist = "metricTagWhitelist" MetricTagBlacklist = "metricTagBlacklist" TagInclude = "tagInclude" TagExclude = "tagExclude" ) // Configuration for filtering metrics. // All the filter...
package solutions import ( "fmt" "testing" ) func TestIsPalindrome(t *testing.T) { t.Run("Test push", func(t *testing.T) { stack := Constructor() stack.Push(1) want := fmt.Sprint([]int{1}) result := fmt.Sprint(stack.stack) if want != result { t.Errorf("got %v, want %v", result, want) } stack.Pus...
package ctl import ( "fmt" "log" "testing" "time" "github.com/vhaoran/vchat/lib" "github.com/vhaoran/vchat/lib/yredis" ) func Test_redis_set(t *testing.T) { // load config opt := &lib.LoadOption{ LoadMicroService: false, LoadEtcd: false, LoadPg: false, //-----------attention here---...
package product type Product struct { ID int `json:"id"` Name string `json:"name" bson:"name"` Amount int `json:"amount" bson:"amount"` Stock int `json:"stock" bson:"stock"` }
package hello const testVersion = 2 // HelloWorld greets the user. // If the user does not supply an argument, it returns "Hello, World!" // If the user supplies an argument, it returns "Hello, <arg>!" func HelloWorld(name string) string { if name == "" { return "Hello, World!" } return "Hello, " + name + "!" }...
package raft import ( "fmt" "testing" "time" ) func ThreeNodeRaft() (*RaftNode, *RaftNode, *RaftNode) { members := []string{"localhost:6868", "localhost:6969", "localhost:7070"} conf1 := CreateConfig("localhost:6868", members[1:]) conf3 := CreateConfig("localhost:6969", append([]string{members[0]}, []string{mem...
package main import ( //"golang.org/x/crypto/nacl/secretbox" //"crypto/rand" //"io" "crypto/rand" "encoding/base64" "encoding/hex" "log" "math/big" "golang.org/x/crypto/scrypt" "github.com/aws/aws-lambda-go/lambda" ) //GenerateScryptKey Generate scypt kets on the basis of saltByes and PassphraseBytes fun...
package rt import ( "github.com/pkg/errors" "github.com/suborbital/reactr/rcap" "github.com/suborbital/vektor/vlog" ) var ErrCapabilityNotAvailable = errors.New("capability not available") // Capabilities define the capabilities available to a Runnable type Capabilities struct { Auth rcap.AuthProvider ...
package main import "fmt" // 338. 比特位计数 // 给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数目并将它们作为数组返回。 // 进阶: // 给出时间复杂度为O(n*sizeof(integer))的解答非常容易。但你可以在线性时间O(n)内用一趟扫描做到吗? // 要求算法的空间复杂度为O(n)。 // 你能进一步完善解法吗?要求在C++或任何其他语言中不使用任何内置函数(如 C++ 中的 __builtin_popcount)来执行此操作。 // https://leetcode-cn.com/probl...
package users import ( "crypto/md5" "encoding/hex" "testing" ) //TODO: add tests for the various functions in user.go, as described in the assignment. //use `go test -cover` to ensure that you are covering all or nearly all of your code paths. func TestNewUser_Validate(t *testing.T) { cases := []struct { email...
package gcp import ( "encoding/json" "fmt" "github.com/pkg/errors" machineapi "github.com/openshift/api/machine/v1beta1" "github.com/openshift/installer/pkg/types" ) const ( kmsKeyNameFmt = "projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s" // ocpDefaultLabelFmt is the format string for the default label ...
package base type Client interface { // User calling this method will require a node to do some action. // In this homework, it will be used by test cases to start a test. SendCommand(s *State, command Command) }
package main import ( // "flag" "fmt" "regexp" // "strconv" // "strings" ) type operator string const ( MUL = "*" DIV = "/" ADD = "+" SUB = "-" ) type polynome struct { term int int } func isOperator(s string) bool { if s == MUL || s == DIV || s == ADD || s == SUB { return true } return false } fu...
package main import ( "crypto/rand" "encoding/binary" "fmt" "io" "net" "github.com/katzenpost/noise" ) const ( macLen = 16 maxMsgLen = 65535 msg2Len = 1680 //msg2Len = 96 ) func main() { clientStaticKeypair, err := noise.DH25519.GenerateKeypair(rand.Reader) if err != nil { panic(err) } cs := no...
package day1 import ( "fmt" "io/ioutil" "os" "strconv" "strings" ) //DayOneTwo Day one task two func DayOneTwo() { input, err := ioutil.ReadFile("./1/input.txt") if err != nil { fmt.Println(err) os.Exit(1) } sliceData := strings.Split(string(input), "\n") ans := 0 for i := 0; i < len(sliceData); i+...
package Problem0504 import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) // tcs is testcase slice var tcs = []struct { num int ans string }{ { 0, "0", }, { 100, "202", }, { -7, "-10", }, // 可以有多个 testcase } func Test_convertToBase7(t *testing.T) { ast := assert.New(t) for _...
package main import ( "./backup" heis "./heisdriver" //"./simulator/client" "./network" "./operator" "encoding/json" "fmt" "os" "time" ) /****************************************** The ******************************************/ const ( MAX_NUM_ELEVS = 10 N_FLOORS = heis.N_FLOORS UP = heis...
package main // Create a simple homepage. func main() { pageCreator := NewPageCreator() pageCreator.CreateSimpleHomepage("emily@example.com", "Homepage.html") }
package json type Task struct { }
// Copyright 2018 Diego Bernardes. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package repository import ( "context" "encoding/json" "fmt" "net/url" "time" "github.com/pkg/errors" "github.com/diegobernardes/flare" ) // Document...
package hashtable import ( "testing" ) func TestUncommonFromSentences(t *testing.T) { a := "this apple is sweet" b := "this apple is sour" if !equalArrayString(uncommonFromSentences(a, b), []string{"sweet", "sour"}) { t.Fail() } }
// 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 main import ( // "context" "log" aws "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" // "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go/service/dlm" ) func main() { // Load the Shared AWS Configuration (~/.aws/config) // config, err := config.LoadDefaultConfi...
package main import ( "fmt" "github.com/tealeg/xlsx" "io/ioutil" "os" "path" "strings" ) const ( maxDiffSize = 100 ) type diff struct { row int col int str1 string str2 string } func (d diff) String() string { return fmt.Sprintf("%d:%d | %-10s | %-10s |", d.row, d.col, d.str1, d.str2) } func main() {...
package schemes import "image/color" // Classic is a color scheme that goes through a variety of colors. var Classic []color.Color func init() { Classic = []color.Color{ color.RGBA{R: 0xff, G: 0xed, B: 0xed, A: 0xff}, color.RGBA{R: 0xff, G: 0xe0, B: 0xe0, A: 0xff}, color.RGBA{R: 0xff, G: 0xd1, B: 0xd1, A: 0xf...
package main import ( "fmt" "path/filepath" "testing" "time" "github.com/stretchr/testify/assert" ) func TestStartStop(t *testing.T) { dir := setupTestProject(t) timer, err := NewTimer(dir) assert.NoError(t, err) timer.Start() timer.Stop() assert.False(t, timer.running) assert.True(t, timer.IsPaused()...
package main import "strconv" const MaxUint = ^uint(0) const MinUint = 0 const MaxInt = int(MaxUint >> 1) const MinInt = -MaxInt - 1 func atoi(s string) int { i, err := strconv.ParseInt(s, 10, 32) if err != nil { panic(err) } return int(i) } func abs(x int) int { if x < 0 { return -x } else { return x } }...
package version const DriverVersion = "v1.0.0"
package easy import ( "fmt" "testing" ) func Test88(t *testing.T) { a := []int{1,2,3,0,0,0} b := []int{2,5,6} merge(a,3,b,3) fmt.Println(a) } func merge( nums1 []int, m int, nums2 []int, n int) { for m > 0 || n > 0 { if n == 0 { break } if m == 0 { nums1[n-1] = nums2[n-1] n-- continue } ...
package main const input = `17-19 p: pwpzpfbrcpppjppbmppp 10-11 b: bbbbbbbbbbbj 17-19 c: ccccccccccfrcctcccjc 8-10 k: kkkkkkkfkkks 13-14 l: lvllvllllslllv 8-9 n: nhhcnnnknnqnb 1-3 d: pdbdfbws 5-6 v: vvvgvb 7-8 x: gxcxtwbl 2-15 r: xlgrwqpcsqtrvfrrt 9-14 l: glnldlllllllln 2-3 r: vxnw 8-9 g: gfggczgkgggjgg 4-5 d: ddddh 6...
package cloudflare import ( "testing" "github.com/stretchr/testify/assert" ) func TestPagination_Done(t *testing.T) { testCases := map[string]struct { r ResultInfo expected bool }{ "missing ResultInfo pagination information": { r: ResultInfo{Page: 1}, expected: true, }, "total pages...
package kucoin import ( "crypto/hmac" "crypto/sha256" "encoding/base64" "time" ) // Signer interface contains Sign() method. type Signer interface { Sign(plain []byte) []byte } // Sha256Signer is the sha256 Signer. type Sha256Signer struct { key []byte } // Sign makes a signature by sha256. func (ss *Sha256Si...
package Problem0352 import ( "testing" "github.com/stretchr/testify/assert" ) func Test_Constructor(t *testing.T) { ast := assert.New(t) sr := Constructor() sr.Addnum(1) ast.Equal([]Interval{Interval{Start: 1, End: 1}}, sr.Getintervals()) sr.Addnum(7) ast.Equal([]Interval{ Interval{Start: 1, End: 1}, ...
//go:build !windows // +build !windows // Copyright 2020 Antrea 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 ...
package handlers import ( "io" "log" "net/http" "os" "strconv" "github.com/matscus/Hamster/MicroServices/scenario/scn" "github.com/matscus/Hamster/Package/Scenario/scenario" ) //UpdateOrDeleteScenario - handle for update scenario values to table func UpdateOrDeleteScenario(w http.ResponseWriter, r *http.Reque...
package byte_order import ( "fmt" "testing" ) func TestBytesToInt64(t *testing.T) { fmt.Println(BytesToInt64([]byte{0, 0,0,0,0,0,4,0})) // 1024 fmt.Println(BytesToInt642([]byte{0, 0,0,0,0,0,4,0})) // 1024 fmt.Println(LBytesToInt642([]byte{0, 0,0,0,0,0,4,0})) // 1125899906842624 } func TestInt64ToBytes(t *tes...
package main import ( "bytes" "flag" "fmt" "os" "os/exec" "regexp" "sort" "strconv" "strings" "time" ) var ( callsExpr = regexp.MustCompile("^(.*?)`(.*?) (\\d+)$") ) // Trace call. type TraceCall struct { // Module. Module string // Method. Method string // Calls. Calls uint64 } // Trace. type Tr...
package problem0026 import ( "testing" "github.com/stretchr/testify/assert" ) func Test_removeDuplicates(t *testing.T) { tests := []struct { input []int expected int }{ { []int{}, 0, }, { []int{1, 1, 2}, 2, }, { []int{0, 0, 1, 1, 1, 2, 2, 3, 3, 4}, 5, }, } for _, test := ra...
package models import ( "github.com/astaxie/beego" "github.com/astaxie/beego/orm" _ "github.com/go-sql-driver/mysql" ) func RegisterDB() { //注册驱动 orm.RegisterDriver("mysql", orm.DRMySQL) //数据库链接 //注册默认数据库 var db_url string = beego.AppConfig.String("username_DB") + ":" + beego.AppConfig.String("password_DB") +...
package cli import ( "fmt" "os" "os/exec" "github.com/urfave/cli" "github.com/LeoNdV001/brainfuck/src/interpreter" ) // registerCLICommands registers available commands func (bf BrainfuckCLI) registerCLICommands() { cmd := cli.Command{ Name: "compiler", Usage: "Run and check for Brainfuck CLI", Subcomm...
package interfacez import ( "golangtuts/fileMgmt" ) type FileHandlerImpl string func (filePath FileHandlerImpl) ReadFileInMem() string { return fileMgmt.ReadFileInMem(string(filePath)) } func (filePath FileHandlerImpl) ReadInSmallChunks() { fileMgmt.ReadInSmallChunks(string(filePath)) } func (filePath FileHandl...
package interfaces import ( "testing" applicationMocks "flamingo.me/csrf/application/mocks" "flamingo.me/flamingo/v3/framework/web" "flamingo.me/form/domain" "github.com/stretchr/testify/suite" ) type ( CsrfFormExtensionTestSuite struct { suite.Suite formExtension *CsrfTokenFormExtension service *...
// +build OMIT package sample import "encoding/json" //START OMIT func LoadStruct(data []byte) (output JSONData, err error) { err = json.Unmarshal(data, &output) return output, err } //END OMIT
// Copyright 2017 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...
/* * KSQL * * This is a swagger spec for ksqldb * * API version: 1.0.0 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package swagger type ModelError struct { Type_ string `json:"@type,omitempty"` ErrorCode float64 `json:"error_code,omitempty"` Message str...
package struct_util // ------------------------------------------ 1. 堆(开始) ------------------------------------------ // MyHeap 堆。 type MyHeap struct { data []interface{} // 堆数据。 compareValue func(interface{}, interface{}) bool // 堆内保证: compareValue(堆顶元素, 非堆顶元素) 必为 true。 lastIndex ...
package tcp import ( "strconv" "testing" "github.com/phayes/freeport" "github.com/stretchr/testify/require" ) func TestServer(t *testing.T) { t.Run("NewServer", func(t *testing.T) { port, err := freeport.GetFreePort() require.NoError(t, err) server, err := NewServer(":" + strconv.Itoa(port)) require.NoE...
// +build linux package volume import "syscall" // Fallocate uses the linux Fallocate syscall, which helps us to be // sure that subsequent writes on a file just created will not fail, // in addition, file allocation will be contigous on the disk func Fallocate(fd int, offset int64, len int64) error { // No need to...
package generate import ( "encoding/json" "errors" "fmt" "io/ioutil" "net/url" "os" "path" ) // ReadInputFiles from disk and convert to JSON schema. func ReadInputFiles(inputFiles []string, schemaKeyRequired bool) ([]*Schema, error) { schemas := make([]*Schema, len(inputFiles)) for i, file := range inputFile...
package controller import ( "encoding/json" "fmt" "github.com/go-martini/martini" "github.com/go-redis/redis/v8" "io/ioutil" "log" "net/http" "projja_exec/graph" "projja_exec/model" "strconv" "sync" "time" ) type controller struct { Rds *redis.Client Projects map[int64]*usingProject Mutex *sync...
package appenv import ( "log" "os" "strings" ) // Validate validates environment variables before app startup // Exits/stops the app on validation failure func Validate() { // ------------------------------------ // Database variables // ------------------------------------ validateNotEmptyF("DATABASE_URL") v...
package rivescript // Loading and Parsing Methods import ( "bufio" "fmt" "os" "path/filepath" "strings" ) /* LoadFile loads a single RiveScript source file from disk. Parameters path: Path to a RiveScript source file. */ func (rs *RiveScript) LoadFile(path string) error { rs.say("Load RiveScript file: %s", ...
package main import ( "fmt" "net/http" "time" ) func main() { urls := []string{ "http://google.com", "http://facebook.com", "http://stackoverflow.com", "http://golang.org", "http://amazon.com", } /* Create a channel to use for communication between go routines and main routine Sending data wit...
package gender import ( "bytes" "errors" ) var ( ErrInvalidGender = errors.New("Invalid Gender value") ) type Gender uint8 const ( Unknown Gender = 0 + iota Male Female ) var genderKeys = []string{"unknown", "male", "female"} // String fmt.Stringer func (z Gender) String() string { if z >= Unknown && z <= ...
package auth import ( "strings" "github.com/pkg/errors" "gopx.io/gopx-common/str" ) const ( authTypeAuthKey = "AuthKey" ) // AuthenticationType represents the http request auth type. type AuthenticationType interface { Name() string } // AuthenticationTypeAuthKey represents the Auth Key http auth type. type A...
package reconciler import ( "github.com/operator-framework/api/pkg/operators/v1alpha1" ) type GrpcAddressRegistryReconciler struct { now nowFunc } var _ RegistryEnsurer = &GrpcAddressRegistryReconciler{} var _ RegistryChecker = &GrpcAddressRegistryReconciler{} var _ RegistryReconciler = &GrpcAddressRegistryReconci...
package main import ( "time" ) // Config ... type Config struct { expiry time.Duration }
package aoc2020 import ( "testing" aoc "github.com/janreggie/aoc/internal" "github.com/stretchr/testify/assert" ) func Test_readPassportFile(t *testing.T) { assert := assert.New(t) scanned, err := readPassportFile(day04sampleInput) assert.NoError(err) assert.ElementsMatch( scanned, []passport{ {ecl: "g...
// Copyright 2020 The Operator-SDK 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 ...
// 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 statse import ( "fmt" "opentsp.org/internal/github.com/vaughan0/go-zmq" ) // ListenAddr is the listen address of Statse sink service. con...
package x // GENERATED BY XO. DO NOT EDIT. import ( "errors" "strings" //"time" "ms/sun/shared/helper" "strconv" "github.com/jmoiron/sqlx" ) // (shortname .TableNameGo "err" "res" "sqlstr" "db" "XOLog") -}}//(schema .Schema .Table.TableName) -}}// .TableNameGo}}// FileMsg represents a row from 'sun_file.file_m...
package rpcd import ( "github.com/Cloud-Foundations/Dominator/lib/srpc" "github.com/Cloud-Foundations/Dominator/proto/hypervisor" ) func (t *srpcType) GetRootCookiePath(conn *srpc.Conn, request hypervisor.GetRootCookiePathRequest, reply *hypervisor.GetRootCookiePathResponse) error { *reply = hypervisor.GetRootCo...
package controllers import ( "github.com/astaxie/beego" middleware "scholarship/middlewares" "scholarship/models" ) type RechargeController struct { beego.Controller } // @Title Get // @Description test2 recharge hide two Paramter userFrom & password // @Param userTo query string true "userName of who rece...
package sqldb import "upper.io/db.v3/lib/sqlbuilder" // represent a straight forward change that is compatible with all database providers type ansiSQLChange string func (s ansiSQLChange) apply(session sqlbuilder.Database) error { _, err := session.Exec(string(s)) return err }
package websocket import ( "context" "github.com/gorilla/websocket" "github.com/k0kubun/pp" "github.com/tech-botao/logger" "strings" "time" ) func ExampleHbg() { ctx, cancel := context.WithCancel(context.Background()) client := NewBuilder().URL("wss://api.huobi.pro/ws"). Subs([]string{`{"id": "id1", "sub":...
package main import ( "crypto/sha1" "encoding/hex" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "os" "strings" "time" "github.com/boltdb/bolt" "github.com/urfave/cli" ) const doneBucketStr = "done" var downloadList, downloadDir string func main() { app := cli.NewApp() app.Name = "downloadCli" a...
package base import ( "fmt" "strings" "github.com/astaxie/beego" "github.com/imsilence/gocmdb/server/utils" ) type BaseController struct { beego.Controller } func (c *BaseController) Prepare() { controller, action := c.GetControllerAndAction() controller, action = strings.TrimSuffix(utils.Snake(controller), ...
package main func main() { print("1") }
package dsmr4p1 import ( "bytes" "encoding/json" "errors" "fmt" "strings" ) // Value holds a P1 value type Value struct { Val float64 Unit string } func (v *Value) UnmarshalJSON(b []byte) error { var err error v.Val, v.Unit, err = parseValue(strings.Trim(string(b), "\"")) return err } type GasMeterValue ...
package devutil import ( "io/ioutil" "net/http" "net/http/httptest" "os" "testing" ) func TestMux(t *testing.T) { tmpFile, err := ioutil.TempFile("", "TestMux") must(err) tmpFile.Write([]byte("<html><body>contents of temp file</body></html>")) tmpFile.Close() defer os.Remove(tmpFile.Name()) m := NewMux()...
package main import ( "github.com/kataras/iris" "github.com/kataras/iris/mvc" ) type lotterController struct { Ctx iris.Context } func newApp() *iris.Application { app:=iris.New() mvc.New(app.Party("/",)) return app } func main() { app:=newApp() app.Run(iris.Addr(":8080")) }
package main import "fmt" func main() { //Arrays Declaration I var fnum[3] float64 fnum[0]=12 fnum[1]=1.23 fnum[2]=8.27 fmt.Println(fnum[2]) //Arrays Declaration II fnum2 := [3]float64 {1,2,3} //Loops in Arrays for i, value := range fnum2 { fmt.Println(value,i) } for _, value := range fnum2 { fmt.Pr...
package main import ( "unsafe" "golang.org/x/sys/windows" ) func wndProc(hWnd uintptr, msg uint32, wParam, lParam uintptr) uintptr { switch msg { case WM_DESTROY: PostQuitMessage(0) default: r, _ := DefWindowProc(hWnd, msg, wParam, lParam) return r } return 0 } func createMainWindow() (uintptr, error) ...
package plik import ( "bytes" "fmt" "io" "os" "testing" "github.com/stretchr/testify/require" "github.com/root-gg/plik/server/common" ) func TestGetServerVersion(t *testing.T) { ps, pc := newPlikServerAndClient() defer shutdown(ps) err := start(ps) require.NoError(t, err, "unable to start plik server") ...
package apiv3 import ( "errors" "os" "strconv" ) var debug bool var ErrIdOrNameNotSpecified = errors.New("Either an ID or Name must be specified") func init() { debug, _ = strconv.ParseBool(os.Getenv("GOXTREMIO_DEBUG")) } type Ref struct { Href string `json:"href"` Name string `json:"name"` SysName st...
package service import ( "github.com/msvetkov/notes-app/pkg/domain" "github.com/msvetkov/notes-app/pkg/repository" ) type UserService struct { repo repository.User } func NewUserService(repo repository.User) *UserService { return &UserService{repo: repo} } func (s *UserService) GetById(userId int) (domain.User,...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //179. Largest Number //Given a list of non negative integers, arrange them such that they form the largest number. //For example, given [3, 30, 34, 5,...
package leetcode /*A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element. Now given an M x N matrix, return True if and only if the matrix is Toeplitz. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/toeplitz-matrix 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/ func isToeplitzMatrix(m...
// Licensed to SolID under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. SolID licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use this file except in compli...
package main import ( "fmt" "strconv" ) func main() { num := 1221 fmt.Println(translateNum(num)) } func translateNum(num int) int { s := strconv.Itoa(num) n := len(s) dp := make([]int, n+1) dp[0] = 1 dp[1] = 1 for i := 2; i <= n; i++ { if s[i-2] == '1' || (s[i-2] == '2' && s[i-1] <= '5') { dp[i] =...
package hash import ( "strconv" "github.com/gogo/protobuf/proto" "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" "github.com/gogo/protobuf/protoc-gen-gogo/generator" ) type plugin struct { *generator.Generator generator.PluginImports fmtPkg generator.Single bytesPkg generator.Single } var E_Serializ...
package gogo import ( "crypto" "math" "net/http" "strings" "sync" "time" ) const ( abortIndex = math.MaxInt8 / 2 minSlowdownMs = 1 * time.Millisecond ) type Context struct { Response Responser Request *http.Request Params *AppParams Server *AppServer Config *AppConfig Logger Logger mux ...
package realm import ( "bytes" "encoding/json" "errors" "fmt" "io" "mime" "mime/multipart" "net/http" "os" "github.com/10gen/realm-cli/internal/utils/api" ) const ( dependenciesPathPattern = appPathPattern + "/dependencies" dependenciesArchivePathPattern = dependenciesPathPattern + "/archive" dep...
package crypto import ( "crypto/sha256" "fmt" ) // https://pkg.go.dev/crypto/sha256 func SumSha256(s string) (sha string) { sum := sha256.Sum256([]byte(s)) sha = fmt.Sprintf("%x", sum) return }
package gozip import ( "testing" "github.com/johnolafenwa/gozip/writer" ) func TestWriter(t *testing.T) { writer, err := writer.New("test.zip") if err != nil { t.Errorf("%v", err) return } if err != nil { t.Errorf("%v", err) } err = writer.AddFile("testfiles/walk.jpg", "") if err != nil { t.Error...
package sstable import ( "fmt" ) func ExampleVerifyChecksum_pass() { err := VerifyChecksum(0x21f1576e, []byte("abc")) fmt.Printf("%#v\n", err) fmt.Println(err) // Output: // <nil> // <nil> } func ExampleVerifyChecksum_fail() { err := VerifyChecksum(0, []byte("abc")) fmt.Printf("%#v\n", err) fmt.Println(err...
package bring import ( "image/draw" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Layers", func() { var layers layers BeforeEach(func() { layers = newLayers() layers.getDefault().Resize(1024, 768) }) It("returns the default layer", func() { Expect(layers.getDefault()).To(Equ...
package functiomanager import ( "testing" "os" "io/ioutil" ) func TestMain(m *testing.M) { wd, _ := os.Getwd() os.Setenv("RUNTIME_ROOT", wd) os.Setenv("RUNTIME_LAMBDA", wd + "/../../runtime/bin/lambda-run") dest := wd + "/func" _, err := os.Stat(dest) if err == nil { os.RemoveAll(dest) } o...
package main import ( "fmt" "golang.org/x/net/html" "io" "log" "net/http" "os" ) func getLinks(body io.Reader) []string { var links []string z := html.NewTokenizer(body) for { tt := z.Next() switch tt { case html.ErrorToken: //todo: links list shoudn't contain duplicates return links case html...
package main import ( "encoding/json" "github.com/urfave/cli" "os" "fmt" "github.com/andreaskoch/go-fswatch" "strings" "path/filepath" ) type Config struct { IP string `json:"ip"` PORT string `json:"port"` STORAGE_PATH string `json:"storage_path"` } type Message struct { Interaction stri...
/* Problem Create a function that can determine whether or not an arbitrary DNA string is a Watson-Crick palindrome. The function will take a DNA string and output a true value if the string is a Watson-Crick palindrome and a false value if it is not. (True and False can also be represented as 1 and 0, respectively.)...
package models import ( "fmt" "log" "database/sql" ) type Staff struct { ID int64 `form:"-"` FirstName string `form: "first_name"` LastName string `form: "last_name"` Position string `form: "position"` Admin bool `form: "admin""` } var ( staff [] Staff id int64 firstName string lastName string position...
package mqops import ( "encoding/json" "github.com/matscus/Hamster/Guns/busM5/errors" ) type clientSearchJSON struct { Data struct { RequestFields []string `json:"requestFields"` Filter struct { Surname string `json:"surname"` Name string `json:"name"` Patronymic string `json:"patrony...
package sort7 import ( "math/rand" "testing" "time" ) func Test_heapSort(t *testing.T) { type args struct { data []int a int b int } tests := []struct { name string args args }{ { name: "test1", args: args{ data: []int{10, 7, 6, 8, 9, 5, 4}, a: 0, b: 7, }, }, } ...
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) func main() { // Part1: Need to determine how many duplicate sections exist // (contained sets in pairs) duplicateSets := 0 //Part2: Need to determine how many pairs have any overlap at all in pairs overlaps := 0 // Open file file, er...
package main import ( //"math/rand" //"time" //"golang.org/x/mobile/app" //"golang.org/x/mobile/event/key" //"golang.org/x/mobile/event/lifecycle" //"golang.org/x/mobile/event/paint" //"golang.org/x/mobile/event/size" //"golang.org/x/mobile/event/touch" //"golang.org/x/mobile/exp/gl/glutil" //"golang.org/x/...
package freshdesk import "testing" func TestTicket(t *testing.T) { // FILL IN YOUR INFORMATION AND UNCOMMENT TO TEST! // r := &Request{ // Domain: "", // API: "", // } // // tk := &NewTicket{} // tk.Ticket = &Ticket{ // Email: "", // Name: "", // Subject: "this is a test", // T...