text
stringlengths
11
4.05M
package persistence import ( "fmt" "testing" ) func TestCategoryDAO(t *testing.T) { result, err := GetCategoryList() if err != nil { t.Error(err.Error()) } fmt.Println(result) }
// md2docx project main.go package main import ( "fmt" "io/ioutil" "os" "baliance.com/gooxml/document" bf "gopkg.in/russross/blackfriday.v2" ) func main() { mdf, err := os.Open("/home/cuberl/gopath/src/connect-core/docs/论文.md") if err != nil { fmt.Println(err) os.Exit(-1) } input, err := ioutil.ReadAll(...
// Created at 10/21/2021 4:50 PM // Developer: trungnq2710 (trungnq2710@gmail.com) package go_apns type ApsAlert struct { Title string `json:"title,omitempty"` Subtitle string `json:"subtitle,omitempty"` Body string `json:"body,omitempty"` LaunchImage string `json:"launch-i...
package main import ( "bufio" "fmt" "io" "os" "strconv" "strings" ) func main() { arguments := os.Args if len(arguments) == 1 { fmt.Println("Usage:selectColumn column <file1> [<file2> [...<fileN]]") os.Exit(1) } temp, err := strconv.Atoi(arguments[1]) if err != nil { fmt.Println("") os.Exit(1) } ...
package tsmt import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00900103 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:tsmt.009.001.03 Document"` Message *BaselineAmendmentRequestV03 `xml:"BaselnAmdmntReq"` } func (d *Document00900...
package common import ( "sync" ) func NewStdRole(id string) *stdRole { return &stdRole{ id: id, permissions: make(Permissions), } } type stdRole struct { sync.RWMutex id string `json:"id"` permissions Permissions } func (role *stdRole) getId() string { return role.id } func (role *stdR...
package http import ( "bufio" "fmt" "io" "io/ioutil" "net" "net/http/httputil" "strconv" "strings" ) // Response represents a HTTP response. type Response struct { StatusCode int StatusDescription string Headers Headers Body string HTTPVer string } // NewResponse ...
//author xinbing //time 2018/9/11 11:40 // package utils type Resp struct { Code int Msg string Data interface{} } func (p Resp) Success(msg string, data interface{}) *Resp { p.Code = 0 p.Msg = msg p.Data = data return &p } func (p Resp) Failed(msg string) *Resp { p.Code = -1 p.Msg = msg return &p }
package main import ( "fmt" ) func GetNext(source string) []int { sourceLen := len(source) next := make([]int, sourceLen) for i := 0; i < sourceLen; i++ { if i == 0 { next[i] = 0 } else { if source[i] == source[next[i-1]] { next[i] = next[i-1] + 1 } else { next[i] = 0 } } } return ne...
package util import ( "fmt" git "gopkg.in/src-d/go-git.v4" gitconfig "gopkg.in/src-d/go-git.v4/config" ) // GetRepositoryRemotes returns a map containing the remote names and the URLs they // point to. func GetRepositoryRemotes(repo *git.Repository) (map[string][]string, error) { gitRemotes, err := repo.Remotes(...
package main import ( "flag" "fmt" "io/ioutil" "log" "net/http" "os" ) func main() { flag.Parse() args := flag.Args() if len(args) < 1 { fmt.Println("Enter the url first! \n") os.Exit(1) } retrieve(args[0]) } func retrieve(url string) { resp, _ := http.Get(url) defer resp.Body.Close() body, _ :=...
package oidc import ( "testing" "github.com/stretchr/testify/assert" ) func TestValidateToken(t *testing.T) { sig, err := validateToken("none", nil) assert.Equal(t, "", sig) assert.EqualError(t, err, "square/go-jose: compact JWS format must have three parts") } func TestGetTokenSignature(t *testing.T) { sig, ...
package firequeue_test import ( "context" "fmt" "math/rand" "strings" "sync/atomic" "testing" "time" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/service/firehose" "github.com/aws/aws-sdk-go/service/firehose/firehoseiface" "github.com/natureglob...
/* Copyright 2016 The Kubernetes Authors 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 ag...
package main import ( "bytes" "fmt" "io/ioutil" "os" "github.com/dnephin/configtf/docs" "github.com/dnephin/dobi/config" ) var ( basePath = "docs/gen/config/" ) func write(filepath string, source interface{}) error { content, err := docs.Generate(source, docs.ReStructuredText) if err != nil { return err ...
package aws import "encoding/json" func SetJSONMarshal(f func(interface{}) ([]byte, error)) { jsonMarshal = f } func ResetJSONMarshal() { jsonMarshal = json.Marshal }
package main //Needs to sort array first //create a array with the gaps if any from the input array //first element in array is the first distance from 0. //check the different from i+1 to i. //if the distance is greater than jump add that to count. import ( "fmt" "sort" ) func main() { test := []int{5, 3, 6, 7, ...
// 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 main import ( "fmt" ) func main(){ mapPlayer := make(map[int]Player) mapPlayer[1] = Player{id : 1, name : "hendrawan"} mapPlayer[2] = Player{id : 2, name : "jupe"} for _, v := range mapPlayer{ fmt.Println(v.name) } } type Player struct{ id int name string }
/* Copyright 2022 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, softw...
package main import ( "log" "net/http" "github.com/Ankr-network/dccn-midway/handlers" "github.com/gorilla/mux" ) func main() { r := mux.NewRouter() // user management r.HandleFunc("/signup", handlers.Signup) // POST r.HandleFunc("/confirm_registration", handlers.ConfirmRegistration) // POST r.HandleFunc("...
package server import ( "fmt" //"github.com/danielkrainas/shrugmud/logging" ) type InputHandler func(input string, d *Descriptor) error type Ctrl interface { Do(input string, d *Descriptor) error ValidateState(state CtrlState) bool NewState(d *Descriptor) CtrlState } type CtrlState interface{} type CtrlRouter...
package bgControllers import ( "github.com/astaxie/beego" "fmt" "GiantTech/models" "GiantTech/controllers/tools" ) type BgUserUpdatePassWordController struct { beego.Controller } func (this *BgUserUpdatePassWordController) Prepare() { s := this.StartSession() username = s.Get("login") beego.Informational(use...
package notifications import ( "bytes" "fmt" "html/template" "log" "net/smtp" "net/url" "strings" ) // NotifyMessage is an interface to send notification messages for new posts // this gets sent when a post is set to 'published' for the first time type NotifyMessage interface { send(title string, url string) ...
/* * @lc app=leetcode.cn id=1385 lang=golang * * [1385] 两个数组间的距离值 */ // @lc code=start package main import "math" func findTheDistanceValue(arr1 []int, arr2 []int, d int) int { count := 0 for i := 0; i < len(arr1); i++ { flag := true for j := 0; j < len(arr2); j++ { if int(math.Abs(float64(arr1[i]-arr2[...
package 一维子串问题 /* 给定一个未经排序的整数数组,找到最长且连续的的递增序列。 */ func findLengthOfLCIS(nums []int) int { /* 1. 明白dp定义后,初始化dp数组 */ dp := make([]int, len(nums)) // 定义dp[i]为: 以nums[i]为结尾的最长递增串长度 for i := 0; i < len(nums); i++ { if i == 0 { /* 2. dp[i]基础情况处理 (nums[i]前面没有元素时) */ dp[i] = 1 continue } /* 3. 根据条件更新dp[i]...
package factories import ( "database/sql" "github.com/barrydev/api-3h-shop/src/common/connect" "github.com/barrydev/api-3h-shop/src/connections" "github.com/barrydev/api-3h-shop/src/model" ) func FindOneCoupon(query *connect.QueryMySQL) (*model.Coupon, error) { connection := connections.Mysql.GetConnection() ...
// SPDX-FileCopyrightText: (c) 2018 Daniel Czerwonk // // SPDX-License-Identifier: MIT package server import ( "context" "fmt" "math" "net" bnet "github.com/bio-routing/bio-rd/net" "github.com/bio-routing/bio-rd/protocols/bgp/types" "github.com/bio-routing/bio-rd/route" "github.com/czerwonk/bioject/pkg/api" ...
// Copyright 2020 orivil.com. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found at https://mit-license.org. package modes type BookPattern struct { ID int PlatformID int `gorm:"index"` Url string Title string Author ...
package memory import ( "fmt" "github.com/SergeyShpak/owngame/server/src/model/layers" "github.com/SergeyShpak/owngame/server/src/types" ) type memoryRoomLayer struct { rooms *rooms roomPlayers *roomPlayers roomAdmins *roomAdmin } func NewMemoryRoomLayer() (layers.RoomsDataLayer, error) { m := &memory...
package peach import ( "github.com/BurntSushi/toml" ) //TomlClient 解析toml文件的客户端 type TomlClient struct { mapping map[string]interface{} } //NewToml 新建toml func (t *TomlClient) NewToml(text []byte) (*TomlClient, error) { raws := map[string]interface{}{} if err := toml.Unmarshal(text, &raws); err != nil { return...
package controller import ( "enter-module/core/common" "enter-module/core/config" "enter-module/core/info" "fmt" "net/http" ) //获取服务配置 func GetConfig(w http.ResponseWriter, r *http.Request) { var configList [10]info.ConfigInfo var i = 0 for item, value := range config.MemoryRouteConfig { fmt.Println(item) ...
/* * @lc app=leetcode.cn id=20 lang=golang * * [20] 有效的括号 */ // @lc code=start package main import "fmt" // import "container/list" func main() { var s string s = "(())" fmt.Printf("%s, %t\n", s, isValid(s)) s = "(()))" fmt.Printf("%s, %t\n", s, isValid(s)) s = "()[]{}" fmt.Printf("%s, %t\n", s, isVali...
package proxy const ( // Thrift协议中 SEQ_ID的访问 BACKEND_CONN_MIN_SEQ_ID = 1 BACKEND_CONN_MAX_SEQ_ID = 1000000 // 100万次请求一个轮回(也挺不容易的) INVALID_ARRAY_INDEX = -1 // 无效的数组元素下标 HB_TIMEOUT = 6 // 心跳超时时间间隔 REQUEST_EXPIRED_TIME_MICRO = 5 * 1000000 // 5s TEST_PRODUCT_NAME ...
// Copyright 2018 The InjectSec 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 injectsec import "testing" func TestDetector(t *testing.T) { maker, err := NewDetectorMaker() if err != nil { t.Fatal(err) } detector := ...
// Package delayed wraps a datastore allowing to artificially // delay all operations. package delayed import ( delay "gx/ipfs/QmUe1WCHkQaz4UeNKiHDUBV2T6i9prc3DniqyHPXyfGaUq/go-ipfs-delay" ds "gx/ipfs/Qmf4xQhNomPNhrtZc67qSnfJSjxjXs9LWvknJtSXwimPrM/go-datastore" dsq "gx/ipfs/Qmf4xQhNomPNhrtZc67qSnfJSjxjXs9LWvknJtSXw...
package extended import "github.com/mkamadeus/cipher/cipher/hill" func Encrypt(plain []byte, key []byte) []byte { result := []byte{} for i, char := range plain { result = append(result, byte(hill.CorrectModulus(int(char+key[i%len(key)]), 256))) } return result }
package main import "github.com/daniilperestoronin/go-chain/cmd" func main() { cli := cmd.CLI{} cli.Run() }
// Copyright 2022 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 foo import "fmt" func init() { fmt.Println("foo.") } func Foo() { fmt.Println("foo Foo.") }
// Copyright 2020 MongoDB 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 in...
package user import ( "github.com/btnguyen2k/prom" "github.com/btnguyen2k/henge" ) // NewUserDaoAwsDynamodb is helper function to create AWS DynamoDB-implementation of UserDao. func NewUserDaoAwsDynamodb(dync *prom.AwsDynamodbConnect, tableName string) UserDao { var spec *henge.DynamodbDaoSpec = nil dao := &User...
package test import ( "fmt" "os" "testing" "github.com/gruntwork-io/terratest/modules/random" "github.com/gruntwork-io/terratest/modules/terraform" ) var githubOrganization, githubToken string func init() { githubOrganization = os.Getenv("GITHUB_OWNER") githubToken = os.Getenv("GITHUB_TOKEN") if githubOrga...
package models import ( "post_crud_golang/database" "github.com/jinzhu/gorm" ) type Post struct { gorm.Model Title string `gorm:"size:50;not null"` Content string `gorm:"size:2000;not null"` } func dbInit() (d *gorm.DB) { d = database.Init() defer d.Close() d.AutoMigrate(&Post{}) return d } func Insert(...
package log import "context" var ( root Logger ) // Root return default logger instance func Root() Logger { if root == nil { root = newGlog() } return root } // NewContext return a new logger context func NewContext(ctx context.Context, logger Logger) context.Context { if logger == nil { logger = Root() ...
package server import "github.com/SOMAS2020/SOMAS2020/internal/common/disasters" // probeDisaster checks if a disaster occurs this turn func (s *SOMASServer) probeDisaster() (disasters.Environment, error) { s.logf("start probeDisaster") defer s.logf("finish probeDisaster") e := s.gameState.Environment e = e.Samp...
package main import ( "fmt" "github.com/feng/future/design/factory/factory" ) func main() { var pf factory.PenFactory p := pf.Produce("brush") p.Write() var of factory.OperationFactory o := of.Produce("*") result := o.Operation(10, 20) fmt.Println(result) var bp factory.BrushPen f(bp) u := factory.Us...
package main import ( "strings" "github.com/corymurphy/adventofcode/shared" ) type Direction int const ( Unknown Direction = 0 Up Direction = 1 Down Direction = 2 Left Direction = 3 Right Direction = 4 ) type Instruction struct { Distance int Direction Direction } func (d Direction) String(...
/***************************************************************** * Copyright©,2020-2022, email: 279197148@qq.com * Version: 1.0.0 * @Author: yangtxiang * @Date: 2020-07-30 17:11 * Description: *****************************************************************/ package xthrift import "github.com/apache/thrift/lib/go/...
/* Package shaping provides tables corresponding to Unicode® Character Data tables relevant for text shaping. ___________________________________________________________________________ License This project is provided under the terms of the UNLICENSE or the 3-Clause BSD license denoted by the following SPDX identif...
package search import ( "testing" "github.com/stretchr/testify/assert" ) func TestGetYoutubeLink(t *testing.T) { tests := []struct { title string artists []string link string }{ {"CLOUDS", []string{"NF"}, "https://youtube.com/watch?v=JXOYZXb0no4"}, {"Blinding Lights", []string{"The Weeknd"}, "http...
package shell import ( "github.com/stretchr/testify/assert" "testing" ) func TestCommandsNameShouldReturnCommands(t *testing.T) { assert.Equal(t, "commands", commands(0).name()) } func TestCommandssDescriptionShouldNotBeEmpty(t *testing.T) { assert.NotEqual(t, "", commands(0).description()) } func TestCommandsU...
package iface type IRequest interface { GetLen() uint32 GetData() []byte GetConn() Iconnection }
package server import ( "encoding/json" "testing" "github.com/yekhlakov/gojsonrpc/common" ) func TestJsonRpcServer_AddHandler(t *testing.T) { s := NewServer() s.AddHandler(test_PassHandler{}, "Handle_") if len(s.Methods) != 1 { t.Errorf("Methods were not extracted from the first handler") } s.AddHandle...
/* make用于内建类型(map、slice 和channel)的内存分配。new用于各种类型的内存分配。 内建函数new本质上说跟其它语言中的同名函数功能一样:new(T)分配了零值填充的T类型的内存空间,并且返回其地址, 即一个*T类型的值。用Go的术语说,它返回了一个指针,指向新分配的类型T的零值。有一点非常重要: new返回指针。 内建函数make(T, args)与new(T)有着不同的功能,make只能创建slice、map和channel,并且返回一个有初始值(非零)的T类型, 而不是*T。本质来讲,导致这三个类型有所不同的原因是指向数据结构的引用在使用前必须被初始化。 例如,一个slice,是一个...
// Copyright 2022 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 sort // BucketSort 桶排序 func BucketSort(arr *[]int, bucketSize int) { if len(*arr) < 2 { return } var maxVal = (*arr)[0] var minVal = (*arr)[0] // 找到最大最小值 for _, v := range *arr { if v < minVal { minVal = v } else if v > maxVal { maxVal =...
// Package adapter contains the required logic for creating data structures used for // feeding CloudFormation templates. // // It follows the adapter pattern https://en.wikipedia.org/wiki/Adapter_pattern in the // sense that it has the knowledge to transform a aws custom object into a data structure // easily interpol...
package gitcomm import ( "fmt" "os" ) // CheckIfError should be used to naively panics if an error is not nil func CheckIfError(err error) { if err == nil { return } fmt.Printf("\x1b[31;1m%s\x1b[0m\n", fmt.Sprintf("error: %s", err)) os.Exit(1) } // Info should be used to describe the example commands that a...
// @Package gotorsocks // @Author: Kalle Vedin <kalle.vedin@fripost.org> // @Author: hIMEI <himei@tuta.io> // @Date: 2017-12-16 22:02:59 // @Copyright © 2017 hIMEI <himei@tuta.io> // @license MIT // gotorsocks Here is GitHub fork of https://bitbucket.org/kallevedin/torsocks. // Import path "code.google.com/p/go.net/...
//go:build test // +build test // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package service import ( "context" "encoding/json" "fmt" "io" "log" "net/http" "os/exec" "regexp" "time" "github.com/Azure/aks-engine/test/e2e/kubernetes/util" "github.com/pkg/er...
package vastflow import ( "github.com/jack0liu/logs" "io/ioutil" "math" "os" "os/exec" "path" "runtime" "strconv" "strings" "sync" "time" ) const ( DefaultWndCapacity = 500 defaultShrinkLen = 2 defaultExtendLen = 2 ) var flowWnd = &FlowWnd{ Capacity: DefaultWndCapacity, CurSize: 0, } var sys = ...
package core import ( "github.com/labstack/echo/v4" "github.com/pkg/errors" "html/template" "io" "path/filepath" ) type ( Template struct { LayoutPath string IncludePath string //Templates *template.Template templates map[string]*template.Template } ) func (t *Template) Render(w io.Writer, name stri...
package protocol type Command interface { Evaluate([]string) Result }
package main import "fmt" var x, y int var ( a int b bool ) var c, d int = 1, 2 var e, f = 123, "hello" func main(){ g, h := "g", "h" fmt.Println(x, y, a, b, c, d, e, f, g, h) i, j := 123, 456 fmt.Println(i, j) i = j // only copy values instead of reference fmt.Println(i, j) fmt.Pr...
// O exemplo mostra vários tipos de variáveis e também que as declarações de variáveis // podem ser "construídas" em blocos, como com as declarações de importação. // Os tipos int, uint e uintptr são geralmente de 32 bits em sistemas de 32 bits e 64 bits // em sistemas de 64 bits. Quando você precisar de um valor inte...
package apiResponse import ( "fmt" "net/http" config "github.com/alexhornbake/go-crud-api/config" log "github.com/alexhornbake/go-crud-api/lib/logging" ) type ErrorResponse struct { Status int Body interface{} } type errorBody struct { Error string } func InternalServerError(message interface{}, args ...i...
/* * 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 2013 The Camlistore Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
package httpresponse import ( "context" "encoding/json" "fmt" "net/http" ) type httpErrorResponse struct { Error string `json:"error"` ErrorDescription string `json:"error_description"` } // RespondJSON writes JSON as http response func RespondJSON(w http.ResponseWriter, httpStatusCode int, object i...
package agent import ( "crypto/md5" "fmt" "io" "strings" "github.com/astaxie/beego/httplib" ) type TaobaoAgent struct { Url string AppKey string Secret string Session string params map[string]string } func NewTaobaoAgent(url, appkey, secret, session string) *TaobaoAgent { a := new(TaobaoAgent) a....
package persistence import ( "database/sql" "errors" "gopetstore/src/domain" "gopetstore/src/util" "log" ) const getCategoryListSQL = "SELECT CATID AS categoryId,NAME,DESCN AS description FROM CATEGORY" const getCategoryByIdSQL = "SELECT CATID AS categoryId,NAME,DESCN AS description FROM CATEGORY WHERE CATID = ?...
package main type S int func main() { a := S(0) b := make([]*S, 2) b[0] = &a c := new(S) b[1] = c } //go run -gcflags "-m -l" escape.go
package virtualgateway import ( "context" appmesh "github.com/aws/aws-app-mesh-controller-for-k8s/apis/appmesh/v1beta2" "github.com/aws/aws-app-mesh-controller-for-k8s/pkg/k8s" "github.com/aws/aws-app-mesh-controller-for-k8s/pkg/webhook" "github.com/pkg/errors" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimach...
package types import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) var _ sdk.Msg = &MsgCreateCosmosToEth{} func NewMsgCreateCosmosToEth(sender string, ethDest string, amount string, bridgeFee string) *MsgCreateCosmosToEth { return &MsgCreateCosmosToEth{ Sende...
package main import ( "database/sql" _ "github.com/mattn/go-sqlite3" "strings" "log" "os" "io" "path/filepath" "fmt" "net/http" "net/url" ) const ( database = "austen.db" tempDir = "/tmp/output/data" outDir = "output" ) var ( db_length int...
// Copyright 2022 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 domain import ( "fmt" "regexp" "github.com/quintans/faults" ) // FullName is a Value Object representing a first and last names type FullName struct { firstName string lastName string } func (f FullName) String() string { return fmt.Sprintf("%s %s", f.firstName, f.lastName) } func NewFullName( firs...
package merkle import ( "crypto/sha256" "hash" "testing" ) func TestNewConfig(t *testing.T) { type input struct { hasher hash.Hash depth int hashSize int } type output struct { config *Config err error } testCases := []struct { name string in input out output }{ { "success: mi...
package utils import ( "net/url" "strconv" "github.com/athlum/gorp" "github.com/juju/errors" ) // Direction represents the sort direction // swagger:strfmt Direction // enum:ASC,DESC type Direction string // sort directions const ( Asc Direction = "ASC" Desc Direction = "DESC" ) const ( DefaultPageSize = ...
package inmem import ( chat "github.com/greatchat/gochat/transport" ) type client struct { chanBuff int channels map[string]chan chat.Message } // NewClient initalises new in memory client func NewClient(chanBuffer int) chat.BasicClient { return &client{ chanBuff: chanBuffer, channels: make(map[string]chan c...
package main import "fmt" const heightTallPerson = 1.90 func main() { firstName := "Joabe" lastName := "Leão" heightInMeters := 1.72 workInAVCorp := true monthsWork := 30 if len(firstName) < 1 || firstName == "" { panic("O primeiro nome esta vazio.") } if firstName == "Joabe" { fmt.Println("Ele é o Joa...
package service type Update interface { Do(event UpdateEvent) error }
package builder import ( exec "os/exec" "../../../contract/request" sshBuilder "../../../domain/builder" ) type SshCommandBuilder struct { } func InitSshCommandBuilder() sshBuilder.ISshCommandBuilder { builder := &SshCommandBuilder{} return builder } func (b *SshCommandBuilder) BuildSshCommand(request request...
package command import ( "context" "github.com/quintans/faults" "github.com/quintans/go-clean-ddd/internal/app" "github.com/quintans/go-clean-ddd/internal/domain" "github.com/quintans/go-clean-ddd/internal/domain/customer" ) type UpdateCustomerHandler interface { Handle(context.Context, UpdateCustomerCommand) ...
package main import ( "bufio" "log" "net/http" "os" "strings" ) var ( Headers map[string]*tokenizedString ) func loadHeaders() { Headers = map[string]*tokenizedString{} file, err := os.Open(*headersFile) if err != nil { //Probably file not found } else { defer file.Close() scanner := bufio.NewScanne...
package main import ( "fmt" ) func sortedSquares(A []int) []int { ret := make([]int, len(A)) // 使用两个指针,一个指向第一个,一个指向最后一个, 然后挨个比较,比较后的值,从后往前填入到要返回的数组中 i := 0 j := len(A) - 1 n := j for i <= j { if abs(A[i]) >= abs(A[j]) { ret[n] = abs(A[i]) n-- i++ continue } else { ret[n] = abs(A[j]) n--...
package mq import ( "encoding/json" "fmt" "github.com/streadway/amqp" "mq-go/config" "testing" "time" ) func TestAdmin(t *testing.T) { adminMq := Admin() msg := AdminMsg{ Name: "ybdx", Value: "hello", } adminMq.Publish(msg) } func TestQueue_Consume(t *testing.T) { adminMq := Admin() adminMq.Consume(...
package main // 优美的解法 (根本在于消除长度差) // 迭代解法 func getIntersectionNode(headA, headB *ListNode) *ListNode { pA, pB := headA, headB for pA != pB { if pA == nil { pA = headB } else { pA = pA.Next } if pB == nil { pB = headA } else { pB = pB.Next } } return pA } func main() { } /* 题目链接: https:...
package trello type Checklist struct { Id string `json:"id"` Name string `json:"name"` IdBoard string `json:"idBoard"` IdCard string `json:"idCard"` Pos float32 `json:"pos"` CheckItems []struct { State string `json:"state"` Id string `json:"id"` Name s...
package main import ( "github.com/colinmarc/hdfs/v2" "os" "time" ) func touch(paths []string, noCreate bool, accessTime bool, modifyTime bool) { paths, nn, err := normalizePaths(paths) if err != nil { fatal(err) } if len(paths) == 0 { printHelp() } client, err := getClient(nn) if err != nil { fatal(...
package storage import ( "encoding/json" "path/filepath" "sync" "time" ) const ( MaxRecordsPerFile = 10 ResultsSubdirectory = "results" ProductSubdirectory = "results_by_product" ) var FlushInterval = time.Second // FIXME make into a parameter. turned var from const to make tests more responsive // batchWr...
package main import ( "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" // 选择驱动 ) type Product struct { gorm.Model Code string Price uint } var product Product // 根据ID查询数据 func R(id int, db *gorm.DB) { res := db.First(&product, id).Value // 查询id为1的product if res.(Product).Model.ID =...
package swarm import ( "crypto/rand" "crypto/rsa" "crypto/tls" "crypto/x509" "encoding/binary" "encoding/pem" "errors" "io" "log" "math/big" "net" "github.com/pion/stun" ) func addrFromStun(conn *net.UDPConn) (string, error) { raddr, err := net.ResolveUDPAddr("udp4", "stun.l.google.com:19302") if err !...
// kggseq project doc.go /* kggseq document */ package main
package swarm import ( "errors" "github.com/docker/engine-api/types" "github.com/docker/engine-api/types/swarm" "github.com/gaia-docker/tugbot-leader/mockclient" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "testing" ) func TestIsValidNode_Error(t *testing.T) { client := mockclient....
package linked_lists import ( "testing" ) func TestListFromSlice(t *testing.T) { tests := []struct { in []int expected bool }{ {[]int{1, 2, 3, 4, 5}, false}, } for _, test := range tests { actualList := listFromSlice(test.in...) actualSlice := sliceFromList(actualList) if len(actualSlice) != ...
package skel import ( "github.com/globalsign/mgo" ) // Get 定义获取操作 func (skel *Skel) Get() (skelRet *Skel, err error) { c := skel.GetC() defer c.Database.Session.Close() err = c.Find(skel).One(&skelRet) if err != nil { if err != mgo.ErrNotFound { return } err = nil return } return }
package mos6502 import ( "testing" "github.com/KaiWalter/go6502/pkg/addressbus" "github.com/KaiWalter/go6502/pkg/memory" ) const ( endOfDecimalTest = 0x024b resultDecimalTest = 0x0b ) func TestDecimal(t *testing.T) { // arrange ramContent, err := RetrieveROM("6502_decimal_test.bin") if err != nil { t.Er...
package executor_runner import ( "fmt" "os/exec" "strings" "time" "github.com/onsi/ginkgo" "github.com/onsi/ginkgo/config" . "github.com/onsi/gomega" "github.com/onsi/gomega/gbytes" "github.com/onsi/gomega/gexec" ) type ExecutorRunner struct { executorBin string listenAddr string wardenNetwork strin...