text
stringlengths
11
4.05M
package bus import ( "fmt" "github.com/go-redis/redis" "github.com/tmtx/res-sys/pkg/bus" "github.com/tmtx/res-sys/pkg/validator" ) type redisBus struct { client *redis.Client subscriptions map[bus.MessageKey][]bus.Callback } type MessageBus interface { Dispatch(m bus.Message) DispatchSync(m bus.Messa...
package first import "fmt" type Person struct { Name string } // export first func Firsteg() { var i interface{} i = 4 fmt.Println(i) i = 4.5 //interface type conversion j := int(i.(float64)) fmt.Println(i, j) i = "Parit" fmt.Println(i) //interface can hold non-primitive type data as well i = Person{N...
package ibmcloud // Metadata contains IBM Cloud metadata (e.g. for uninstalling the cluster). type Metadata struct { AccountID string `json:"accountID"` BaseDomain string `json:"baseDomain"` CISInstanceCRN string `json:"cisInstanceCRN,omitempty"` DNSInstanceID string `json:"dnsInstanc...
/* Copyright © 2022 SUSE 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 writing, software distrib...
package main import "fmt" //结构体嵌套 type Address struct { province string city string } type workPlace struct { province string city string } type Person struct { name string age int addr Address } type Company struct { name string Address } func main() { p1 := Person{ name: "lujing", age: 999,...
/* Kirchhoff's law says that when you sum up all the currents (positive for the currents going to a junction, and negative for current leaving a junction), you will always get as result 0. Using Kirchhoff's law, you can see that i1 + i4 - i2 - i3 = 0, so i1 + i4 = i2 + i3. Given two lists, one with all the currents ...
package gotten_test import ( "bytes" "encoding/json" "errors" "fmt" "github.com/Hexilee/gotten" "github.com/Hexilee/gotten/headers" "io" "mime/multipart" "net/http" "net/url" "os" "strconv" "testing" ) type ( ChangeParam struct { NewToken string `type:"form"` OldToken string `type:"form" require...
package cmd import ( "fmt" "os" "strings" "github.com/aelindeman/goname" "github.com/kyoh86/xdg" homedir "github.com/mitchellh/go-homedir" log "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/spf13/viper" ) var ( cfgFile string apiClient *goname.GoName ) // rootCmd represents the base ...
package actions import ( "errors" "strings" "github.com/barrydev/api-3h-shop/src/common/connect" "github.com/barrydev/api-3h-shop/src/factories" "github.com/barrydev/api-3h-shop/src/model" ) func UpdateOrder(orderId int64, body *model.BodyOrder) (*model.Order, error) { queryString := "" var args []interface{}...
package main import ( "fmt" "strconv" "strings" ) func main() { rules := parseInput() fmt.Println(dfBagCount(rules, "shiny gold")-1) } func dfBagCount(rules map[string][]connection, node string) int { children := rules[node] bags := 1 for _, c := range children { contained := dfBagCount(rules, c.c) if c...
//---------------------------------------------Paquetes E Imports------------------------------------------------------- package AnalisisYComandos import ( "../Metodos" "../Variables" "bufio" "bytes" "fmt" "github.com/asaskevich/govalidator" "github.com/gookit/color" "os" "strconv" "strings" ...
//go:generate goagen bootstrap -d github.com/odiak/MoneyForest/design package main import ( "context" "fmt" "net/http" "time" "github.com/go-pg/pg" "github.com/go-pg/pg/orm" "github.com/goadesign/goa" "github.com/goadesign/goa/middleware" "github.com/odiak/MoneyForest/app" "github.com/odiak/MoneyForest/con...
package fixtures import ( . "github.com/polydawn/refmt/tok" ) // sequences_Number contains what it says on the tin -- but be warned: // bytes are not representable in all formats. // // JSON can't clearly represent binary bytes; typically in practice transforms // to b64 strings are used, but this is application spe...
package vsphere // MachinePool stores the configuration for a machine pool installed // on vSphere. type MachinePool struct { // NumCPUs is the total number of virtual processor cores to assign a vm. // // +optional NumCPUs int32 `json:"cpus"` // NumCoresPerSocket is the number of cores per socket in a vm. The n...
package types import ( "time" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" // Importing this for gorm to designate the db driver uuid "github.com/satori/go.uuid" "github.com/tespo/satya/v2/scoping" ) // // Barcode describes a barcode on a Pod // type Barcode struct { ID uuid.UUID ...
package g var AllLabelsMap = map[string]bool{ LabelProduct: true, LabelCompany: true, LabelStock: true, LabelChain: true, } var LabelProduct string = "Product" var LabelCompany string = "Company" var LabelStock string = "Stock" var LabelChain string = "Chain"
package queries import ( "context" "database/sql" "reflect" "strings" "github.com/friendsofgo/errors" "github.com/volatiletech/sqlboiler/v4/boil" "github.com/volatiletech/strmangle" ) type loadRelationshipState struct { ctx context.Context exec boil.Executor loaded map[string]struct{} toLoad []string...
// Copyright 2018-2019 Authors of Cilium // // 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 ag...
package db import ( "database/sql" "fmt" ) type Database struct { DB *sql.DB } func (db Database) begin() (transaction *sql.Tx) { transaction, err := db.DB.Begin() if err != nil { fmt.Println(err) return nil } return transaction } func (db Database) prepare(query string) (statement *sql.Stmt) { statemen...
package maps import ( "fmt" "testing" ) type Vertex struct { Lat, Long float64 } func TestMaps(t *testing.T) { var m map[string]Vertex var stranger map[string]int m = make(map[string]Vertex) m["Bell Labs"] = Vertex{ 40.68433, -74.39967, } stranger = make(map[string]int) stranger["Hello World"] = 8 ...
// 在前面的例子中,我们用互斥锁进行了明确的锁定来让共享的 // state 跨多个 Go 协程同步访问。另一个选择是使用内置的 Go // 协程和通道的的同步特性来达到同样的效果。这个基于通道的方 // 法和 Go 通过通信以及每个 Go 协程间通过通讯来共享内存,确 // 保每块数据有单独的 Go 协程所有的思路是一致的。 package main import ( "fmt" "math/rand" "sync/atomic" "time" ) // 在这个例子中,state 将被一个单独的 Go 协程拥有。 // 这就能够保证数据在并行读取时不会混乱。 // 为了对 state 进行读取或者写入, // 其他...
package main import ( "bufio" "crypto/rand" "encoding/base64" "encoding/json" "fmt" "io" "io/ioutil" "log" "net/http" "os" "strings" "time" ) const ( ACCESS_TOKEN = "SECRET" DEV_SITE = "https://kapi.kakao.com" STORIES_PATH = "/v1/api/story/mystories" ) var ( err error client *http...
package gettingstarted import "fmt" // create own type type jamesBond int func HandsOnEx() { fmt.Println("[*] Welcome From Getting Started ") printEx() fundInt() fundConstants() fundControls() fundArrays() funcDefer() funcPanicRecover() } func funcPanicRecover() { fmt.Println("[-] Panic & Recover") defer ...
/* * thresh: histogram thresholding * * input: * matrix: the integer matrix to be thresholded * nrows, ncols: the number of rows and columns * percent: the percentage of cells to retain * * output: * mask: a boolean matrix filled with true for cells that are kept * */ package main import ( "flag" ...
package main import ( "strconv" "github.com/tidwall/gjson" "github.com/tidwall/sjson" ) type Property struct { Properties *Properties Name string data interface{} InUse bool OnChange func() } func NewProperty(name string, properties *Properties) *Property { return &Property{ Properties...
package detectcoll import "log" var ( md5_shifts [64]uint = [64]uint{ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, } ...
// Copyright © 2020, 2021 Attestant Limited. // 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 a...
package com_errors import "errors" var ( // ZeroMQ errors ErrZMQContext = errors.New("fetcher: Could not create ZeroMQ Context") ErrZMQConnect = errors.New("fetcher: Could not connect to port") ErrZMQRecieve = errors.New("fetcher: Could not receive message from server") ErrZMQSend = errors.New("fetcher: Could...
package routinghelpers import ( "context" "testing" peert "gx/ipfs/QmPJxxDsX2UbchSHobbYuvz7qnyJTFKvaKMzE2rZWJ4x5B/go-libp2p-peer/test" routing "gx/ipfs/QmRjT8Bkut84fHf9nxMQBxGsqLAkqzMdFaemDK7e61dBNZ/go-libp2p-routing" ) func TestGetPublicKey(t *testing.T) { d := Parallel{ Routers: []routing.IpfsRouting{ Pa...
package main import ( "testing" "strings" "fmt" "reflect" "github.com/stretchr/testify/assert" ) func TestSplit(t *testing.T) { fmt.Println("string array test....") got := strings.Split("a:b:c", ":") want := []string{"a", "b", "c"}; if !reflect.DeepEqual(got, want) { fmt.Println("!reflect.Deep...
package socket import ( "KServer/library/kiface/isocket" "KServer/library/socket" ) type IClient interface { /* 发送消息 data []byte 返回值 error */ Send(data []byte) error /* 发送buff消息 data []byte 返回值 error */ SendBuff(data []byte) error /* 获取Client ConnId 返回值 uint32 */ GetConnId() uint32 /* 停止...
package reflection import ( "fmt" "reflect" ) func ValidateWriterFunction(writerFuncPtrValue reflect.Value, baseType reflect.Type) reflect.Type { if writerFuncPtrValue.Kind() != reflect.Ptr || writerFuncPtrValue.Elem().Kind() != reflect.Func { panic(fmt.Errorf("reader function value has to be passed by pointer")...
// Copyright 2017 Vlad Didenko. All rights reserved. // See the included LICENSE.md file for licensing information package slops // import "go.didenko.com/slops" // Common gathers same entries from two sorted slices into // a new slice. The order is preserved. The lesser number of // duplicates is preserved func Comm...
package onepage import ( "path/filepath" "runtime" "github.com/maprost/application/generator/genmodel" ) func Data(application *genmodel.Application) (data interface{}, err error) { index, err := initData(application) if err != nil { return } data = index return } func Files() (path string, mainFile stri...
package msgbuzz import "fmt" type QueueNameGenerator struct { topicName string clientGroup string } func NewQueueNameGenerator(topicName string, clientGroup string) *QueueNameGenerator { return &QueueNameGenerator{ topicName: topicName, clientGroup: clientGroup, } } func (q QueueNameGenerator) Exchange(...
package main import ( "fmt" "io/ioutil" "log" "path/filepath" "runtime" "strconv" "strings" ) func main() { _, file, _, _ := runtime.Caller(0) content, err := ioutil.ReadFile(filepath.Join(filepath.Dir(file), "./input.txt")) if err != nil { log.Fatalln("load input error:", err) } rawInput := strings.Spl...
package slices_test import ( "fmt" "github.com/life4/genesis/channels" "github.com/life4/genesis/slices" ) func ExampleAny() { even := func(item int) bool { return item%2 == 0 } result := slices.Any([]int{1, 2, 3}, even) fmt.Println(result) result = slices.Any([]int{1, 3, 5}, even) fmt.Println(result) // Ou...
package boot import ( _ "gf-init/packed" ) func init() { }
package sqlmodel import ( "github.com/2liang/mcache/models/base" "errors" "strconv" ) type KeyData struct { Id int `xorm:"id int(11)" json:"id"` CaseId int `xorm:"case_id int(10)" json:"case_id"` Name string `xorm:"name varchar(250)" json:"name"` Desc string `xorm:"desc varchar(250)" json:"desc"` ...
package rule import ( "net/http" "strings" "github.com/sirupsen/logrus" ) // HTTPMethodSetting HTTPMethodRule Setting type HTTPMethodSetting struct { Method string Exclude bool } type httpMethodRule struct { method string exclude bool } // NewHTTPMethodRule : func NewHTTPMethodRule(setting HTTPMethodSetti...
/* Description Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, ... shows the first 10 ugly numbers. By convention, 1 is included. Given the integer n,write a program to find and print the n'th ugly number. Input Each line of the input contains a postisiv...
package main import ( "fmt" "dockertree" ) func main() { r := dockertree.Root{Registry: "test.com", BasePath: "/foo/bar"} fmt.Println(r.GetBaseName()) p := dockertree.Node{Name: "bare", Tag: "latest", Root: &r} n := dockertree.Node{Name: "centos", Tag: "7", Parent: &p} fmt.Println(n.GetFullName()) }
// Copyright 2019 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
package instrument import ( "time" confluent "github.com/confluentinc/confluent-kafka-go/kafka" ) // Collector allows to specify a collector for all the main actions of the kafka transformer. // Main actions are : consume, transform, produce/project // Before is called before the action and After called after. // ...
package main import ( "github.com/aws/aws-lambda-go/events" "encoding/json" "bartenderAsFunction/dao" "bartenderAsFunction/model" "github.com/aws/aws-lambda-go/lambda" "fmt" ) var DataConnectionManager dao.CommandConnectionInterface func Handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyRes...
package storage import ( "context" "fmt" "strings" "k8s.io/apimachinery/pkg/fields" "github.com/operator-framework/operator-lifecycle-manager/pkg/lib/kubernetes/pkg/printers" printerstorage "github.com/operator-framework/operator-lifecycle-manager/pkg/lib/kubernetes/pkg/printers/storage" apierrors "k8s.io/api...
// Package tfrecord is an obvious tfrecord IO implementation // // Format spec: https://www.tensorflow.org/tutorials/load_data/tfrecord, // assume all numbers are little-endian although not actually defined in spec. package tfrecord import ( "encoding/binary" "errors" "hash/crc32" "io" ) const ( crcMagicNum = 0x...
package config import ( "github.com/caarlos0/env" log "github.com/sirupsen/logrus" ) type Config struct { Port string `env:"PORT"` } func Load() (cfg Config) { if err := env.Parse(&cfg); err != nil { log.Errorf("%s", err) } return }
package decl import ( "go/ast" "fmt" "github.com/sky0621/go-testcode-autogen/inspect/result" ) type GenDeclInspector struct{} func (i *GenDeclInspector) IsTarget(node ast.Node) bool { switch node.(type) { case *ast.GenDecl: return true } return false } func (i *GenDeclInspector) Inspect(node ast.Node, ag...
package main import "os" func fib(n uint, acc uint, prev uint) uint { if n == 0 { return acc } else { return fib(n-1, prev+acc, acc) } } func main() { os.Exit(int(fib(2560000, 0, 0))) }
package main func main() { //data := data2.SampleUser //keyPem := utils.ReadFile("./jwtRS256.key") //keyPemPub := utils.ReadFile("./jwtRS256.key.pub") //expires := time.Now().Add(24 * time.Hour) //token := auth.CreateRSA256SignedToken(keyPem, data, expires, {}) //fmt.Println(token) //claims := auth.ParseRSA2...
package main import ( "fmt" "time" ) // --------------------------------------------------------- // EXERCISE: fix without type conversion // // 1. Fix the program without doing any conversion. // 2. Explain why it doesn't work. // // EXPECTED OUTPUT // 10h0m0s later... // ---------------------------------------...
package utils import "golang.org/x/crypto/bcrypt" type Hashing struct{} type HashingInterface interface { HashPass(pass string) ([]byte, error) ComparePass(hashedPass, pass string) error } func (h *Hashing) HashPass(pass string) ([]byte, error) { return bcrypt.GenerateFromPassword([]byte(pass), bcrypt.DefaultCos...
package main import "fmt" func main() { var i int = 10 { var i string = "Phani" fmt.Println(i) } fmt.Println(i) }
package datamodels // Request : Format d'une requete type Request struct { ID int `json:"id"` Method string `json:"method"` Params DataParams `json:"params"` } // Response : Format d'une reponse type Response struct { ID int `json:"id"` Method string `json:"method"` Params DataPara...
package api import ( "bytes" "encoding/json" "io/ioutil" "testing" ) func Test_RepoCreate(t *testing.T) { http := &FakeHTTP{} client := NewClient(ReplaceTripper(http)) http.StubResponse(200, bytes.NewBufferString(`{}`)) input := RepoCreateInput{ Description: "roasted chesnuts", HomepageURL: "http://exam...
// Copyright 2019-2023 The sakuracloud_exporter 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 appl...
// Copyright 2019 Kuei-chun Chen. All rights reserved. package mdb import ( "encoding/json" "io/ioutil" "testing" "github.com/simagix/gox" "go.mongodb.org/mongo-driver/bson" ) func TestGetIndexSuggestionFromFilter(t *testing.T) { filename := "testdata/commerceticket-replica-explain.json" buffer, err := iouti...
package suites import ( "context" "encoding/json" "fmt" "log" "strings" "testing" "time" mapset "github.com/deckarep/golang-set/v2" "github.com/stretchr/testify/suite" ) type CustomHeadersScenario struct { *RodSuite } func NewCustomHeadersScenario() *CustomHeadersScenario { return &CustomHeadersScenario{...
// Copyright (c) 2020 VMware, Inc. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package starlark import ( "bytes" "fmt" "io" "os" "path/filepath" "strings" "testing" "go.starlark.net/starlark" ) func TestCaptureLocalFunc(t *testing.T) { tests := []struct { name string args func(t *testin...
// Copyright 2015 Alexey Martseniuk. All rights reserved. // Use of this source code is governed by a MIT license // that can be found in the LICENSE file. package linq import ( "container/list" ) type T interface{} type Enumerator interface { // Sets the enumerator to its initial position, which is before the fi...
package dialog import ( "github.com/therecipe/qt/core" "github.com/therecipe/qt/internal/examples/showcases/wallet/wallet/dialog/controller" ) type dialogTemplate struct { core.QObject _ func() `constructor:"init"` _ func(cident string) `signal:"show,<-(controller.Controller)"` _ func(bool) ...
package main import "testing" func TestCheckParenthesis(t *testing.T) { cases := []struct { input string want bool }{ {"a+(b*c)-2-a", true}, {"(a+b*(2-c)-2+a)*2", true}, {"(a*b-(2+c)", false}, {"2*(3-a))", false}, {")3+b*(2-c)(", false}, } for _, c := range cases { got := CheckParenthesis(c.inp...
package sqlbuilder type Sqlizer interface { ToSql() (string, []interface{}, error) } type rawSqlizer interface { toSqlRaw() (string, []interface{}, error) }
package verr import ( "fmt" "io" "strings" ) var StackEnabled = true // Error severance level type. Can be used to determine the importance of the error before it handled appropriately. type ErrLevel int const ( ErrError ErrLevel = iota ErrIgnorable ErrInfo ErrNotice ErrWarning ErrCritical ErrFatal ErrPa...
package api import ( "fmt" "net/http" ) // Route represents a standard route object type Route struct { Method string Version int Path string HandlerFunc http.HandlerFunc Authenticate bool } // GetPattern returns the url match pattern for the route func (r Route) GetPattern() string { ret...
package set import ( "sort" "golang.org/x/exp/constraints" ) type SortableSet[V constraints.Ordered] map[V]struct{} // OrderedList return an ordered list // can use AscLess, DescLess as less function func (s SortableSet[V]) OrderedList(less func(v1, v2 V) bool) []V { list := Set[V](s).List() sort.Slice(list, fu...
package Problem0383 func canConstruct(ransomNote string, magazine string) bool { mc := getCount(magazine) for _, b := range ransomNote { mc[b-'a']-- if mc[b-'a'] < 0 { return false } } return true } func getCount(s string) []int { res := make([]int, 26) for i := range s { res[s[i]-'a']++ } return...
package main import ( "errors" "fmt" "io/ioutil" "log" "os" "path/filepath" "github.com/is8ac/tfutils/descend" "github.com/is8ac/tfutils/descend/models" tf "github.com/tensorflow/tensorflow/tensorflow/go" "github.com/tensorflow/tensorflow/tensorflow/go/op" ) func convModel(s *op.Scope, input tf.Output, fi...
package models import ( "github.com/google/uuid" ) type Session struct { SessionId uuid.UUID User *User } type SessionService interface { Set(session *Session) error Get(sessionId uuid.UUID) (bool, error) Delete(sessionId uuid.UUID) error }
package main import ( "os" "fmt" ) func rm(message Message) { err := os.Remove(configData.STORAGE_PATH + message.Name) if err != nil { fmt.Printf("Failed to remove '%v' because '%v'\n", message.Name, err) } }
package main import ( "flag" "fmt" "io/ioutil" "log" "os" "path/filepath" "reflect" "strconv" "testing" "time" "github.com/robustirc/rafthttp" "github.com/robustirc/robustirc/internal/ircserver" "github.com/robustirc/robustirc/internal/outputstream" "github.com/robustirc/robustirc/internal/raftstore" "...
package factories import ( sdk "github.com/identityOrg/oidcsdk" "net/url" "time" ) type ( DefaultAuthenticationRequestContext struct { RequestID string RequestedAt time.Time State string RedirectURI string ClientId string Nonce string ResponseMode...
package pstoremem import pstore "gx/ipfs/QmQFFp4ntkd4C14sP3FaH9WJyBuetuGUVo6dShNHvnoEvC/go-libp2p-peerstore" // NewPeerstore creates an in-memory threadsafe collection of peers. func NewPeerstore() pstore.Peerstore { return pstore.NewPeerstore( NewKeyBook(), NewAddrBook(), NewPeerMetadata()) }
/* * EVE Swagger Interface * * An OpenAPI for EVE Online * * OpenAPI spec version: 0.4.1.dev1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ package swagger // 200 ok object type GetUniverseBloodlines200Ok struct { // bloodline_id integer BloodlineId int32 `json:"bloodline_id,omi...
package hive import ( "github.com/google/uuid" "net" ) type AConnection interface { Start() RemoteAddr() net.Addr Send([]byte) Close() } type AUserHandler interface { ConnectionAdd(uint32, AConnection) ConnectionRemove(uint32, AConnection) ConnectionMessage(uint32, []byte) } type AUserStat interface { Con...
package logbridge import ( "bufio" "bytes" "io" "time" "github.com/rcrowley/go-metrics" "github.com/square/p2/pkg/logging" "golang.org/x/time/rate" ) type LogBridge struct { Reader io.Reader DurableWriter io.Writer LossyWriter io.Writer // We rate limit writes to LossyWriter because we can toler...
package main import ( "flag" "github.com/gin-gonic/gin" "github.com/jalgoarena/skeleton-code-java/api" "log" "net/http" ) func setupRouter() *gin.Engine { router := gin.Default() router.GET("health", api.HealthCheck) v1 := router.Group("api/v1") { v1.GET("/code/java/:problemId", api.GetSkeletonCode) } ...
package monosize import "fmt" // GetFixedSize reads files size as float64 for supporting huge file sizes // (like ZettaByte and YottaByte) and returns user friendly file size in 6 // characters long with leading spaces (if required) using Base 2 calculation // and file size abbreviation from Bytes to YottaBytes as st...
/* * Tencent is pleased to support the open source community by making Blueking Container Service available., * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except * in compliance with the License. You may obt...
// Copyright 2016 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
package mut import ( "net" "sync" ) type Server struct { closed bool address string cfg *Config mgr *ConnMgr ln *net.TCPListener wgConn *sync.WaitGroup localAddress *net.TCPAddr } func NewServer(address string, cfg *Config) *Server { return &Server{ address: a...
package leetcode func canThreePartsEqualSum(A []int) bool { lA := len(A) s := 0 for _, v := range A { s += v } if s%3 != 0 { return false } left := 0 var i int for i = 0; i < lA-2; i++ { left += A[i] if left == s/3 { break } } if i == lA-2 { return false } i++ mid := 0 for ; i < lA-1; i++...
package core import ( "fmt" "time" "github.com/golang/protobuf/ptypes" "github.com/textileio/go-textile/broadcast" "github.com/textileio/go-textile/keypair" "github.com/textileio/go-textile/pb" ) // Account returns account keypair func (t *Textile) Account() *keypair.Full { return t.account } // Sign signs i...
package Shuffle import ( "fmt" "sort" "testing" ) func TestSolution_Shuffle(t *testing.T) { type fields struct { origin []int } tests := []struct { name string fields fields }{ // TODO: Add test cases. { name: "first", fields: fields{ origin: []int{1, 2, 3}, }, }, } for _, tt := ra...
package util // Replaced during build var Version = "devel"
package tonberry import ( "image" ) const ( CHKX = iota CHKY ) type player struct { spr Sprite box image.Rectangle xVel, yVel int velInc int boundsChk func(int, image.Rectangle) bool } func NewMoveable(file string, bounds image.Rectangle, bcheck func(int, image.Rectangle) bool) GameObject...
package main import ( "github.com/streadway/amqp" ) func setupRabbit(rabbitURI string, rabbitVHost string, rabbitQueue string) (*amqp.Connection, *amqp.Channel, <-chan amqp.Delivery) { log.Notice("Connecting to RabbitMQ...") conn, err := amqp.DialConfig(rabbitURI, amqp.Config{Vhost: rabbitVHost}) if err != nil {...
package _404_Sum_of_Left_Leaves type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func sumOfLeftLeaves(root *TreeNode) int { // return sumOfLeftLeavesBFS(root) // return sumOfLeftLeavesDFSRecursion(root) return sumOfLeftLeavesDFSUnrecursion(root) } func sumOfLeftLeavesDFSUnrecursion(node *Tree...
package main import ( "services" "log" "crypto/sha256" "crypto/x509" ) func main() { /*config, err := services.NewConfigObject() if err != nil { log.Println("Error creating config object: " + err.Error()) os.Exit(1) } // Open configuration file //priv, pub, err := services.ParseKeys("keypair3.pem") if...
package sand import ( "html/template" "io/ioutil" "log" "net/http" "os" "github.com/gorilla/mux" ) /* For Development Only , for InitDevRouter(TODO) */ func (s *Sand) addTmpl(router *mux.Router) { router.HandleFunc("/v1/{page}.html", func(w http.ResponseWriter, r *http.Request) { w.Header().Add("Vary", "Acc...
package helpers import ( "encoding/json" "example.com/banking/models" ) func ConvertJsonToWallet(jsonStr string) *models.Wallet { model := models.Wallet{} json.Unmarshal([]byte(jsonStr), &model) return &model }
package main import ( "fmt" "log" "os" "path/filepath" "github.com/joho/godotenv" "github.com/sendgrid/sendgrid-go" "github.com/sendgrid/sendgrid-go/helpers/mail" "github.com/xuri/excelize/v2" ) func main() { err := godotenv.Load() if err != nil { log.Fatal("Error loading .env file") } path, err := os....
package whookie import "encoding/json" type Event struct { Id string `json:"id"` Message string `json:"message"` Type string `json:"type"` Timestamp int64 `json:"timestamp"` Data json.RawMessage `json:"data"` }
package main import ( "fmt" "strconv" "sync" "time" ) var count int var wg sync.WaitGroup var so sync.Once var m = sync.Map{} func main() { wg.Add(21) for i :=0;i<21;i++ { go func(n int) { key := strconv.Itoa(n) m.Store(key,n) fmt.Println(m.Load(key)) wg.Done() }(i) } wg.Wait() } f...
package main import ( "fmt" "math" "os" ) func isPowerOfTwo(n uint64) bool { if n == 0 || n == 1 { return false } return (n & (n - 1)) == 0 } // Convert 1024 to '1 KiB' etc func bytesToHuman(src uint64) string { if src < 10 { return fmt.Sprintf("%d B", src) } s := float64(src) base := float64(1024) s...
package main import "math" func Powerset1(nums []int) [][]int { if len(nums) == 0 { return [][]int{ []int{} } } length := int(math.Pow(2, float64(len(nums)))) result := make([][]int, length) for i := 0; i < length; i++ { bi := i s := []int{} for _, n := range nums { if bi % 2 != 0 { s = append(s...
/* * Go Library (C) 2017 Inc. * * @project Project Globo / avaliacao.com * @author @jeffotoni * @size 01/03/2018 */ package handler import ( "github.com/jeffotoni/gmongocrud/conf" "github.com/jeffotoni/gmongocrud/lib/context" "github.com/jeffotoni/gmongocrud/lib/upload" "github.com/jeffotoni/gmong...
package paperswithcode_go import ( "github.com/stretchr/testify/assert" "testing" ) func TestClient_PaperRepositoryList(t *testing.T) { c := NewClient() list, err := c.PaperRepositoryList("generative-adversarial-networks") assert.NoError(t, err) assert.NotEmpty(t, list.Results[0].URL) }
package server import ( "runtime" "github.com/sirupsen/logrus" "github.com/spf13/viper" ) // Init the server config for Gin func Init(config *viper.Viper, logger *logrus.Logger) { // Use all cpu cores runtime.GOMAXPROCS(runtime.NumCPU()) // Create router and listen on the configed port r := NewRouter(config,...