text
stringlengths
11
4.05M
// Copyright 2019 The OpenSDS 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 agre...
package types import ( "fmt" "reflect" "strings" "github.com/docker/docker/api/types" "github.com/globalsign/mgo/bson" "github.com/portainer/libcompose/config" yaml "gopkg.in/yaml.v3" ) // GroupLight data type GroupLight struct { ID bson.ObjectId `json:"_id,omitempty" bson:"_id,omitempty"` Name ...
package cmd import ( "adminbot/framework" "adminbot/config" "fmt" "encoding/json" "io/ioutil" "strconv" "time" "strings" ) func KickCommand(ctx framework.Context) { // TODO [!] In progress if !HasRole(ctx.Discord, ctx.User.ID, "admin"){ return } if len(ctx.Args) =...
package set_monitor import ( "context" "fmt" "go.etcd.io/etcd/clientv3" ) func SetURLToMonitorAll(address, name, url string) { cfg := clientv3.Config{Endpoints: []string{address}} c, err := clientv3.New(cfg) defer c.Close() if err != nil { fmt.Println(c) fmt.Println("err: ", err) } fmt.Println("Check 1...
package keepalive /* #include <stdlib.h> struct Thing { long long *ptr; int len; }; struct Thing* newThing(long long * arr, int len) { struct Thing* t = (struct Thing*)malloc(sizeof(struct Thing));; t->ptr = arr; t->len = len; return t; } long long doIt(struct Thing *t) { long long sum =...
package main import ( "fmt" ) type ListCommand struct{} func (l *ListCommand) Execute(args []string) error { triggers, err := getTriggers(options.APIHost, options.Dataset, options.WriteKey) if err != nil { fmt.Println("Failed to list triggers: ", err) return err } for _, trigger := range triggers { fmt.P...
package windows import "syscall" const ( errnoERROR_IO_PENDING = 997 ) var ( errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) ) const ( EVENT_MIN uint32 = 0x00000001 EVENT_MAX uint32 = 0x7FFFFFFF EVENT_SYSTEM_FOREGROUND uint32 = 0x0003 WINEVENT_SKIPOWNPROCESS uint32...
package main import "bufio" //import "flag" // can't use, doesn't allow repeated options (--enable vrr --enable irnr) import "fmt" //import "log" import "io" import "os" import "strings" import "voteutil" // from countvotes.c /* countvotes [--dump][--debug][--preindexed]\n" "\t[--full-html|--no-full-html|--no-html-h...
package leetcode /*A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above. Given the array reservedSeats containing the numbers of seats already reserved, for example, reservedSeats[i]=[3,8] means the seat located in row 3 and labelle...
package models import "go.mongodb.org/mongo-driver/bson/primitive" type Article struct { ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"` Id string `json:"id,omitempty" bson:"id,omitempty"` Title string `json:"title" bson:"title,omitempty"` SubTitle string ...
package service import ( "fmt" "github.com/jdcloud-cmw/jdsf-demo-go/jdsf-demo-client/jdsfapi" "github.com/jdcloud-cmw/jdsf-demo-go/jdsf-demo-client/sling" "github.com/opentracing/opentracing-go" "io/ioutil" "net/http" ) func RegistryCheck(w http.ResponseWriter, r *http.Request) { t1 := opentracing.GlobalTracer...
// +build hosted package router import ( "regexp" "strings" ) var hostedDomainPattern *regexp.Regexp func init() { hostedDomainPattern = regexp.MustCompile("(eventgateway([a-z-]*)?.io|slsgateway.com)") } func extractPath(host, path string) string { if hostedDomainPattern.Copy().MatchString(host) { subdomain ...
package main import ( "fmt" "io" "os" "github.com/mitchellh/cli" "github.com/romantomjak/b2/command" "github.com/romantomjak/b2/version" ) func main() { os.Exit(Run(os.Stdin, os.Stdout, os.Stdout, os.Args[1:])) } func Run(stdin io.Reader, stdout, stderr io.Writer, args []string) int { ui := &cli.BasicUi{ ...
package provider import ( "github.com/hashicorp/terraform/helper/schema" "github.com/mrparkers/terraform-provider-keycloak/keycloak" ) func resourceKeycloakRole() *schema.Resource { return &schema.Resource{ Create: resourceKeycloakRoleCreate, Read: resourceKeycloakRoleRead, Delete: resourceKeycloakRoleDele...
package caaa import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00800102 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:caaa.008.001.02 Document"` Message *AcceptorCancellationAdviceResponseV02 `xml:"AccptrCxlAdvcRspn"` } ...
package p08 func largeGroupPositions(S string) [][]int { ret := make([][]int, 0) curChar := S[0] startIndex := 0 endIndex := 0 for i := 1; i < len(S); i++ { if S[i] == curChar { endIndex = i if i == len(S)-1 { l := endIndex - startIndex + 1 if l >= 3 { ret = append(ret, []int{startIndex, endI...
package riverntorch var _ RiverCrosser = (*fastestBearerApproach)(nil) var _ RiverCrosser = (*clubSlowestApproach)(nil) type RiverCrosser interface { //get name of the approach been used GetName() string //cross all people from SideA to SideB. //gives back solution object, with details about the process. Cross(...
// Copyright 2021 Tamás Gulácsi. All rights reserved. package main import ( "io" "log" "os" plsqlparser "github.com/UNO-SOFT/plsql-parser" ) func main() { if err := Main(); err != nil { log.Fatalf("ERROR: %+v", err) } } func Main() error { text, _ := io.ReadAll(os.Stdin) return plsqlparser.ChromaParse(str...
/* SPDX-License-Identifier: Apache-2.0 * Copyright (c) 2019-2020 Intel Corporation */ package ngcnef import ( "context" "encoding/json" "errors" "io/ioutil" "net/http" "strconv" "strings" //"strconv" "github.com/gorilla/mux" ) func createNewSub(nefCtx *nefContext, afID string, ti TrafficInfluSub) (loc s...
package main import ( "bytes" "context" "crypto/md5" "encoding/json" "fmt" "io/ioutil" "net/http" "os" "reflect" "regexp" "strconv" "time" "github.com/confluentinc/confluent-kafka-go/kafka" "github.com/gomodule/redigo/redis" "gopkg.in/olivere/elastic.v7" ) var newsSummary map[string][]StdNews var news...
package cli import ( "io" "os" "strings" "unicode" "github.com/alecthomas/kong" "github.com/gotidy/app/pkg/scope" ) type LoggingFormat string func (l LoggingFormat) AfterApply(scope *scope.Scope, writer *ConsoleWriter) error { format := ColoredTextFormat switch strings.ToLower(string(l)) { case "coloredtex...
package v1 import ( "github.com/seaung/Go-Scaffolding/api/v1" "github.com/gin-gonic/gin" ) func InitUserRouters(router *gin.RouterGroup) { router.GET("/demon", v1.Demon) }
/***************************************************************** * Copyright©,2020-2022, email: 279197148@qq.com * Version: 1.0.0 * @Author: yangtxiang * @Date: 2020-08-26 17:00 * Description: *****************************************************************/ package regcenter import ( "fmt" "github.com/go-xe2/x/...
package bag01 // New 创建01背包问题 func New(itemsW []int, w int) *Bag01 { n := len(itemsW) if n == 0 || w == 0 { panic("error params") } // 初始化状态数组 status := make([][]bool, n) for i := 0; i < n; i++ { status[i] = make([]bool, w+1) } return &Bag01{itemsW, w, status} } // Bag01 01背包问题 // 固定物品范围的前提下,求背包可放物品最大重量 t...
package converter import ( "github.com/stretchr/testify/assert" "testing" ) // Test case with incorrect input string with all digit cases func TestInvalidInputStringWithDigits(t *testing.T) { inputStrings := []string{ "4abc", "4563", } for _, input := range inputStrings { converter := NewStringConverter(i...
package service import ( entity "github.com/Surafeljava/Court-Case-Management-System/Entity" "github.com/Surafeljava/Court-Case-Management-System/caseUse" ) type OpponentServiceImpl struct { oppoRepo caseUse.OpponentRepository } func NewOpponentServiceImpl(opRepo caseUse.OpponentRepository) *OpponentServiceImpl {...
package web_test import ( "bytes" "context" "encoding/json" "fmt" "net/http" "net/http/httptest" "testing" account "williamfeng323/mooncake-duty/src/domains/account" "williamfeng323/mooncake-duty/src/domains/project" repoimpl "williamfeng323/mooncake-duty/src/infrastructure/db/repo_impl" "williamfeng323/moo...
/* A laser shoots a straight beam in one of the four orthogonal directions, indicated by <>^v. Determine whether it will hit the target O on a rectangular grid. Each of these will hit (True): ..... ...O. ..... ...^. ..... >O. ... v.... O.... ........... ........... O.........< ........... These will miss (False):...
package router import ( "fmt" "log" "github.com/nedp/command" "github.com/nedp/command/sequence" ) const defaultRoutesCapacity = 6 type Router struct { routes map[string]func() Route slots chan *slots } type Interface interface { RouteFor(string) (Route, error) SequenceFor(string) (sequence.RunAller, error...
package common import ( "fmt" "os" "os/user" log "github.com/yugabyte/yugabyte-db/managed/yba-installer/logging" ) /* * Utility methods that allow us to log common actions * like making dirs, copying files, etc */ func MkdirAll(path string, perm os.FileMode) error { log.Debug(fmt.Sprintf("Creating dir %s", pa...
package main import "fmt" func main() { ii := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} n := foo(ii...) fmt.Println(n) ii1 := []int{11, 22, 33, 44, 55} n2 := bar(ii1) fmt.Println(n2) } func foo(xi ...int) int { total := 0 for _, v := range xi { total += v } return total } func bar(x []int) int { total := 0 for ...
package postgres import ( "database/sql" "github.com/idena-network/idena-indexer/explorer/types" ) const ( identityQuery = "identity.sql" identityAgeQuery = "identityAge.sql" identityAnswerPointsQuery = "identityAnswerPoints.sql" identityCurrentFlipsQuery = "identityCurr...
package dbtool type ( // Config config for postgres tool Config struct { DBName string DBUser string DBPass string Host string Port string } // Configurer return config Configurer interface { Config() *Config } )
package controller import ( "encoding/json" "fmt" "main/model" "main/structs" "main/utils" "net/http" "strconv" database "g.ghn.vn/scte-common/godal" "github.com/labstack/echo/v4" ) var ( EMP_DEP string = "emp_dep" ) func AddEmployeeToDepartment(c echo.Context) error { var err error // get data from re...
package services import ( "fmt" "github.com/CS-SI/SafeScale/utils" "github.com/pkg/errors" log "github.com/sirupsen/logrus" "io" "os" ) func init() { log.SetFormatter(&utils.MyFormatter{ TextFormatter: log.TextFormatter{ForceColors:true, TimestampFormat : "2006-01-02 15:04:05", FullTimestamp:true, DisableLevel...
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package api import ( "strconv" "strings" "github.com/Azure/aks-engine/pkg/api/common" ) func (cs *ContainerService) setCloudControllerManagerConfig() { o := cs.Properties.OrchestratorProfile isAzureCNIDualStack := c...
package exportAsciinemaJson import ( "encoding/json" tsm "github.com/stbuehler/go-termrecording/libtsm" "github.com/stbuehler/go-termrecording/rawrecording" "io" ) type FilmFrame struct { Delay float64 Diff interface{} } type FilmMaker struct { FirstFrameOffset float64 LastFrameOffset float64 PreviousFram...
package ssh import ( "fmt" "io/ioutil" "os" "sort" "time" ) // реализация сортировки hosts, необходимо чтобы вниз сваливались пофейленные type sortHostStates struct { slice []*hostState } func (h sortHostStates) Len() int { return len(h.slice) } func (h sortHostStates) Swap(i, j int) { h.slice[i], h.slice[j]...
package main import ( "fmt" "grpc/proto" "context" "net" "google.golang.org/grpc" ) type Message struct {} func main() { lis, err := net.Listen("tcp", ":4040") if err != nil { fmt.Println(err) } grpcServer := grpc.NewServer() proto.RegisterMessageServiceServer(grpcServer, &Message{}) if e := grpcServer...
/***************************************************************** * Copyright©,2020-2022, email: 279197148@qq.com * Version: 1.0.0 * @Author: yangtxiang * @Date: 2020-08-07 12:15 * Description: *****************************************************************/ package netstream import ( "io" "net/http" ) type Str...
package pg import ( "github.com/kyleconroy/sqlc/internal/sql/ast" ) type ResTarget struct { Name *string Indirection *ast.List Val ast.Node Location int } func (n *ResTarget) Pos() int { return n.Location }
package Problem0350 func intersect(a1, a2 []int) []int { res := []int{} m1 := getInts(a1) m2 := getInts(a2) if len(m1) > len(m2) { m1, m2 = m2, m1 } // m1 是较短的字典,会快一些 for n := range m1 { m1[n] = min(m1[n], m2[n]) } for n, size := range m1 { for i := 0; i < size; i++ { res = append(res, n) } } ...
package main import ( "fmt" "net" "os" "strings" ) type User struct { Name string ChatConn *net.UDPConn } var ErrorCode = 1 //监听的端口 && 地址 var ServerPort = ":1212" var LocalHost = "127.0.0.1" // var isOnline = make(map[string]*net.UDPConn) var userSlice = make([]User, 0) //心跳包检查,检...
func oddEvenList(head *ListNode) *ListNode { i := 0 if head == nil || head.Next == nil { return head } node := head pre := node pre1 := node.Next for node != nil { if i != 0 && i%2 == 0 { pnext := pre.Next nnext := node.Next pre.Next = node pre1.Next = nnext node.Next = pnext node = pre1 ...
package blockchain import ( "bytes" "encoding/gob" "log" "time" ) type Block struct { Timestamp int64 Hash []byte // current hash Transactions []*Transaction // transactions on block. needs to have at least 1 transaction. can have many different transactions as well PrevHash []byte // last blocks hash Nonce ...
/* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
package block import ( "bytes" "crypto/sha256" "fmt" "math/big" ) //共识算法管理文件 //实现POW实例以及相关功能 //目标难度值 const targetBit = 16 //工作量证明的结构 type ProofOfWork struct { // 需要共识验证的区块 Block *Block // 目标难度的哈希 target *big.Int } //创建一个POW对象 func NewProofOfWork(block *Block) *ProofOfWork { target := big.NewInt(1) //数据长...
package merkletree import "hash" type LeafHasherz interface { HashLeaf(leaf []byte) []byte } type NodeHasher interface { HashNode(l, r []byte) []byte } type TreeHasher interface { LeafHasherz NodeHasher } var _ TreeHasher = &DefaultTreeHasher{} type DefaultTreeHasher struct { h hash.Hash } func NewDefaultHash...
package virtualbox import ( "bufio" "encoding/binary" "fmt" "io" "github.com/Cloud-Foundations/Dominator/lib/format" ) type headerType struct { Header [0x40]byte Signature uint32 VersionMajor uint16 VersionMinor uint16 HeaderSize uint32 ImageType uint32 ImageFlags uin...
// +build acceptance networking package v2 import ( "testing" "github.com/gophercloud/gophercloud/acceptance/clients" "github.com/gophercloud/gophercloud/acceptance/tools" "github.com/gophercloud/gophercloud/openstack/networking/v2/ports" ) func TestPortsList(t *testing.T) { client, err := clients.NewNetworkV2...
package main // oauth.go contains utility functions for managing oauth connections. // Credit to the Go examples, from which this is mostly copied: // https://code.google.com/p/google-api-go-client/source/browse/examples // and which are Copyright (c) 2011 Google Inc. All rights reserved. import ( "encoding/gob" "...
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. // Package engine takes an AKS cluster model and generates the corresponding template. package engine
package cmd import ( "fmt" "github.com/spf13/cobra" ) const ( addCommandUse = "add" shortAddCommand = "Add pair key-value to cache" longAddCommand = "Add pair key-value to cache with expiress time" ) // NewAddCommand return new add command func NewAddCommand() *cobra.Command { addCmd := &cobra.Command{ ...
func longestCommonPrefix(strs []string) string { size := len(strs) if size == 0 { return "" } result := strs[0] for i := 0; i < size; i++ { curr := strs[i] result = comparePrefix(result, curr) } return result } func min(i1, i2 int) int { if i1 > i2...
package efclient import ( "bytes" "encoding/json" "fmt" "log" "math/rand" "net/http" "sync" "time" "syreclabs.com/go/faker" "syreclabs.com/go/faker/locales" ) // ProductCategories ... type ProductCategories = []ProductCategory // ProductCategory ... type ProductCategory struct { ID ...
package main import ( mlocswuc "leetcode/maxlengthofconcatstrwithuniquechars" "log" "time" ) func main() { start := time.Now() uniques := mlocswuc.MaxLength([]string{"cha", "r", "act", "ers"}) elapsed := time.Since(start) log.Println(elapsed) log.Println(uniques) }
package main import ( "testing" ) var ( root string patterns []string args = []string{"/opt/local", "e"} ) func init() { root, patterns = parseArgs(args) } func BenchmarkParseArgs(b *testing.B) { for n := 0; n < b.N; n++ { parseArgs(args) } } func BenchmarkWalk(b *testing.B) { for n := 0; n < b.N...
package flow import ( "sync" "testing" ) // Starter component fires the network // by sending a number given in its constructor // to its output port. type starter struct { Component Start <-chan float64 Out chan<- int } func (s *starter) OnStart(num float64) { s.Out <- int(num) } func newStarter() interfac...
package assembler import ( "testing" "log" ) func init() { var a float32 = 2 x := []float32{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1} y := []float32{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1} //log.Printf("avx %f", SaxpyAvx(a, x, y)) if useAVX { SaxpyAvx(a, x, y) } log.Printf("x %v", x) //log....
package main import ( "fmt" "math" ) type Abser interface { Abs() float64 } func main() { var a, b Abser f := MyFloat(-math.Sqrt2) v := Vertex{3, 4} a = f // MyFloat implements Abser b = &v // *Vertex implements Abser fmt.Println(b.Abs()) // 5 fmt.Println(a.Abs()) // 1.4142 ...
package collector import ( "github.com/prometheus/client_golang/prometheus" ) func init() { registerCollector("tcp", true, NewTCPCollector) } const ( tcpCollectorSubsystem = "tcp" ) var ( tcpPacketsReceivedTotal = prometheus.NewDesc( prometheus.BuildFQName(namespace, tcpCollectorSubsystem, "tcp_packets_receiv...
// // Copyright 2020 IBM Corporation // // 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 ...
package main import ( "fmt" ) func main() { messagesChan := make(chan string) signalsChan := make(chan bool) // non-blocking receive. If there is no one sends through channel, do what in the "default" select { case msgStr := <-messagesChan: fmt.Println("received: ", msgStr) default: fmt.Println("no messag...
package main import "testing" func TestPalindrome(t *testing.T) { tables := []struct { input string result bool }{ {"abba", true}, {"abbba", true}, {"aabba", false}, {"ababba", false}, {"ababa", true}, } for _, table := range tables { result := Palindrome(table.input) if result != table.result...
package handler import ( "log" "net/http" . "github.com/patrickmn/go-cache" "github.com/go-openapi/runtime/middleware" "github.com/gorilla/mux" ) func Routes(c *Cache) *mux.Router { // Register handler functions. r := mux.NewRouter() r.Use(loggingMiddleware) r.HandleFunc("/", NothingToDoHandler).Methods("G...
package database import ( "context" "ctipo/pkg/models" "strings" "github.com/georgysavva/scany/pgxscan" "github.com/prometheus/common/log" ) const getPacienteQuery = "SELECT nome,cpf, prontuario, data_nascimento,sexo, id_endereco FROM Paciente where prontuario = $1" const buscaPacientesQuery = "SELECT nome,cpf,...
package main import ( "fmt" ) func main() { c := make(chan int, 10) c <- 0 fmt.Printf("%#v, len: %v, cap: %v\n", c, len(c), cap(c)) }
package main import ( "fmt" "time" ) func sendMessages(receiver chan string) { // Create a slice of some strings to send. messages := []string{ "ping", "pong", "pinggg", } // Send the 3 messages to the receiver for _, m := range messages { fmt.Println("sendMessages is sending:", m) receiver <- m }...
package main /** 和为K的子数组 给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。 示例 1: ``` 输入:nums = [1,1,1], k = 2 输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。 ``` 说明 : - 数组的长度为 [1, 20,000]。 - 数组中元素的范围是 [-1000, 1000] ,且整数 k 的范围是 [-1e7, 1e7]。 */ /** 太晚了,今天过了吧 */ func SubarraySum(nums []int, k int) int { return -1 }
package blevebench import ( "encoding/json" "io/ioutil" "log" "github.com/blevesearch/bleve" ) type BenchConfig struct { IndexType string `json:"index_type"` KVStore string `json:"kvstore"` KVConfig map[string]interface{} `json:"kvconfig"` } func LoadConfigFile(path string)...
package main import ( "context" "fmt" "github.com/coreos/etcd/clientv3" "time" ) func main() { //在服务器启动etcd // nohup ./etcd --listen-client-urls 'http://0.0.0.0:2379' --advertise-client-urls 'http://0.0.0.0:2379' & config := clientv3.Config{ Endpoints: []string{"127.0.0.1:2379"}, //集群列表 DialTimeout: 5 * ...
package main import ( "fmt" ) // in return we don't have to write variable names if return values are defined as follows func addSub(x int, y int) (add int, sub int) { add = x + y sub = x - y return } func main() { add, sub := addSub(14, 7) fmt.Println(add, sub) }
package child import ( "gopkg.in/mgo.v2/bson" "time" mgo "gopkg.in/mgo.v2" ) type ChildRepo struct { Collection *mgo.Collection } //MONGO FUNCTIONS func (repo ChildRepo) create(member *Child) error { //check the family query := bson.M{ "family_id": member.Family, "name": member.Name, } exist, err := ...
package inspect import ( "testing" "github.com/makkes/gitlab-cli/mock" ) func TestSubCommands(t *testing.T) { cmd := NewCommand(mock.Client{}) subCmds := cmd.Commands() if len(subCmds) != 3 { t.Errorf("Expected 1 sub-command but got %d", len(subCmds)) } if cmd.UseLine() != "inspect" { t.Errorf("Unexpected...
package realm import ( "encoding/json" "fmt" "net/http" "github.com/10gen/realm-cli/internal/utils/api" ) // Routes for functions const ( FunctionsPattern = appPathPattern + "/functions" AppDebugExecuteFunctionPattern = appPathPattern + "/debug/execute_function" ) type stats struct { ExecutionT...
package routers import ( "github.com/gorilla/mux" "github.com/ismayilmalik/avengers-api/controllers" ) func InitUserRoutes(r *mux.Router) *mux.Router { controller := controllers.UserController{} router := mux.NewRouter() router.HandleFunc("/users", controller.Create).Methods("POST") router.HandleFunc("/users/l...
package server import ( "github.com/gin-gonic/gin" "gopkg.in/mgo.v2" "net/http" ) func NewServer(session *DatabaseSession) *gin.Engine { s := gin.Default() s.Use(session.Database()) s.GET("/persons", func(c *gin.Context) { db := c.MustGet("db").(*mgo.Database) c.JSON(http.StatusOK, fetchAllPersons(db)) }) ...
package main import ( "CaculatorAPI/router" "github.com/Sirupsen/logrus" "net/http" "os" ) func main() { rCors := router.CompleteRouterSetup() port := os.Getenv("PORT") port = "8080" if port == "" { logrus.Error("$Cannot get #PORT value from system and port value has been set to 8080") port = "8080" } ...
package amazon import ec2 "github.com/aws/aws-sdk-go/service/ec2" import mock "github.com/stretchr/testify/mock" // mockClient is an autogenerated mock type for the client type type mockClient struct { mock.Mock } // AssociateAddress provides a mock function with given fields: _a0 func (_m *mockClient) AssociateAdd...
/* * @lc app=leetcode.cn id=1275 lang=golang * * [1275] 找出井字棋的获胜者 */ package main // @lc code=start func tictactoe(moves [][]int) string { board := make([][3]int, 3) for i := 0; i < len(moves); i++ { board[moves[i][0]][moves[i][1]] = i%2 + 1 } for i := 0; i < 3; i++ { if board[i][0] != 0 && board[i][0] == ...
package main import ( "database/sql" "encoding/json" "fmt" "log" "net/http" "os" _ "github.com/mattn/go-sqlite3" ) type Tx struct { FromAddress string `json:"fromAddress"` TxHash string `json:"txHash"` } func main() { if _, err := os.Stat("txdb.db"); os.IsNotExist(err) { file, e...
package api import ( "fmt" "os" "github.com/arxdsilva/olist/storage" "github.com/labstack/echo" "github.com/labstack/echo/middleware" ) type Server struct { Storage storage.Storage Port string } func New() *Server { return &Server{Port: port()} } func (s *Server) Listen() { e := echo.New() e.Use(middl...
package profiling import ( "fmt" httpProf "net/http/pprof" "os" "path/filepath" "runtime" "runtime/pprof" "sync" "time" "github.com/gorilla/mux" "github.com/pkg/errors" "github.com/spf13/pflag" ) // Profiler helps setup and manage profiling type Profiler struct { // Dir, if set, is the path where profili...
package common import ( _"time" _"fmt" "encoding/json" _"sysmonitor/profile" ) func JsonMarshal(Network interface{}) string { b, err := json.Marshal(Network) if err != nil { return "" } else { return string(b) } } /* func GetLocalTime() string { local, err := time.Lo...
//import "github.com/solomonooo/mercury" //author : solomonooo //create time : 2016-09-08 package mercury import ( "bufio" "fmt" "io" "os" "strconv" "strings" ) const ( CONFIG_FILE = "mercury.conf" DEFAULT_LISTEN_IP = "0.0.0.0" DEFAULT_LISTEN_PORT = 7531 DEFAULT_RECV_BUFF_SIZE = 32 * 1024 DEFAU...
package ierr const ( Success = 0 // 请求相关 BindDataError = 10001 InvalidEmailOrPassword = 10002 InvalidRequestPhone = 10003 InvalidRequestParams = 10004 UnexpectedError = 10010 // 用户 InvalidUserId = 20001 InvalidToken = 20002 InvalidPassword = 20003 I...
package jws type ClaimSet struct { Iss string `json:"iss"` Sub string `json:"sub,omitempty"` }
// Copyright 2015 The Chromium 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 main import ( "errors" "fmt" "github.com/kr/pretty" "github.com/luci/luci-go/client/swarming" "github.com/maruel/subcommands" ) var cmdReq...
package popcount // pc[i] is the population count of i (number of set bits) var pc [256]byte func init() { for i := range pc { // i = (i / 2) * 2 + i % 2 // to double a binary number shift left (last bit is 0) // so the popcount of i is popcount of i / 2 plus 1 if i % 2 == 1 pc[i] = pc[i/2] + byte(i&1) // ...
package main const ( MessageCardSelected = "MessageCardSelected" MessageCardDeselected = "MessageCardDeselected" MessageCardResizeCompleted = "MessageCardResizeCompleted" MessageCardResizeStart = "MessageCardResizeStart" MessageCardDeleted ...
package main import "fmt" func main() { ids := []int{12, 26, 35, 4, 54, 6, 73} fmt.Println(ids) // range for i, id := range ids { fmt.Printf("%d - ID: %d\n", i, id) } // not using index for _, id := range ids { fmt.Printf("ID: %d\n", id) } // add ids together sum := 0 for _, id := range ids { sum...
package controller import ( "Seaman/config" "Seaman/model" "Seaman/service" "Seaman/utils" "github.com/kataras/iris/v12" "github.com/kataras/iris/v12/mvc" "github.com/kataras/iris/v12/sessions" "strconv" "time" ) /** * 项目控制器结构体:用来实现处理项目模块的接口的请求,并返回给客户端 */ type ProjectController struct { //上下文对象 Ctx iris....
package assembler import ( "math/rand" "testing" "time" ) func init(){ rand.Seed(time.Now().Unix()) } func TestSaxpy(t *testing.T) { for j := 0; j < 100; j++ { X := make([]float32, j) Y := make([]float32, j) Y1 := make([]float32, j) for i := range X { X[i] = rand.Float32()*0.2 - 0.1 Y[i] = rand.F...
package main import ( "fmt" goredislib "github.com/go-redis/redis/v8" "github.com/go-redsync/redsync/v4" "github.com/go-redsync/redsync/v4/redis/goredis/v8" "time" ) func main() { // Create a pool with go-redis (or redigo) which is the pool redisync will // use while communicating with Redis. This can also be ...
package post import ( "github.com/gofiber/fiber" ) func RegisterURLs(app *fiber.App) { router := app.Group("/posts") router.Get("/submit", publish) router.Get("/:id", get) router.Post("/", post) } func get(c *fiber.Ctx) { context := fiber.Map{ "id": c.Params("id"), } err := c.Render("post/post", context, "...
package main import "fmt" const g_s string = "the global constant" func main() { fmt.Println(g_s) const l_s = "the local constant" fmt.Println(l_s) }
package jarvisbot import ( "fmt" "io/ioutil" "math/rand" "os" "path" "github.com/boltdb/bolt" "github.com/kardianos/osext" "github.com/tucnak/telebot" ) // jokes.go contain joke functions. Not part of jarvisbot's default funcmap // SendLaugh returns Jon's laugh. Thx, @jhowtan func (j *JarvisBot) SendLaugh(m...
package propertiesRepository import ( "github.com/button-tech/BNBTextWallet/data" "github.com/button-tech/BNBTextWallet/services/redisService" "time" ) const propertiesLifetime = 24 * 30 * time.Hour func Read(identifier string) (data.PropertiesStamp, error) { return redisService.ReadProperties(identifier) } fun...
package commands import ( "os" "code.cloudfoundry.org/garden" ) type Attach struct { Process string `short:"p" long:"pid" description:"process id to connect to" required:"true"` } func (command *Attach) Execute(maybeHandle []string) error { handle := handle(maybeHandle) container, err := globalClient().Lookup(...
package main import ( _ "github.com/go-sql-driver/mysql" _ "github.com/lib/pq" "log" "github.com/jinzhu/gorm" "fmt" ) type Place struct { gorm.Model Name string Town Town // `gorm:"ForeignKey:TownID"` TownID int //Place belongs to Town } type Town struct { gorm.M...