text
stringlengths
11
4.05M
// full_test package main import ( "GT/Graphics" // "GT/Scene" "GT/Window" // "fmt" // "github.com/veandco/go-sdl2/sdl" "math/rand" // "time" "fmt" // "github.com/davecheney/profile" ) func random(min, max int) int { //srand.Seed(time.Now().Unix()) return rand.Intn(max-min) + min } type TestGame struct { ...
package models import ( "time" "github.com/jinzhu/gorm" ) // Session type that extends gorm.Model. type Session struct { gorm.Model // Session ID Key string `gorm:"unique"` // encrypted cookie Data []byte // Time the session will expire ExpiresAt time.Time }
package lc // Time: O(n) // Benchmark: 0ms 3mb | 100% 79% func intersection(nums1 []int, nums2 []int) []int { add := func(set *[]int, num int) { for _, v := range *set { if v == num { return } } *set = append(*set, num) } nums := make(map[int]bool) for _, num := range nums1 { nums[num] = true ...
package whosonit import ( "template" ) const root_template = ` <html> <body> <h1>Who is on it?</h1> <h2>Current Emails</h2> <ul> {.repeated section @} <li><a href="/show?sender={Sender}&date={RecieptDate}">{Sender} - {Subject} - {RecieptDate}</a></li> {.or} Nothing to do. Good job. {.end} </ul> </body> </ht...
package adminModel import ( "gopkg.in/mgo.v2/bson" "time" "crypto/md5" "encoding/hex" "casino_common/utils/db" "sendlinks/conf/tableName" ) //后台用户 type Admin struct { ObjIds bson.ObjectId `bson:"_id"` NickName string //昵称 AccountName string //帐户 Password string //密码 AccountPower []*Power //权...
package main //2325. 解密消息 //给你字符串 key 和 message ,分别表示一个加密密钥和一段加密消息。解密 message 的步骤如下: // //使用 key 中 26 个英文小写字母第一次出现的顺序作为替换表中的字母 顺序 。 //将替换表与普通英文字母表对齐,形成对照表。 //按照对照表 替换 message 中的每个字母。 //空格 ' ' 保持不变。 //例如,key = "happy boy"(实际的加密密钥会包含字母表中每个字母 至少一次),据此,可以得到部分对照表('h' -> 'a'、'a' -> 'b'、'p' -> 'c'、'y' -> 'd'、'b' -> 'e'、'o' -...
package weixin import ( "crypto/sha1" "encoding/xml" "fmt" "io" "log" "net/http" "sort" "strings" ) func calcSHA1(v string) string { h := sha1.New() io.WriteString(h, v) return fmt.Sprintf("%x", h.Sum(nil)) } func calcSignature(timestamp, nonce string) string { sa := sort.StringSlice([]string{Token, time...
package lib import ( "strings" tea "github.com/charmbracelet/bubbletea" "github.com/muesli/reflow/ansi" ) type Viewport struct { ModelWidth, ModelHeight, YPosition int Component } func (v *Viewport) Width() int { return v.ModelWidth } func (v *Viewport) Height() int { return v.ModelHeight } func (v Viewport)...
package delaytask import ( "time" "strconv" "strings" ) const ( // 普通的延时任务,或者定时任务 DelayTask = iota // 周期性任务 PeriodTask ) type Serializer interface { ToJson() string } type Runner interface { Serializer Run() (bool, error) // 计划执行runner的时刻 GetToRunAt() time.Time UpdateToRunAt() GetRunAt() time.Time Get...
package find import ( "errors" "io" "io/ioutil" "os" "path/filepath" "regexp" "sort" ) type Options struct { Recursive bool StopAtFirstMatch bool RegularFilesOnly bool DirectoriesOnly bool MatchRegex *regexp.Regexp MatchExtension string // Sort newest to oldest SortByRecentModTime bool // ...
/** * Copyright (c) 2018-present, MultiVAC Foundation. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package chain import ( "fmt" "os" "reflect" "testing" "github.com/multivactech/MultiVAC/configs/config" "github.com/multiv...
package eventsapi import ( "encoding/json" "fmt" "github.com/oklahomer/golack/v2/event" "github.com/tidwall/gjson" ) // https://api.slack.com/events-api#callback_field_overview type outer struct { Token string `json:"token"` TeamID string `json:"team_id"` APIAppID string ...
// Copyright (c) 2020 - for information on the respective copyright owner // see the NOTICE file and/or the repository at // https://github.com/hyperledger-labs/perun-node // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may...
package model type CrawlResult struct { Url Input Page string }
package authinfo import ( "testing" "github.com/stretchr/testify/assert" ) var ( testAuthInfo = AuthInfo{ Username: "a-user", Groups: []string{"company", "admin-team"}, } ) func TestCheckPermittedGroups(t *testing.T) { assert.False(t, testAuthInfo.CheckGroup("a-team"), "a-team is not a member") assert.T...
/* * * Copyright 2020 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agree...
package main import ( "fmt" ) // 声明一个新的类型 type person struct { name string age int } // 比较两个人的年纪,返回年纪大的那个人,并且返回年纪差 // struct 也是传值的 func Older(p1,p2 person)(person,int){ if p1.age > p1.age { // 比较p1 和 p2 这两个人的年纪 return p1,p1.age-p2.age } return p2,p2.age-p1.age } func main(){ var tom person // 赋值初始化 tom...
package main import ( "log" "net/http" "os" "strings" ) const dir = "." func main() { fs := http.FileServer(http.Dir(dir)) log.Printf("Serving "+dir+" on http://localhost:%+v", os.Getenv("PORT")) http.ListenAndServe(":"+os.Getenv("PORT"), http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { ...
package main import ( "bufio" "encoding/json" "fmt" "os" ) func main() { scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { input := scanner.Text() var dat map[string]interface{} if err := json.Unmarshal([]byte(input), &dat); err != nil { panic(err) } if b, err := json.MarshalIndent(dat...
package main import ( "bufio" "fmt" "log" "net" "os" "runtime" "strings" ) func main() { host := "0.0.0.0" port, ok := os.LookupEnv("PORT") if !ok { port = "9999" } err := start(fmt.Sprintf("%s:%s", host, port)) if err != nil { log.Fatal(err) } } func start(addr string) (err error) { listener, err...
package cmd import ( "errors" "net" "github.com/michaelhenkel/gokvm/network" "github.com/spf13/cobra" log "github.com/sirupsen/logrus" ) var ( subnet string gateway string dnsServer string dhcp bool networkType string ) func init() { cobra.OnInitialize(initNetworkConfig) createNetwork...
package main import ( "time" "github.com/gin-gonic/gin" ) type timer struct{} type timerInterface interface { Sleep(d time.Duration) } func (t *timer) Sleep(d time.Duration) { time.Sleep(d) } func timerMiddleware(c *gin.Context) { c.Set("timerAPI", &timer{}) c.Next() }
package domain import ( "time" "github.com/traPtitech/trap-collection-server/src/domain/values" ) type OIDCSession struct { accessToken values.OIDCAccessToken expiresAt time.Time } func NewOIDCSession(accessToken values.OIDCAccessToken, expiresAt time.Time) *OIDCSession { return &OIDCSession{ accessToken: ...
package Largest_Rectangle_in_Histogram func largestRectangleArea(heights []int) int { if len(heights) == 0 { return 0 } max := -1 s := NewStack(len(heights)) for i := 0; i < len(heights); i++ { // if heights[i] <= heights[s.Back()], s.Pop(), and calculate area for s.Len() > 0 && heights[i] <= heights[s.Ba...
package lib import ( "time" vegeta "github.com/tsenart/vegeta/lib" ) // uses the vegeta library to run a load test against a target func LoadTest(target string, duration time.Duration, requestsPerScond int) vegeta.Metrics { rate := vegeta.Rate{Freq: requestsPerScond, Per: time.Second} targeter := vegeta.NewSt...
package main import ( "html/template" "net/http" "sort" "github.com/bake/qual-o-mat/qualomat" "github.com/pkg/errors" ) type sortByDate []*qualomat.Election func (e sortByDate) Len() int { return len(e) } func (e sortByDate) Less(i, j int) bool { return e[i].Date.Unix() < e[j].Date.Unix() } func (e s...
package main import ( "fmt" "runtime" "sync" ) /** 如果map由多协程同时读和写就会出现 fatal error:concurrent map read and map write的错误 如下代码很容易就出现map并发读写问题 **/ // ERROR CODE 1 type UserAges struct { ages map[string]int sync.Mutex } func (ua *UserAges) Add(name string, age int) { ua.Lock() defer ua.Unlock() ua.ag...
package password import( "crypto/rand" "encoding/base64" "log" ) const( PASSLEN int = 8 ) func GenerateRandomPassword() string{ pass := make([]byte,PASSLEN) rand.Read(pass) finalpass := base64.URLEncoding.EncodeToString(pass) return string(finalpass[0:PASSLEN]) } func GenerateRandomPasswords(noOfPas...
// Copyright 2018 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package main import "net/http" func main() { print("server is running on http://0.0.0.0:3000") http.ListenAndServe(":3000", http.FileServer(http.Dir("."))) }
package epaxospb import ( "github.com/google/btree" ) // Less implements the btree.Item interface. func (ihs *InstanceState) Less(than btree.Item) bool { return ihs.InstanceNum < than.(*InstanceState).InstanceNum }
package corp import "fmt" type ICorp interface { GetInfo() string SetParent(corp ICorp) GetParent() ICorp } type IBranch interface { AddSubordinate(corp ICorp) GetSubordinateInfo() []ICorp } //--------------------------------------------------------------- type Corp struct { name string position string sal...
package taoke import ( "fmt" "bytes" "common" "errors" "io/ioutil" "encoding/json" "github.com/mahonia" log "code.google.com/p/log4go" ) type ItemInfo struct { Date string Id string Name string ShopId string ShopName string Count string Price string Stat...
package test import ( "bytes" "image" "image/jpeg" "io/ioutil" "os" "path" "testing" "github.com/stretchr/testify/require" ) func RootDir(t *testing.T, level int) string { dir, err := os.Getwd() require.NoError(t, err) for i := 0; i < level; i++ { dir = path.Dir(dir) } return dir } func SampleImage(t...
package cluster import ( "fmt" "time" "github.com/zdnscloud/cement/log" "github.com/zdnscloud/cluster-agent/monitor/event" "github.com/zdnscloud/cluster-agent/monitor/namespace" "github.com/zdnscloud/cluster-agent/monitor/node" "github.com/zdnscloud/gok8s/client" ) type Monitor struct { cli client.Client...
package dmsghttp // import ( // "io" // "net/http" // ) // func NewRequest2(method, url string, body io.Reader) (*http.Request, error) { // req, err := http.NewRequest(method, url, body) // req.Proto = "HTTP/dmsg" // return req, err // }
package server import ( "encoding/json" "net/http" "strconv" "strings" "github.com/gempir/gempbot/internal/api" "github.com/gempir/gempbot/internal/store" ) func (a *Api) BlocksHandler(w http.ResponseWriter, r *http.Request) { authResp, _, apiErr := a.authClient.AttemptAuth(r, w) if apiErr != nil { return ...
// Copyright 2020 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package handler import ( "database/sql" "fmt" "github.com/ysugimoto/husky" ) func Accept(d *husky.Dispatcher) { db := husky.NewDb(GetDSN()) req := d.Input.GetRequest() token := req.Header.Get("X-LAP-Token") if token == "" { SendError(d, "Accept Error") return } // match token var userName string row :...
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package network import ( "context" "fmt" "regexp" "strings" "time" "chromiumos/tast/common/policy" "chromiumos/tast/common/policy/fakedms" "chromiumos/tast/common/t...
package movetaskorder import ( "errors" "fmt" "time" "github.com/gobuffalo/pop/v5" "github.com/gobuffalo/validate/v3" movetaskorderops "github.com/transcom/mymove/pkg/gen/primeapi/primeoperations/move_task_order" "github.com/transcom/mymove/pkg/models" "github.com/transcom/mymove/pkg/services" "github.com/t...
package gflObject import "github.com/garclak/gflgo/gflConst" type Waypoint struct { id : int Type : gflConst.WaypointC Designation : string Altitude : int LatHemi : gflConst.HemiC LatDeg : int LatMin : int LatSec : int LongHemi : gflConst.HemiC LongDeg : int LongMin : int LongSec : int Frequency : float3...
package main // Leetcode 386. (medium) func lexicalOrder(n int) []int { res := make([]int, n) cur := 1 for i := 0; i < n; i++ { res[i] = cur if cur*10 <= n { cur *= 10 } else { if cur == n { cur /= 10 } cur++ for cur%10 == 0 { cur /= 10 } } } return res }
package main import ( "bufio" "fmt" "log" "math/bits" "os" "runtime" "strconv" "strings" "time" ) const M = 150 const N = 6 var names []string var attacks [M][3]uint64 type Result struct { best int answer [N]uint8 } func (result *Result) search_i0(i0 int) { var s4 [3]uint64 for i1 := 0; i1 < i0; i...
package atoi import ( "fmt" "testing" ) func TestMAtoi(t *testing.T) { str := " -123 bs" fmt.Println(MAtoi(str)) }
//lint:file-ignore U1000 Ignore all unused code package cmd import ( "encoding/json" "fmt" "log" "os" "github.com/fugue/fugue-client/client" "github.com/go-openapi/runtime" httptransport "github.com/go-openapi/runtime/client" "github.com/go-openapi/strfmt" "github.com/spf13/cobra" ) const ( // DefaultHost ...
package models type Neuron struct { Weights []float64 Value float64 Error float64 Biais float64 Expected float64 NewWeights []float64 } const MaxWeight float64 = 20 const MaxBiais float64 = 250
package main import ( "fmt" "github.com/captncraig/blog/designBrowser" "net/http" "os" ) func main() { http.HandleFunc("/resume", resume) http.HandleFunc("/colors", designSeeds) http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/")))) bind := fmt.Sprintf("%s:%s", os.Geten...
package schema import ( "github.com/facebookincubator/ent" "github.com/facebookincubator/ent/schema/edge" "github.com/facebookincubator/ent/schema/field" ) // SubjectType holds the schema definition for the SubjectType entity. type SubjectType struct { ent.Schema } // Fields of the SubjectType. func (SubjectType...
package protocol import fuzz "github.com/jamieabc/gofuzz" const ( transactionStatusRPCMethod string = "Transaction.Status" ) type TransactionStatusRpc struct { ID string `json:"id"` Method string `json:"method"` Params []TransactionStatus `json:"params"` } type TransactionStatus st...
package main import ( "flag" "fmt" "log" "os" ) func main() { destination, departure := getPlaces() key := getAPIKey() client := Client{ APIKey: key, Departure: destination, Destination: departure, } response, error := client.Request() if error != nil { log.Fatalln(error) } printGPX(*...
// Copyright 2021 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package dragonpuzzle import ( "testing" ) func TestTrack(t *testing.T) { tests := []struct{ desc string call *Track want *Track }{ { desc: "nil track", call: &Track{}, want: &Track{Col: BLANK}, }, { desc: "red no hts", call: Red(), want: &Track{Col: RED, Count: HT{}, Ends: 0}, }, ...
package types type UbuntuOptions struct { InstallUbuntu InstallUbuntu `json:"install-ubuntu"` }
package nanolog import ( "fmt" "io" "io/ioutil" "log" "os" "runtime" "strings" "sync" ) // LogLevel determines the level of logging (priority) // Separate loggers exists for all types of log levels type LogLevel string // passthrough constants from standart log package const ( Ldate = log.Ldate Lti...
package entity import "gorm.io/gorm" type Review struct { gorm.Model UserID uint MovieID uint Review string Rate uint Movie Movie User User }
package atgo import ( "context" "fmt" "github.com/hashicorp/errwrap" pay "github.com/wondenge/at-go/payments" "go.uber.org/zap" ) // Move money from a Payment Product to an application stash. // An application stash is the wallet that funds your service usage expenses. func (c *Client) TopupStash(ctx context.Con...
package peer import ( "net" ) type CoreTCPSocketOption struct { readBufferSize int writeBufferSize int noDelay bool } func (self *CoreTCPSocketOption) SetSocketBuffer(readBufferSize, writeBufferSize int, noDelay bool) { self.readBufferSize = readBufferSize self.writeBufferSize = writeBufferSize self....
package entity type TwitterUser struct { ID string Name string Username string Description string ProfileImageURL string }
// Copyright 2018 Google LLC // // 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 w...
package request import ( "marketplace/transactions/domain" ) type GetAdsResponse struct { Id int64 `json:"id"` Title string `json:"title"` Description string `json:"description"` Price float64 `json:"price"` UserId int64 `json:"userId"` Picture string `json:"-"` Sold ...
/* author:admin createTime: 2022-06-16 16:30 */ package main import "fmt" func bubbleSort(arr []int) []int { if len(arr) <= 1 { return arr } for i := 0; i < len(arr)-1; i++ { for j := 0; j < len(arr)-i-1; j++ { if arr[j] > arr[j+1] { arr[j], arr[j+1] = arr[j+1], arr[j] fmt.Println("current:", arr)...
package udwSync import ( "github.com/tachyon-protocol/udw/udwTest" "sync" "testing" ) func TestWaitGroup(ot *testing.T) { { wg := Rc{} wg.Add(1) wg.Done() wg.Wait() } { i := Int{} wg := Rc{} wg.Inc() go func() { i.Inc() wg.Dec() }() wg.Wait() udwTest.Equal(i.Get(), 1) } { counter...
package main import ( "github.com/labstack/echo" "github.com/labstack/echo/middleware" "github.com/than-os/sentinel-bot/nodes/master-node/service" ) func main() { e := echo.New() //middlewares e.Use(middleware.Logger()) e.Use(middleware.Recover()) //CORS e.Use(middleware.CORSWithConfig(middleware.CORSCon...
package main import ( "flag" "fmt" "os" "github.com/n0x1m/md2gmi/mdproc" "github.com/n0x1m/md2gmi/pipe" ) func main() { var in, out string flag.StringVar(&in, "i", "", "specify a .md (Markdown) file to read from, otherwise stdin (default)") flag.StringVar(&out, "o", "", "specify a .gmi (gemtext) file to wri...
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2015 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met...
package filewatch import ( "context" "sync" "time" "k8s.io/apimachinery/pkg/types" ctrl "sigs.k8s.io/controller-runtime" "github.com/jonboulle/clockwork" "github.com/tilt-dev/tilt/internal/watch" "github.com/tilt-dev/tilt/pkg/apis" "github.com/tilt-dev/tilt/pkg/apis/core/v1alpha1" "github.com/tilt-dev/til...
package review import ( . "movie-app/entity" "movie-app/movie" "movie-app/user" ) type ReviewFormatter struct { ID int `json:"id"` UserID uint `json:"user_id"` MovieID uint `json:"movie_id"` Review string `json:"review"` Rate uint ...
package apilifecycle // OnStart Set func (api *APILifeCycle) OnStart(handler HandlerCycle) { api.onStart = handler } // GetOnStart Get func (api *APILifeCycle) GetOnStart() HandlerCycle { return api.onStart }
package verdeps const ( gophrPrefix = "\"gophr.pm/" goFileSuffix = ".go" githubPrefix = "\"github.com/" )
package shardmaster import "raft" import "labrpc" import "sync" import "encoding/gob" import "log" import "time" var Debug = 0 const time_1 = time.Second * 1 func DPrintf(format string, a ...interface{}) (n int, err error) { if Debug > 0 { log.Printf(format, a...) } return } type ShardMaster struct { mu ...
package solutions type NestedIterator struct { list []*NestedInteger i int current *NestedIterator } func Constructor(nestedList []*NestedInteger) *NestedIterator { return &NestedIterator{list: nestedList} } func (this *NestedIterator) Next() int { if this.list[this.i].IsInteger() { ...
package api import ( "os" "github.com/pkg/errors" "github.com/suborbital/reactr/rcap" "github.com/suborbital/reactr/rwasm/runtime" ) func GetStaticFileHandler() runtime.HostFn { fn := func(args ...interface{}) (interface{}, error) { namePointer := args[0].(int32) nameeSize := args[1].(int32) ident := args...
package sample import ( "github.com/gin-gonic/gin" jwt "github.com/kyfk/gin-jwt" "github.com/wyllisMonteiro/go-api-template/pkg/jwt_auth" ) //Routes All routes for sample func Routes(r *gin.RouterGroup, jwtAuth jwt.Auth) { r.Use(jwt.ErrorHandler) r.GET("/", jwt_auth.Operator(jwtAuth), GetSample) }
package entry type Entry struct { Path string VisitedCount int LastVisited int } type Entries []*Entry func (e Entries) Map(f func(*Entry) interface{}) Entries { result := make(Entries, len(e)) for _, v := range e { result = append(result, v) } return result } func (e Entries) Filter(f func(*Entry...
// Copyright (C) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed t...
package functest import ( "fmt" faker "github.com/dmgk/faker" pb "github.com/hugdubois/ah-svc-www/pb" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) func testGetRsvpCreationRequest( config FunctionalTestConfig, ) (reqs []*pb.RsvpCreationRequest, extras map[string]interface{}, err error) { va...
package server import ( "encoding/json" "eosApi/httpPost" "fmt" ) func GetBlock()(string,int,int){ HeadBlockNum:=GetInfo() type AutoGenerated struct { BlockNumOrID int `json:"block_num_or_id"` } block_num_0:=AutoGenerated{ HeadBlockNum, } block_num_1,_:=json.Marshal(block_num_0) block_num :=string(b...
package main import ( "fmt" "time" ) func myticker() { flag := false ticker := time.NewTicker(2 * time.Second) go func() { time.Sleep(10 * time.Second) ticker.Stop() flag = true }() for { if flag { break } fmt.Println(<-ticker.C) } fmt.Println("myticker end") } func main() { myticker() fm...
package gopherillamail import ( "fmt" "net/http" "net/http/cookiejar" "time" ) const ( STANDARD_IP = "127.0.0.1" ) // Mail is an e-mail from GuerrillaMail type Mail struct { guid string subject string sender string time time.Time read bool excerpt string body string } // Inbox is a struct t...
package types import ( "math/big" "time" mint "github.com/void616/gm.mint" ) // Approvement model type Approvement struct { ID uint64 Transport SendingTransport Status SendingStatus To mint.PublicKey Sender *mint.PublicKey SenderNonce *uint64 Digest *mint.Di...
package main import ( "github.com/garyburd/redigo/redis" ) // DBWriter is an interface for database writers. type DBWriter interface { Writer() AddKey(blocking bool, key string, value interface{}) DeleteKey(blocking bool, key ...string) SetAdd(blocking bool, key string, members ...interface{}) SetRemove(blockin...
package solutions import ( "sort" ) func largestDivisibleSubset(nums []int) []int { sort.Slice(nums, func (i int, j int) bool { return nums[i] > nums[j] }) dictionary := make(map[int][]int) return findLargestDivisibleSubset(nums, dictionary, 0) } func findLargestDivisibleSubset(nums []i...
package main import ( "crypto/aes" "crypto/cipher" "crypto/rand" "fmt" "io" "io/ioutil" "log" ) func main() { //crypto.Hash.String() b, _ := aes.NewCipher([]byte("Test1234Test1234")) data, err := ioutil.ReadFile("input.pdf") if err != nil { fmt.Println("Error :", err.Error()) } fmt.Println("LEN:", len(...
package restore_test import ( "database/sql" "fmt" "log" "github.com/cvgw/sql-db-restore/pkg/restore" ) func ExampleRestoreSQLFile() { db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@/", "foo", "bar")) if err != nil { log.Fatal("could not open connection to sql db") } restore.RestoreSQLFile(db, "dump.sql"...
package main import "fmt" import "unsafe" type User struct { id int64 name string } func main() { var v User v.id = 1 v.name = "v" var n int32 = 1 var s string = "v" fmt.Println(unsafe.Sizeof(n)) fmt.Println(unsafe.Sizeof(s)) fmt.Println(*&v.id) }
package main import ( "fmt" "runtime" "time" ) const c = 10000000 func funcGoLoop(ch chan<- int) { n := 0 for i := 0; i < c; i++ { n += i } ch <- n } func funcGo() { ch := make(chan int) go funcGoLoop(ch) go funcGoLoop(ch) <-ch <-ch } func main() { runtime.GOMAXPROCS(1) t1 := time.Now() funcGo()...
package main import ( "encoding/csv" "io/ioutil" "log" "net/http" "os" "regexp" "strconv" "strings" "time" ) const BIRTHS = `<h2>.+Births.+</h2>` const DEATHS = `<h2>.+Deaths.+</h2>` const HOLIDAYS = `<h2>.+Holidays.+</h2>` const DELIMITTER = "&#8211" func checkError(err error) { if err != nil { log.Fata...
// package react // // const testVersion = 4 // // /* reactor */ // // type reactor struct { // cells []*compuCell // } // // func New() Reactor { // return &reactor{} // } // // func (r *reactor) CreateCompute1(c Cell, f func(int) int) ComputeCell { // old := f(c.Value()) // cc := new(compuCell) // cc.cb = make(m...
package tb import ( "encoding/json" ) type Cfg_Area struct { AreaId int32 AreaName string StartDate int32 State int32 } type CfgData struct { Ver string Items *CfgDataAll } type CfgDataAll struct { Cfg_Area []*Cfg_Area } var Data *CfgDataAll var Ver string func InitCfgData(data []byte) error { va...
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package cycle import ( "cycle/one" "github.com/golang/dep/gps" ) var ( A = gps.Solve B = one.A )
package main //883. 三维形体投影面积 //在n x n的网格grid中,我们放置了一些与 x,y,z 三轴对齐的1 x 1 x 1立方体。 // //每个值v = grid[i][j]表示 v个正方体叠放在单元格(i, j)上。 // //现在,我们查看这些立方体在 xy、yz和 zx平面上的投影。 // //投影就像影子,将 三维 形体映射到一个 二维 平面上。从顶部、前面和侧面看立方体时,我们会看到“影子”。 // //返回 所有三个投影的总面积 。 // // // //示例 1: // // // //输入:[[1,2],[3,4]] //输出:17 //解释:这里有该形体在三个轴对齐平面上的三个投影(...
package main import ( "fmt" "time" "strings" ) func BuildLocationsList() (locations Locations, err error) { miners, err := MinersCollection() locations = Locations{} locationsAdded := map[string]Location {} // Add the default 'all' location allLocations := Location{ Name: "all", } locations =...
// 本文件由gen_static_data_go生成 // 请遵照提示添加修改!!! package sd import "encoding/json" import "fmt" import "log" import "path/filepath" import "github.com/tealeg/xlsx" import "github.com/trist725/mgsu/util" ////////////////////////////////////////////////////////////////////////////////////////////////// // TODO 添加扩展import代...
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package policy import ( "context" "time" "chromiumos/tast/common/fixture" "chromiumos/tast/common/pci" "chromiumos/tast/common/policy" "chromiumos/tast/common/policy/...
package main import "fmt" func main() { fmt.Println("test") in := make(chan int, 1) go func(in chan int) { defer close(in) for i := 0; i < 15000; i++ { fmt.Println("To channel:", i) in <- i } fmt.Println("CLOSED") }(in) for v := range in { fmt.Println("\tFrom channel:", v) } }
package Products import ( "encoding/json" "fmt" "io/ioutil" "net/http" "strconv" "github.com/GAQF202/servidor-rest/Structs" "github.com/GAQF202/servidor-rest/list" ) //VARIABLE PARA ALMACENAR LOS PRODUCTOS DEL CARRITO var CartProducts []CarritoType //STRUCT PARA BUSQUEDA DE TIENDA type Buscar_tienda struct {...
package main import "fmt" type person struct { first string last string age int } type human interface { speak() } func (p *person) speak() { fmt.Println("Hello, my name is", p.first, p.last) } func saySomething(h human) { h.speak() } func main() { p1 := person{ first: "Jonathan", last: "Thompson",...
package utils import ( "github.com/influxdata/influxdb/client/v2" "log" "sync/atomic" "time" "zpush/conf" ) type ServerStats struct { StartTime time.Time MsgIn uint64 MsgOut uint64 } var stats ServerStats func (s *ServerStats) RecordStart() { s.StartTime = time.Now() go s.ReportStats() } func (s ...
package collector import ( "fmt" "os" "path" "strings" "testing" "github.com/arunvelsriram/sftp-exporter/pkg/constants/viperkeys" "github.com/arunvelsriram/sftp-exporter/pkg/internal/mocks" "github.com/golang/mock/gomock" "github.com/kr/fs" "github.com/pkg/sftp" "github.com/prometheus/client_golang/prometh...