text
stringlengths
11
4.05M
package main import ( "fmt" "io/ioutil" "net/http" "strconv" "time" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { var body []byte bodyStr := "" sleep := 1 if r.Body != nil { body, _ = ioutil.ReadAll(r.Body) if len(body) > 0 { bodyStr = string(body) } ...
package store import ( "encoding/json" "log" "github.com/go-pg/pg" "github.com/google/uuid" "github.com/gracew/widget/graph/model" "github.com/pkg/errors" ) type Store struct { DB *pg.DB } func (s Store) NewAPI(input model.DefineAPIInput) (*model.API, error) { // janky way of converting from DefineAPIInput ...
package utils import ( "github.com/stretchr/testify/assert" "testing" ) func TestGenerateSha256(t *testing.T) { ast := assert.New(t) ast.Equal("2dce505d96a53c5768052ee90f3df2055657518dad489160df9913f66042e160", GenerateSha256("mysecret", "data"), ) }
package pkg import ( "net/http" "path/filepath" "regexp" "github.com/pkg/errors" ) type Headers []string type File struct { RelPath string `yaml:"path"` AbsPath string DirPath string Content string Links Links `yaml:"links"` Headers Headers Status bool Config *FileConfig `yaml:"config"` Stats *Fi...
package main import ( "encoding/json" "fmt" "github.com/liuzl/goutil/rest" ) func main() { jsonStr := `{"n":"13702032331","msg":"hello"}` jsonStr = `{"status":"ok","message":{"key":"20181009063703:4d819b10a0c780eeb2da8d6a2b2c921d","value":"eyJuIjogIjYyODE1MTkxMDM1MTYiLCAibXNnIjogInRoaXMgaXMganVzdCBhIHRlc3QifQ==...
package integration import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "context" "fmt" "github.com/onsi/gomega/gbytes" "github.com/onsi/gomega/gexec" "io" "os/exec" "strings" "testing" "time" ) func TestStore(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Pachyderm Integration Suite"...
package main import ( "encoding/json" "net/http" ) func GetStatusEndpoint(w http.ResponseWriter, r *http.Request) { var status Status status.Msg = "Hello World Frankfurt" status.Version = "1.0.1" json.NewEncoder(w).Encode(status) }
package login import ( "github.com/labstack/echo" "main/config" "main/handlers/awss3" "net/http" ) func LoginPage(c echo.Context) error { return c.Render(http.StatusOK, "login.html", "") } func Login(c echo.Context) error { storageProvider := c.FormValue("storage_provider") ID := c.FormValue("id") SecretKey ...
package executor import ( "github.com/meshplus/bitxhub-core/agency" "github.com/meshplus/bitxhub-kit/types" "github.com/meshplus/bitxhub-model/pb" ) type SerialExecutor struct { normalTxs []*types.Hash interchainCounter map[string][]uint64 applyTxFunc agency.ApplyTxFunc boltContracts map[stri...
package api import "github.com/tedsuo/router" const ( GetContainer = "GetContainer" AllocateContainer = "AllocateContainer" InitializeContainer = "InitializeContainer" RunActions = "RunActions" DeleteContainer = "DeleteContainer" ListContainers = "ListContainers" GetRemai...
package main import ( "fmt" "io/ioutil" "log" "strings" ) func partOne(data []string) int { var two, three int for _, line := range data { counter := make(map[rune]int) for _, char := range line { counter[char]++ } var twoExist, threeExist bool for char := range counter { switch counter[char] {...
package handlers //TODO: implement handlers for your task-related resources here
package main import "fmt" func main() { Go := Course{ Name: "curso desde cero", Price: 30.9, IsFree: false, UserIDs: []uint{10, 14, 17}, Classes: map[uint]string{ 1: "Introduccion", 2: "Estructuras", 3: "Maps", }, } // css := Course{Name: "css desde cero", IsFree: true} // js := Cours...
package main import ( "fmt" "log" "path/filepath" "regexp" "github.com/mrled/caryatid/pkg/caryatid" ) // Test whether a string is a valid URI func testValidUri(uri string) bool { matched, err := regexp.MatchString("^[a-zA-Z0-9]+://", uri) if err != nil { matched = false } return matched } func convertLoc...
package shttp import ( "context" "log" "net/http" "os" "sync/atomic" "unsafe" "github.com/Packet-Clearing-House/DNSAuth/libs/utils" ) type HttpServerConfig struct { Addr string `cfg:"addr; required; netaddr"` Acl []string `cfg:"acl; [\"127.0.0.1\", \"::1\"]"` Password string `cfg:"password; ""...
// This file was generated for SObject AppDefinition, API Version v43.0 at 2018-07-30 03:47:44.624862783 -0400 EDT m=+30.968631246 package sobjects import ( "fmt" "strings" ) type AppDefinition struct { BaseSObject Description string `force:",omitempty"` DeveloperName string `for...
package gitlab_test import ( "bytes" "context" "errors" "fmt" "io/ioutil" "net/http" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/kryabinin/go-gitlab" ) func TestClient_GetUsersByIDs(t *testing.T) { t.Run("positive case", func(t *testing.T) { for _, conc...
package main import ( "fmt" "main/decoder" "main/encoder" "main/projector" "strings" ) type Hub struct { Projectors map[string]*projector.Device Encoders map[string]*encoder.Device Decoders map[string]*decoder.Device } func (h *Hub) Add(device string, name string, vars map[string]string) { device = strings....
package printer import ( "crypto/md5" "encoding/hex" "strings" "github.com/davyxu/tabtoy/v2/i18n" "github.com/davyxu/tabtoy/v2/model" ) const combineFileVersion = 4 type binaryPrinter struct { } func (self *binaryPrinter) Run(g *Globals, outputClass int) *Stream { fileStresam := NewStream() fileStresam.Wri...
package systemd import ( "os" "syscall" "testing" ) func TestListenFds(t *testing.T) { var testcases = []struct { ListenPid string pid int ListenFds string GetflFlags uintptr GetflErr syscall.Errno SetflFlags uintptr SetflErr syscall.Errno NumFds int Err bool }{ {ListenPid: ...
package env func GetAppName() string { return appname } func GetNodeId() string { return nodeid }
package core type NodeSummary struct { Id string `json:"id"` Name string `json:"name"` Status string `json:"status"` Datacenter string `json:"datacenter"` NodeClass string `json:"node_class"` Version string `json:"version"` Drain bool ...
/* ** description(""). ** copyright('open-im,www.open-im.io'). ** author("fg,Gordon@tuoyun.net"). ** time(2021/5/27 10:31). */ package http import ( "bytes" "encoding/json" "io/ioutil" "net/http" "time" ) func Get(url string) (response []byte, err error) { client := http.Client{Timeout: 5 * time.Second} resp,...
package http import ( "github.com/kataras/iris/v12" "report-api/api" ) func LoadRouter(app *iris.Application) { test(app) } func test(app *iris.Application) { app.Get("/", api.HelloWorld) }
// Copyright 2020 Kuei-chun Chen. All rights reserved. package mdb import ( "encoding/json" "fmt" "log" "net/http" "os" "path/filepath" "sort" "time" "github.com/simagix/gox" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" ) // WiredTigerCache stores wiredTiger cache structure type...
// Copyright (c) 2023 Target Brands, Inc. All rights reserved. // // Use of this source code is governed by the LICENSE file in this repository. package vela import ( "encoding/json" "fmt" "net/http" "net/http/httptest" "reflect" "testing" "github.com/go-vela/server/mock/server" "github.com/go-vela/types/lib...
package criteria import ( "github.com/open-policy-agent/opa/ast" "github.com/pomerium/pomerium/pkg/policy/generator" "github.com/pomerium/pomerium/pkg/policy/parser" ) var corsPreflightBody = ast.Body{ ast.MustParseExpr(`input.http.method == "OPTIONS"`), ast.MustParseExpr(`count(object.get(input.http.headers, "...
package main import ( "fmt" "sync" "sync/atomic" "time" ) const ( ChildCount = 3 ConsumerPeriod = 3 ) func main() { channelNotify() fmt.Println("main process exit!") } // 不同粒度的运行单位之间的调度通常借用系统底层的信号。上下文切换导致粒度对效率的影响是巨大的,用户态的协程是成本较低的。 // 各种语言都可以有,没有的后期自行扩展都行,无非是看runtime(库)的实现程度。golang的协程从语言设计开始作为一类实体,用法以及推广...
package main import ( "encoding/json" "fmt" ) type person struct { Name string `json:"name"` Age int `json:"age"` } func main() { //序列化 p1 := person{ Name: "小明", Age: 18, } b, err := json.Marshal(p1) if err != nil { fmt.Printf("marshal failed,err %v", err) return } fmt.Println(string(b)) fmt...
// Licensed to Elasticsearch B.V. under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Elasticsearch B.V. licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use ...
package main import "fmt" // These values map to rlimit constants defined in linux const ( RlimitCPU = iota // CPU time in sec RlimitFsize // Maximum filesize RlimitData // max data size RlimitStack // max stack size RlimitCore // max core file size Rlimi...
package utils import "fmt" type Printer interface { Printf(format string, args ...interface{}) } type PrinterImpl struct{} func NewPrinter() Printer { return &PrinterImpl{} } func (p *PrinterImpl) Printf(format string, args ...interface{}) { fmt.Printf(format, args...) }
package main import ( "fmt" "github.com/crosbymichael/boss/config" "github.com/hashicorp/consul/api" ) // Consul is a connection to the local consul agent type Consul struct { client *api.Client } // Register sends the provided service registration to the local agent func (c *Consul) Register(id, name, ip strin...
package search import ( logger "github.com/joaosoft/logger" "github.com/joaosoft/manager" ) // SearchOption ... type SearchOption func(search *Search) // Reconfigure ... func (search *Search) Reconfigure(options ...SearchOption) { for _, option := range options { option(search) } } // WithConfiguration ... fu...
package git import ( "testing" ) func TestRemotePush(t *testing.T) { t.Parallel() repo := createBareTestRepo(t) defer cleanupTestRepo(t, repo) localRepo := createTestRepo(t) defer cleanupTestRepo(t, localRepo) remote, err := localRepo.Remotes.Create("test_push", repo.Path()) checkFatal(t, err) defer remote...
package domain_test import ( "encoding/json" "github.com/pivotal-cf-experimental/envoy/domain" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Catalog", func() { var catalog domain.Catalog Context("catalog with all optional fields", func() { var catalog domain.Catalog BeforeEac...
package main import ( "fmt" "io/ioutil" "os" "strings" ) func main() { s, err := ioutil.ReadAll(os.Stdin) if err != nil { panic(err) } msg := string(s) r := strings.NewReplacer( "@", "a", "&", "e", "!", "i", "*", "o", "#", "u", ) fmt.Print(r.Replace(msg)) }
package 二叉树 import "github.com/Lxy417165709/LeetCode-Golang/新刷题/util/math_util" func diameterOfBinaryTree(root *TreeNode) int { _, diameter := getHeightAndDiameterOfBinaryTree(root) return diameter } func getHeightAndDiameterOfBinaryTree(root *TreeNode) (int, int) { if root == nil { return 0, -1 } leftHeight,...
// Generated source file. // Edit files in 'src' folder package maestro // Copyright (c) 2018, Arm Limited and affiliates. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obt...
package testing import ( "fmt" "github.com/queueup-dev/qup-io/v2/writer" "sync" "testing" ) func TestAssert_Eq(t *testing.T) { a := Assert{Input: int64(1)} fmt.Print(a.Eq(int64(1))) } func TestAssert_Same(t *testing.T) { a := Assert{Input: float64(1)} fmt.Print(a.Same(int64(1))) } func TestAssertInstance(...
package main //给定一个 n × n 的二维矩阵 matrix 表示一个图像。请你将图像顺时针旋转 90 度。 // // 你必须在 原地 旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要 使用另一个矩阵来旋转图像。 // // // // 示例 1: // // //输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] //输出:[[7,4,1],[8,5,2],[9,6,3]] // // // 示例 2: // // //输入:matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] //输出:[[15,13,2,5],[14...
package main import ( "encoding/json" "io" "net/http" "video_server/api/defs" ) func SendErrorResponse(writer http.ResponseWriter, errResp defs.ErrorResponse) { writer.WriteHeader(errResp.HttpSC) res, _ := json.Marshal(&errResp.Error) io.WriteString(writer, string(res)) } func SendNormalResponse(writer htt...
//Package message used for control and display error or succes message package message import ( "errors" "fmt" "net/http" "reflect" "strings" ) var messages = map[int]map[string]interface{}{ 0: {"message": "Page not found", "status": http.StatusNotFound}, 1: {"message": "You are not authorize", "status": http....
// 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 main import ( "fmt" . "leetcode" ) func main() { h := NewListNode(1, 2, 3, 4) reorderList(h) fmt.Println(h) } func reorderList(head *ListNode) { arr := make([]*ListNode, 0) for head != nil { n := head.Next //head.Next = nil arr = append(arr, head) head = n } left, right := 0, len(arr)-1...
package db import ( "database/sql" "strconv" "sync" "github.com/textileio/go-textile/pb" "github.com/textileio/go-textile/repo" "github.com/textileio/go-textile/util" ) type CafeClientMessagesDB struct { modelStore } func NewCafeClientMessageStore(db *sql.DB, lock *sync.Mutex) repo.CafeClientMessageStore { ...
package main import ( "fmt" "log" "database/sql" _ "github.com/go-sql-driver/mysql" ) func main() { db, err := sql.Open("mysql", "MeatTaro:9868@/test?charset=utf8") checkErr(err) defer db.Close() //設定資料內容 tableUser := `CREATE TABLE IF NOT EXISTS users( username VARCHAR(64) NULL DEFAULT NULL, passwor...
package repository import ( "encoding/json" "github.com/pkg/errors" "github.com/shharn/blog/db" "github.com/shharn/blog/model" ) type MenuRepository interface { GetAll(interface{}) ([]model.Menu, error) Create(interface{}, model.Menu) (string, error) Update(interface{}, model.Menu) error Get(interface{}, str...
package handlers import ( "github.com/krix38/gophotogallery/web/controller" "github.com/krix38/gophotogallery/model/dao" "github.com/krix38/gophotogallery/model" "github.com/krix38/gophotogallery/properties" "mime/multipart" "io" "regexp" "net/http" "errors" "strconv" "log" ) func AddPhoto(w http.ResponseW...
package externalservices import ( "encoding/json" "fmt" "io/ioutil" "net/http" "poliskarta/api/structs" "sync" ) func CallPoliceScraping(policeEvent *structs.PoliceEvent, credentials structs.Credentials, wg *sync.WaitGroup) { scrapeURL := "https://api.import.io/store/data/3c3e1355-d3c9-4047-bd2e-f86d36af29dc/_...
package command import ( "fmt" "strings" "github.com/emicklei/go-restful" . "data-importer/dbcentral/es" . "data-importer/dbcentral/etcd" . "data-importer/dbcentral/pg" . "data-importer/importer" . "data-importer/office" . "data-importer/tasks" "grm-service/command" "grm-service/dbcentral/es" "grm-servi...
package types import ( "testing" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" ) func TestMax(t *testing.T) { var data = []ArgsType{ StringArgsType("1"), StringArgsType("2"), StringArgsType("3"), StringArgsType("2"), NumArgsType(7.0), } max, _ := GetAggregateFunc("max") result := ...
package train import ( "github.com/y4v8/errors" ) type ParamsTrainWagons struct { From string `url:"from"` To string `url:"to"` Date string `url:"date"` Train string `url:"train"` WagonTypeID string `url:"wagon_type_id"` GetTpl string `url:"get_tpl"` } type ResultTrainWagons ...
// Copyright © 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 agreed ...
/* Copyright (c) 2017-2018 Simon Schmidt Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribu...
package postgres import ( "final-project/model" "fmt" "log" "os" "gorm.io/driver/postgres" "gorm.io/gorm" ) func Connect() *gorm.DB { host := os.Getenv("DB_HOST") port := os.Getenv("DB_PORT") user := os.Getenv("DB_USER") password := os.Getenv("DB_PASSWORD") dbname := os.Getenv("DB_NAME") dsn := fmt.Spri...
package j2rpc import ( "bytes" "errors" "fmt" "io" "mime" "net/http" "reflect" "strings" "unsafe" "github.com/atcharles/gof/v2/json" ) // parsePositionalArguments tries to parse the given args to an array of values with the // given types. It returns the parsed values or an error when the args could not be...
package main import "testing" func TestSum(t *testing.T) { type test struct { data []int result int testname string } tests := []test{ {data: []int{1, 2, 3}, result: 6, testname: "Test 1"}, {data: []int{1, 2}, result: 3, testname: "Test 2"}, {data: []int{1, 3}, result: 3, testname: "Test 3"}, ...
package db import ( "fmt" "strconv" "testing" "time" "github.com/stretchr/testify/assert" "go.mongodb.org/mongo-driver/bson" ) const DB_LINK = "mongodb+srv://ddpoll:ddpoll@test-ycw1l.mongodb.net/test?retryWrites=true&w=majority" const TEST_DB = "test" const TEST_COLLECTION = "testCollection_weifeng" const POLL...
package schemes import "image/color" // AlphaFire is a gradient color scheme from transparent through red // to yellow then white. var AlphaFire []color.Color func init() { AlphaFire = []color.Color{ color.NRGBA{R: 0xff, G: 0xff, B: 0xff, A: 0xff}, color.NRGBA{R: 0xff, G: 0xff, B: 0xfa, A: 0xff}, color.NRGBA{...
package main import "fmt" type person struct { name string } func main() { p := person{name: "Amit"} updateStruct(&p) fmt.Println(p) //var p1 *person = &p //p1 := &p //p1.name = "Raj" } func updateStruct(p1 *person) { p1.name = "raj" }
package yousign import ( "encoding/json" "net/http" "time" ) type ProceduresService struct { client *Client } type Procedure struct { ID *string `json:"id,omitempty"` Name *string `json:"name,omitempty"` Description *string `json:"description,omitem...
package server import ( "testing" "github.com/eclipse/paho.mqtt.golang/packets" "github.com/htdvisser/squatt/session" "github.com/htdvisser/squatt/topic" . "github.com/smartystreets/goconvey/convey" ) func TestSubscription(t *testing.T) { Convey(`Given a Subcription`, t, func() { fooSession := session.NewSes...
package vaku import "fmt" // PathUpdate takes in a path with existing data and new data to write to that path. // It then merges the data at the existing path with the new data, with precedence given // to the new data, and writes the merged data back to Vault func (c *Client) PathUpdate(i *PathInput, d map[string]in...
package cmd import ( "context" "fmt" "io" "io/ioutil" "os" "path/filepath" "regexp" "sync" "time" "github.com/briandowns/spinner" "github.com/giantswarm/microerror" log "github.com/sirupsen/logrus" "github.com/spf13/cobra" "k8s.io/apiserver/pkg/apis/audit" "github.com/corest/k8s-resource-lifecycle/pkg...
package model import ( "database/sql" //"github.com/CourseComment/conf" _ "github.com/go-sql-driver/mysql" //"os" //"time" ) // var ( // db *sql.DB // ) // func init() { // db = conf.DB // } type Course struct { Id idtype Name string Number string Professors []Professor } func GetCourse(key strin...
package main import "fmt" // fibonacci is a function that returns // a function that returns an int. func fibonacci() func() int { var fibonacci int = 0 var fn1 int = 1 var fn2 int = 0 return func() int { if fibonacci == 0 { fibonacci = fn1 return fn2 } else if fibonacci == 1 && fn2 != 0 { fibonacci ...
package config import ( "github.com/Azer0s/quacktors/logging" ) var logger logging.Logger var qpmdPort uint16 func init() { logger = &logging.LogrusLogger{} logger.Init() qpmdPort = 7161 }
package main import ( "fmt" "sort" ) type IntegerSlice []int func (mss IntegerSlice) Len() int { return len(mss) } // HL func (mss IntegerSlice) Less(i, j int) bool { return mss[i] < mss[j] } // HL func (mss IntegerSlice) Swap(i, j int) { mss[i], mss[j] = mss[j], mss[i] } //...
package cache type Cache interface { Remove(key string) Get(key string) (value Value, ok bool) Add(key string, value Value) Keys() []string }
package types import ( "github.com/google/uuid" "github.com/jinzhu/gorm" // HOFSTADTER_START import // HOFSTADTER_END import ) /* Name: AuthBasicUser-db-type-funcs About: */ // HOFSTADTER_START start // HOFSTADTER_END start /* Migrates (or creates) the table for AuthBasicUser */ func MigrateAuthBasicUs...
package muxcodec import ( mc "gx/ipfs/QmYMiyZRYDmhMr2phMc4FGrYbsyzvR751BgeobnWroiq2z/go-multicodec" cbor "gx/ipfs/QmYMiyZRYDmhMr2phMc4FGrYbsyzvR751BgeobnWroiq2z/go-multicodec/cbor" json "gx/ipfs/QmYMiyZRYDmhMr2phMc4FGrYbsyzvR751BgeobnWroiq2z/go-multicodec/json" ) func StandardMux() *Multicodec { return MuxMultico...
// Source : https://oj.leetcode.com/problems/anagrams/ // Author : Austin Vern Songer // Date : 2016-06-04 /********************************************************************************** * * Given an array of strings, group anagrams together. * * For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]...
package helper func SafeMap(m map[string]interface{}, key string, def interface{}) interface{} { var outp interface{} = def switch def.(type) { case string: if val, ok := m[key].(string); ok { outp = val } case int: if val, ok := m[key].(int); ok { outp = val } case int64: if val, ok := m[key].(in...
package business_hours import ( "regexp" "strconv" "strings" ) var ( // 24:00未満である必要がある openTimeValidater = regexp.MustCompile(`^([0-1]?\d|2[0-3]):[0-5]\d$`) // 終了時間は24:00を超える表記を許容する closeTimeValidater = regexp.MustCompile(`^[0-2]?\d:[0-5]\d$`) ) func IsValidBusinessHours(hours []string) bool { var lastClose...
package uinput import ( "fmt" "io" "os" "time" "unsafe" ) // Joystick interface type Joystick interface { BtnDown(btn uint16) error BtnUp(btn uint16) error LeftStickX(x int32) error LeftStickY(y int32) error RightStickX(x int32) error RightStickY(y int32) error io.Closer } type vJoystick struct { devF...
package main import ( "WikiGo/crawler" "fmt" ) func main() { patterns := []string{"/wiki/"} exclude := []string{"Wikipedia:", "Special:", "Help:", "Books:", "File:", ".jpg"} trimMarkers := []string{">Notes<", ">References<", ">See also<", `#External_links">`, `id="catlinks"`} myCrawler := crawler.NewCrawler("ht...
package service import ( "archive/tar" "compress/gzip" "encoding/json" "io" "os" "regexp" "strings" "github.com/pkg/errors" "github.com/sirupsen/logrus" ) // regex matching the path of a service entries file. The captured group is the name of the service. // For example, if the filename is "log-bundle-20210...
package main import ( "fmt" "strconv" "strings" "time" "gitlab.jasondale.me/jdale/govult/pkg/pidcheck" "gitlab.jasondale.me/jdale/govult/pkg/slack" "github.com/davecgh/go-spew/spew" "github.com/spf13/viper" ) // Config is the configuration struct type config struct { ChannelToMessage string ChannelToMonit...
package api import ( "full-stack/utils" "log" "net/http" "github.com/gin-contrib/static" "github.com/gin-gonic/gin" "github.com/gorilla/websocket" ) func SetupApi() *gin.Engine { r := gin.New() r.Use(static.Serve("/", static.LocalFile("./public/", false))) api := r.Group("/api") { api.GET("/test", testH...
package repository import "github.com/akwanmaroso/blogos/api/models" type PostsRepository interface { Save(models.Post) (models.Post, error) FindAll() ([]models.Post, error) FindById(uint64) (models.Post, error) Update(uint64, models.Post) (int64, error) Delete(postId uint64, userId uint32) (int64, error) }
package utils import ( "archive/zip" "encoding/json" "io" "io/ioutil" "net/http" "os" "path/filepath" "strings" "task/defs" "time" ) const ( //BaseYearTime = "2006" BaseDayTime = "2006-01-02" ) //检查文件是否以.log为结尾 func CheckEndWithDotLog(inputStr string) bool { split := strings.Split(inputStr, ".") if spl...
package nfs import ( "context" "fmt" nfsstoragev1alpha1 "github.com/johandry/nfs-operator/api/v1alpha1" "github.com/johandry/nfs-operator/resources" storagev1 "k8s.io/api/storage/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" ctrl "sigs.k8s...
package main import ( "context" "flag" "fmt" "mysql-agent/common/env" "mysql-agent/common/http/server" "mysql-agent/common/logger" "mysql-agent/crontask" "mysql-agent/externalfile" "os" "os/signal" "path/filepath" "strings" "time" ) func main() { var printVersion bool flag.BoolVar(&printVersion, "versi...
package piscine func Index(s string, toFind string) int { input := []rune(s) search := []rune(toFind) input_i := 0 search_i := 0 for index := range search { //to implement range index = index search_i++ } if search_i == 0 { return 0 } for index := range input { //to implement range index = index ...
package controllers import ( "log" "logserver/models" "github.com/astaxie/beego" ) type LogCenterController struct { beego.Controller } func (self *LogCenterController) Get() { log.Println("change page") self.TplName = "logcenter.html" devices, err := models.GetAllDevice() if err != nil { beego.Error(err...
package main type Perk struct { Description string Like int Heart int } type Company struct { Id int Name string Detail string Perks []Perk }
package main import ( "bufio" "bytes" "io" "log" "os" "unicode/utf8" "github.com/jcorbin/anansi/ansi" ) var readBuf bytes.Buffer var outBuf *bufio.Writer func main() { outBuf = bufio.NewWriter(os.Stdout) if err := readMore(); err != nil { log.Fatalln(err) } } func readMore() (err error) { defer func()...
package main import ( "encoding/json" "fmt" "html/template" "log" "net" "net/http" "syscall" "time" "github.com/davecgh/go-spew/spew" "github.com/gorilla/mux" "github.com/zemirco/dcp" ) // host order (usually little endian) -> network order (big endian) func htons(n int) int { return int(int16(byte(n))<<...
package models import ( "marketplace-api/application/base" "github.com/google/uuid" ) type Transaction struct { ID uuid.UUID `json:"_id"` Code string `json:"code"` Status uint8 `json:"status"` SubTotal int ...
package auth import ( "github.com/kataras/golog" "github.com/kataras/iris/v12/sessions/sessiondb/redis" "time" ) type RedisManagerOfAuth struct { Database *redis.Database Addr string Logger *golog.Logger } func Init(logger *golog.Logger) RedisManagerOfAuth { addr := "127.0.0.1:6379" redis := redis.New(...
package main import ( "bufio" "fmt" "log" "net" "time" ) func main() { listener, err := net.Listen("tcp", ":8080") if err != nil { log.Fatalln(err) } for { conn, err := listener.Accept() if err != nil { log.Println(err) } go handleRequest(conn) } } func handleRequest(conn net.Conn) { err :=...
package main import ( "flag" "fmt" "time" "github.com/vharitonsky/iniflags" ) type sl []string type Mongo struct { Addresses []string User string Pass string } type Config struct { Interval time.Duration Mongo Mongo } func (s *sl) String() string { return fmt.Sprintf("%s", *s) } func...
package main import ( "fmt" "os" "io/ioutil" "path/filepath" "github.com/urfave/cli" ) func main() { app := cli.NewApp() app.Name = "clean_up" app.Usage = "deletes garbage files" app.Version = Version app.Author = "onody" app.Email = "onodera212@gmail.com" app.Action = func(c *cli.Context) er...
package main import ( "fmt" "github.com/jackytck/projecteuler/tools" ) func solve(nth int) int { a := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} var i int for v := range tools.Perms(a) { i++ if i == nth { return tools.JoinInts(v) } } return 0 } func main() { fmt.Println(solve(1000000)) } // The millionth...
package controllers import ( "github.com/astaxie/beego" ) type MainController struct { beego.Controller } func (this *MainController) Get() { this.Data["Title"] = "企业信用查询系统" this.Data["URL"] = URL this.Layout = "layouts/nav.html" this.TplName = "index.html" this.Render() }
package repository_test import ( "context" "testing" "time" "github.com/dheerajgopi/todo-api/models" "github.com/stretchr/testify/assert" "github.com/DATA-DOG/go-sqlmock" "github.com/dheerajgopi/todo-api/task/repository" ) func TestGetByID(t *testing.T) { db, mock, err := sqlmock.New() if err != nil { ...
package addtwonumbers import ( "math/big" "strconv" "strings" ) // ListNode represents nonzero integer number type ListNode struct { Val int Next *ListNode } func convertLinkedListToInt(node *ListNode) *big.Int { currNode := node numAsStringSlice := []string{strconv.Itoa(currNode.Val)} for currNode.Next !...
package netstat import ( "fmt" "net" ) // SockAddr represents an ip:port pair type SockAddr struct { IP net.IP Port uint16 } func (s *SockAddr) String() string { return fmt.Sprintf("%v:%d", s.IP, s.Port) } // SockTabEntry type represents each line of the /proc/net/[tcp|udp] type SockTabEntry struct { ino ...
package cloudflare import ( "context" "encoding/json" "fmt" "net/http" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func Test_toUTS46ASCII(t *testing.T) { tests := map[string]struct { domain string expected string }{ "empty stays empty": { domain:...