text
stringlengths
11
4.05M
package builder import ( "errors" "io/ioutil" "os" "sync" "syscall" "time" ) var ( calibrateOnce sync.Once calibrationError error _ctimeResolution time.Duration ) // calibrateCtime will calibrate the resolution of inode change times for // temporary files. It will return the minimum resolution or an erro...
package utils import ( "fmt" "log" "os" "strings" "time" "github.com/netclave/common/networkutils" "github.com/netclave/common/storage" ) const FAILED_EVENTS_TABLE = "failedEvents" const FAILED_IPS_TABLE = "failedIPs" var LAST_TIME_LOGGED = map[string]int64{} type Event struct { ID string IP s...
package middlewares import ( "regexp" "github.com/trustelem/zxcvbn" "github.com/authelia/authelia/v4/internal/configuration/schema" ) // PasswordPolicyProvider represents an implementation of a password policy provider. type PasswordPolicyProvider interface { Check(password string) (err error) } // NewPassword...
package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "testing" ) type JSONResp struct { Token string `json:"token"` Value `json:"value"` } type Value struct { AccessKey string `json:"access_key"` } func TestGet(t *testing.T) { var tests = []struct { key string code int }{ {"1key", 200...
package main import ( "fmt" "github.com/shurcooL/githubv4" ) func (dw *DiscordWebhook) CreateMessage(q githubv4.Int) { commit := fmt.Sprintf("今日のコミット数は%v回です!!", q) switch { case q <= 3: dw.UserName = "中野五月" dw.AvatarURL = "https://cdn-ak.f.st-hatena.com/images/fotolife/m/magazine_pocket/20171213/201712132...
package main import ( "fmt" "time" ) var pc [256]byte var pc1 [256]byte func init() { for i := range pc { pc[i] = pc[i/2] + byte(i&1) pc1[i] = pc1[i/2] + byte(i&1) } } func main() { start1 := time.Now() fmt.Printf("Result : %d\n", popcount(10)) //pcSec := time.Since(start1).Seconds() pcSec := tim...
package main import "bufio" import "fmt" import "os" import "strconv" type test_case struct { n int // number of prisoners m int // number of sweets s int // id of prisoner where distribution begins (0 index) } type input struct { t []test_case } func savePrisonerId(t test_case) int { p := (t.m + t.s - 1) % t....
package main import ( "testing" shared "github.com/corymurphy/adventofcode/shared" ) func Test_Part1(t *testing.T) { expected := 26 input := shared.ReadInput("input_test") actual := part1(input) shared.AssertEqual(t, expected, actual) } // func Test_Part2(t *testing.T) { // expected := 93 // input := shared...
package main import ( "fmt" "log" "net/http" "database/sql" "unicode/utf8" _ "github.com/go-sql-driver/mysql" "my.localhost/funny/gotools/badcharsdb/models" ) const ( PRODMODE = false DIRSEP = "/" DSN = "myhouse:pass_to_myhouse@/myhouse" DSN_INFOSCHEMA = "myhouse:pass_to_my...
/* Introduction Each Unicode codepoint can be represented as a sequence of up to 4 bytes. Because of this, it is possible to interpret some 2, 3, or 4-byte characters as multiple 1-byte characters. (See here for a UTF-8 to bytes converter). Challenge Given a UTF-8 character, output it split into a sequence of 1-byte...
package main import ( "fmt" "sync" "time" ) var wg4 sync.WaitGroup //wait for a collection goroutine to finish func main() { wg4.Add(1) //WaitGroup计数+1, main函数等待最后一位参赛者(goroutine)跑步结束 ch := make(chan int) //创建整型无缓冲通道, 返回T而不是*T go run(ch) //创建goroutine ch <- 1 //往通道发送数据 wg4.Wait() //阻塞, 直到WaitGroup计数=0, 即...
package invoice import ( "fmt" "github.com/imrenagi/go-payment" ) type LineItemError struct { Code int } const ( LineItemErrInvalidQty = iota ) func (l LineItemError) Error() string { switch l.Code { case LineItemErrInvalidQty: return "Invalid minimum quantity of the items" default: return "Unrecognized...
package controllers import ( "github.com/labstack/echo" "net/http" ) func GetHomePageHandler(c echo.Context) error { return c.HTML(http.StatusOK, "<div><h2>Golang Blog</h2></div>") }
package stringutil import ( "fmt" "golang.org/x/exp/maps" ) // unit is a convenient alias for struct{} type unit = struct{} // Set is a set of strings. type Set struct { m map[string]unit } // NewSet returns a new string set containing strs. func NewSet(strs ...string) (set *Set) { set = &Set{ m: make(map[st...
package main import ( "crypto/aes" "crypto/cipher" "crypto/rand" "crypto/rsa" "io" "os" "crypto/sha256" ) func decrypt(file string, priv *rsa.PrivateKey) { inFile, err := os.Open(file) if err != nil { panic(err) } defer inFile.Close() outFile, err := os.OpenFile(file[:len(file)-len(LockedExtension)]...
package main import ( "context" "flag" "fmt" "github.com/go-kit/kit/endpoint" kitlog "github.com/go-kit/kit/log" "github.com/go-kit/kit/sd" consulsd "github.com/go-kit/kit/sd/consul" httptransport "github.com/go-kit/kit/transport/http" "github.com/hashicorp/consul/api" stdopentracing "github.com/opentracing/...
/* Copyright The Helm 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, software di...
package main import ( DBProvider "beaver/db" "beaver/user" "github.com/gin-gonic/gin" "net/http" ) var r *gin.Engine func init() { r = gin.New() r.Use(gin.Logger()) r.Use(gin.Recovery()) db := DBProvider.InitDBConnection() user.UserRouter(r.Group("/user"), db) } func main() { r.LoadHTMLGlob("templates/*...
// Copyright (c) 2012-2014 Jeremy Latt // Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net> // released under the MIT license package irc import ( "bufio" "crypto/sha256" "crypto/tls" "encoding/hex" "errors" "io" "net" "strings" "sync" "time" ) var ( handshakeTimeout, _ = time.ParseDuration("5s"...
package main import "fmt" func fibonacci(index int) { var a uint64 = 0 var b uint64 = 1 for i := 0; i < index; i++ { fmt.Println(a) a = b - a b = a + b } } func main() { fibonacci(100) }
package controllers import ( "github.com/danielkrainas/shrugmud/logging" "github.com/danielkrainas/shrugmud/server" ) type nannyState struct { } type nannyCtrl struct { } func Nanny() server.Ctrl { return &nannyCtrl{} } func (ctrl *nannyCtrl) Do(input string, d *server.Descriptor) error { logging.Trace.Printf(...
package main import ( "flag" "fmt" "io/ioutil" "log" "regexp" "strings" ) func main() { flag.Parse() if len(flag.Args()) != 1 { return } fileContents := MustOpenTextFile(flag.Args()[0]) parser := regexp.MustCompile(`[a-j0-9]`) for _, line := range strings.Split(fileContents, "\n") { if len(line) == ...
package network import ( "context" "errors" "net" "reflect" "testing" "github.com/giantswarm/aws-operator/service/locker" "github.com/giantswarm/microerror" "github.com/giantswarm/micrologger/microloggertest" ) var errArtificial = errors.New("artificial error") func mustParseCIDR(val string) net.IPNet { _,...
/* Euler discovered the remarkable quadratic formula: n^2 + n + 41 It turns out that the formula will produce 40 primes for the consecutive integer values 0 <= n < 39. However, when n=40 40^2 + 40 + 41=40(40+1) + 41 is divisible by 41, and certainly when n=41, 41^2 + 41 + 41 is clearly divisible by 41. The incredib...
package order import ( "fmt" "time" "github.com/tppgit/we_service/log" "github.com/tppgit/we_service/log/field" "strings" "github.com/satori/go.uuid" "github.com/tppgit/we_service/core" "github.com/tppgit/we_service/database" "github.com/tppgit/we_service/dto/worder" ) type commentRepository struct { DB ...
package route import ( "github.com/nokamoto/grpc-proxy/descriptor" "github.com/nokamoto/grpc-proxy/yaml" "testing" ) func TestNewRoutes_ping_method_prefix(t *testing.T) { _, afterEach, err := testRoutes(t, "../testdata/yaml/ping.yaml") defer afterEach() if err != nil { t.Fatal(err) } } func TestNewRoutes_p...
// +build !windows,!linux package main import ( "os" "syscall" "github.com/nsf/termbox-go" ) func handleSpecialKeys(key termbox.Key) { if key == termbox.KeyCtrlZ { process, _ := os.FindProcess(os.Getpid()) termbox.Close() process.Signal(syscall.SIGSTOP) termbox.Init() } } const outputMode = termbox.Ou...
package expvar import ( "strings" "github.com/gofiber/fiber/v2" "github.com/valyala/fasthttp/expvarhandler" ) // New creates a new middleware handler func New() fiber.Handler { // Return new handler return func(c *fiber.Ctx) error { path := c.Path() // We are only interested in /debug/vars routes if len(p...
/* Introduction When building an electronics project, a schematic may call for a resistor of an unusual value (say, 510 ohms). You check your parts bin and find that you have no 510-ohm resistors. But you do have many common values above and below this value. By combining resistors in parallel and series, you should b...
//+build . package shmallocator import ( "os" "syscall" "unsafe" ) type SegmentManager struct { region MappedRegion } func NewSegmentManager(fd int) *SegmentManager { syscall.Mm } func (s *SegmentManager) Allocate(size uintptr) unsafe.Pointer {} func (s *SegmentManager) DeAllocate(ptr unsafe.Pointer) {...
package goproxy import ( "net/http" ) // Plugin gives a way to get a source object for a request type Plugin interface { Module(req *http.Request, prefix string) (Module, error) Leave(source Module) error Close() error String() string }
package common import ( "testing" "time" "github.com/stretchr/testify/require" ) func TestNewUpload(t *testing.T) { upload := NewUpload() require.NotNil(t, upload) require.NotZero(t, upload.ID, "missing upload id") require.NotZero(t, upload.UploadToken, "missing upload token") } func TestUploadNewFile(t *tes...
package network import( "data" "net/http" "fmt" "io/ioutil" "encoding/json" ) /**微信获取openid的链接*/ func getWeiChatCodeUrl(code string)(string){ var url=data.WEI_CHAT_CODE_URL+"?appid="+data.APP_ID+"&secret="+data.APP_SECRET+"&js_code="+code+"&&grant_type=authorization_code" return url } // type UserInfo struct{ ...
package leetcode import ( "reflect" "testing" ) func TestRemoveDuplicates(t *testing.T) { tests := []struct { nums []int results []int }{ { nums: []int{}, results: []int{}, }, { nums: []int{1}, results: []int{1}, }, { nums: []int{1, 1}, results: []int{1}, }, { nu...
package company_repository import ( "github.com/jinzhu/gorm" "gitlab.com/username/online-service-and-customer-care/company" "gitlab.com/username/online-service-and-customer-care/entity" ) // CompanyGormRepo implements company repository interface type CompanyGormRepo struct { conn *gorm.DB } // NewCompanyGormRep...
package goxtremio import ( "os" "testing" ) var c *Client func TestMain(m *testing.M) { var err error c, err = NewClient() if err != nil { panic(err) } os.Exit(m.Run()) }
// Copyright 2013 tsuru 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 queue import ( "github.com/adeven/redismq" "launchpad.net/gocheck" "time" ) type RedismqSuite struct { queue *redismq.Queue consumer *redismq.C...
package main import ( "fmt" "math" ) // 8. 字符串转换整数 (atoi) // 请你来实现一个 atoi 函数,使其能将字符串转换成整数。 // 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。接下来的转化规则如下: // 如果第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字字符组合起来,形成一个有符号整数。 // 假如第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成一个整数。 // 该字符串在有效的整数部分之后也可能会存在多余的字符,那么这些字符可以被忽略,它们对函数不应该造成影响。 // ...
/* Copyright 2021 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, so...
package Problem0024 // ListNode ListNode type ListNode struct { Val int Next *ListNode } func swapPairs(head *ListNode) *ListNode { if head == nil || head.Next == nil { return head } // 让temp指向head.Next节点 temp := head.Next // 让head.Next指向转换好了temp.Next节点 head.Next = swapPairs(temp.Next) // 让temp.Next指向hea...
package main import . "./queue" import . "./message" import "container/heap" import "fmt" func main(){ msg := Message{} msg.CreateMessage("husadhusaid",7) msg2 := Message{} msg3 := Message{} msg4 := Message{} msg2.CreateMessage("yolo", 37000) msg3.CreateMessage("olol", 5) msg4.CreateMe...
/* SPDX-License-Identifier: Apache-2.0 * Copyright (c) 2019-2020 Intel Corporation */ package ngcnef import ( "encoding/json" "io/ioutil" "net/http" "path/filepath" ) func closeReqBody(r *http.Request) { err := r.Body.Close() if err != nil { log.Errf("response body was not closed properly") } } func sendC...
package igo import "testing" func TestMd5(t *testing.T) { if GetMd5String("1234") != "81dc9bdb52d04dc20036dbd8313ed055" { t.Fatal("failed.") } }
package clusteragent import ( "github.com/devopstoday11/tarian/pkg/tarianpb" falcoclient "github.com/falcosecurity/client-go/pkg/client" "google.golang.org/grpc" ) type ClusterAgentConfig struct { ServerAddress string ServerGrpcDialOptions []grpc.DialOption EnableFalcoIntegration bool EnableAddConstr...
package i18n import ( "encoding/json" "fmt" "path" "strings" "golang.org/x/text/language" "golang.org/x/text/message" "golang.org/x/text/message/catalog" "github.com/toolkits/pkg/file" "github.com/toolkits/pkg/runner" ) var ( catalogs = make(map[string]*catalog.Builder) printers = make(map[string]*messag...
//Package main represents the main package for the client package main import ( "bufio" "flag" "fmt" "net" "strings" "github.com/TomOrth/go-chat/lists" "github.com/gizak/termui" ) //Type Client represents the client to connect to the server type Client struct { MsgList *lists.MsgList //list of messages conn...
package main import ( "fmt" "io/ioutil" "os" "strconv" "strings" ) func main() { var part int // part is defined as cmd argument if len(os.Args) > 1 && os.Args[1] == "part2" { part = 2 } else { //run part 1 as default part = 1 } input, _ := ioutil.ReadFile("input.txt") strList := strings.Split(stri...
// // Created by Nick on 18-11-2019 // // Main.go // CSV to VCF converter, my first golang program package main import ( "bufio" "encoding/csv" "fmt" "io" "log" "os" "strings" ) func getVCFDataFrom(name string, mobile *string) string { // Check cases where it might be possible that the mobile number is blank...
package main import "fmt" func exploreBehindK(k int, v []interface{}) interface{} { n := 0 for { a := _getOrNil(v, n) if a == nil { break } n++ } return v[n-k-1] } // simulates a Singly Linked Lists func _getOrNil(v []interface{}, index int) interface{} { if len(v) <= index { return nil } return ...
package main import "github.com/gganley/gomultimod/log" func main() { log.Log("Hello world") }
package Services import ( "github.com/kylesliu/gin-demo/App/Repositories/MySQL" //"github.com/kylesliu/gin-demo/Bootstrap" ) func GetAllArticleGroup() *[]MySQL.ArticleGroup { groups := []MySQL.ArticleGroup{} db.Table("blog_article_group"). Select("" + "blog_article_group.id, " + "blog_article_group.name,"...
package tests import ( "testing" "os" "io" "io/ioutil" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "gopkg.in/mgo.v2" "github.com/manyminds/api2go" "github.com/manyminds/api2go-adapter/gingonic" "gopkg.in/gin-gonic/gin.v1" "themis/schema" "themis/resources" "themis/models" "themis/database" "...
package pkce import "fmt" const ( CodeChallengeMethodPlain = "plain" CodeChallengeMethodS256 = "S256" ) type ( Verifier interface { Verify(challenge, verifier string) bool } plainVerifier struct{} s256Verifier struct{} ) var plain = &plainVerifier{} var s256 = &s256Verifier{} func FindVerifierByMethod(me...
package xolphin import ( "encoding/json" "fmt" "net/url" "strings" ) type DCVRequest struct { Domain string `json:"domain"` DCVType string `json:"dcvType"` ApproverEmail string `json:"approverEmail"` } type CertificateCreationRequest struct { Product int Years ...
package main import ( "fmt" pb "redis/message" "strconv" "time" "golang.org/x/net/context" "google.golang.org/grpc" "redis/test/pool" ) type RedisClient struct { Conn *grpc.ClientConn Client pb.RedisClient } func (rc RedisClient) Close() error { return rc.Conn.Close() } func main() { fmt.Println("Cl...
package orders import ( "fmt" "time" cla "github.com/zond/godip/variants/classical/common" dip "github.com/zond/godip/common" ) func init() { generators = append(generators, func() dip.Order { return &disband{} }) } func Disband(source dip.Province, at time.Time) *disband { return &disband{ targets: []dip.P...
func isStrobogrammatic(num string) bool { mirrors := map[byte]byte{ '0': '0', '1': '1', '6': '9', '8': '8', '9': '6', } st, ed := 0, len(num) - 1 for st <= ed{ mirror, valid := mirrors[num[st]] if !valid || mirror != num[ed]{ return false } st += 1 ed -= 1 } ...
package validation_test import ( "github.com/APTrust/exchange/constants" "github.com/APTrust/exchange/validation" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "path" "strings" "testing" ) func TestNewBagValidationConfig(t *testing.T) { conf := validation.NewBagValidationConfig() ...
package app import ( "github.com/btnguyen2k/prom" "github.com/btnguyen2k/henge" "main/src/gvabe/bo" ) // NewAppDaoMultitenantCosmosdb is helper method to create CosmosDB-implementation (multi-tenant table) of AppDao. func NewAppDaoMultitenantCosmosdb(sqlc *prom.SqlConnect, tableName string) AppDao { spec := &he...
package lv2_rectangular import ( "github.com/stretchr/testify/assert" "testing" ) func Test_solution(t *testing.T) { tcs := []struct { w int h int expectedValue int64 }{ {8, 12, 80}, } for _, tc := range tcs { res := solution(tc.w, tc.h) assert.Equal(t, res, tc.expectedValue...
package main import ( "fmt" "io/ioutil" "log" "math" "sort" "strconv" "strings" ) func main() { f, err := ioutil.ReadFile("day03/input.txt") if err != nil { log.Fatal(err) } s := fmt.Sprintf("%s", f) strs := strings.Split(s, "\n") fmt.Println(PartOne(strs[0], strs[1])) fmt.Println(PartTwo(strs[0], str...
package cmd import ( "bufio" "context" "errors" "fmt" "github.com/kobtea/go-todoist/cmd/util" "github.com/kobtea/go-todoist/todoist" "github.com/spf13/cobra" "os" "strconv" "strings" ) // filterCmd represents the filter command var filterCmd = &cobra.Command{ Use: "filter", Short: "subcommand for filter...
package main import ( "fmt" ) var nextId chan string func init() { nextId = make(chan string) go func() { var counter int64 = 0 for { s := fmt.Sprintf("%x", counter) nextId <- s counter += 1 } }() } func main() { fmt.Println("OpenBrain Version: xxx") pb := peaBrain() fmt.Printf("PeaBrain: %s\n...
package main import ( "reflect" "testing" . "github.com/dave/jennifer/jen" "github.com/karantin2020/csvgen/parser" ) //go:generate ./csvgen -p tests -s tests -f tests/fixture/test.go -o test //go:generate ./csvgen -f tests/fixture func Test_main(t *testing.T) { tests := []struct { name string }{ // TODO: A...
package main import ( "fmt" "strings" "jvmgo_c/ch2/classpath" "jvmgo_c/ch2/cmd" "os" ) func main() { cmd := cmd.ParseCmd() if cmd.VersionFlag { fmt.Println("version 0.0.1") }else if cmd.HelpFlag { fmt.Printf("Usage: %s [-option] class [args...]\n",os.Args[0]) } else{ startJVM(cmd) } } func startJVM(...
package aememcache import ( "bytes" "context" "encoding/gob" "time" "go.mercari.io/datastore/v2" "go.mercari.io/datastore/v2/dsmiddleware/storagecache" "google.golang.org/appengine/v2" "google.golang.org/appengine/v2/memcache" ) var _ storagecache.Storage = &cacheHandler{} var _ datastore.Middleware = &cache...
package controller import ( "fmt" "time" "github.com/therecipe/qt/core" "github.com/therecipe/qt/gui" "github.com/therecipe/qt/internal/examples/showcases/wallet/controller" ) type ProgressBarController struct { core.QObject _ func() `constructor:"init"` _ string `property:"text"` _ fl...
package main import "github.com/chhkay/Answer" func main() { Answer.Run() }
package output import ( "fmt" "log" "sort" "../movi" ) func DumpGroupsAsIPTVSimple(groups map[int]*movi.ChannelGroup, prefix string) []byte{ var keys []int data := []byte("#EXTM3U\n") for k := range groups{ keys = append(keys, k) } sort.Ints(keys) for _, k := range ke...
package main import ( "fmt" pb "github.com/gautamrege/gochat/api" ) func addFakeHandles() { for i := 0; i < 10; i++ { h := pb.Handle{ Name: fmt.Sprintf("test+%d", i), Port: int32(i * 23), Host: "fake IP", } HANDLES.Insert(h) } }
package cmd import ( "errors" "io/ioutil" "os" "path/filepath" "regexp" "testing" "github.com/balaji-dongare/gophercises/CLI/task/dbrepository" "github.com/spf13/cobra" ) // initdb initalize db for test environment func initdb() { dir, _ := os.Getwd() databasepath := filepath.Join(dir, "tasks.db") dbrepos...
/* * Copyright 2017 the original author or 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 applica...
// Application entities. // // @author TSS package domain type Config struct { Timeout int UpdateNotify bool UpdatePeriod int Vault string } type Item struct { Category *ItemCategory Created int64 Notes string Title string Trashed bool Sections []*ItemSection Uid string Url ...
package format import ( "testing" ) func TestHasExporter(t *testing.T) { if !HasExporter("text") { t.Error("Incorrect, the IS text exporter") } if HasExporter("unknown1") { t.Error("Incorrect, the ISN'T unknown1 exporter") } } func TestNewExporter(t *testing.T) { ex := NewExporter("text") if ex == nil { ...
package mounts import ( "bufio" "fmt" "os" "strings" ) const ( procMounts = "/proc/mounts" ) func getMountTable() (*MountTable, error) { file, err := os.Open(procMounts) if err != nil { return nil, err } defer file.Close() scanner := bufio.NewScanner(file) table := &MountTable{} for scanner.Scan() { ...
package consul import ( "fmt" _consul "github.com/hashicorp/consul/api" "github.com/tornadoyi/viking/http" "github.com/tornadoyi/viking/log" "github.com/tornadoyi/viking/task" "net/url" "strings" "sync" "time" ) var ( clients = map[string]*Client{} mutex = sync.RWMutex{} ) func CreateClient(name s...
package modconfig import ( "github.com/foxcpp/maddy/internal/config" "github.com/foxcpp/maddy/internal/module" ) func StorageDirective(m *config.Map, node *config.Node) (interface{}, error) { var backend module.Storage if err := ModuleFromNode(node.Args, node, m.Globals, &backend); err != nil { return nil, err ...
package main //2回以上現れる行を出現回数とともに表示する。 import( "bufio" "fmt" "os" ) func main() { counts:=make(map[string]int) input:=bufio.NewScanner(os.Stdin) for input.Scan(){ counts[input.Text()]++ } for line,n := range counts { if n>1{ fmt.Printf("%d\t%s\n",n,line) } } }
package db import ( "github.com/nektro/mantle/pkg/idata" dbstorage "github.com/nektro/go.dbstorage" etc "github.com/nektro/go.etc" ) const ( cTableSettings = "server_settings" cTableUsers = "users" cTableChannels = "channels" cTableRoles = "roles" cTableChannelPerms = "channel...
// 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...
// Definition of repositories. // // @author TSS package out import ( "github.com/mashmb/1pass/1pass-core/core/domain" ) type ConfigRepo interface { IsAvailable() bool GetDefaultVault() string GetTimeout() int GetUpdateNotification() bool GetUpdatePeriod() int Save(config *domain.Config) } type ItemRepo...
package graph type Filter func(*Node, *Arc, *Node) bool func Any() Filter { return func(from *Node, a *Arc, to *Node) bool { return true } } func HasRelationship(relationship string) Filter { return func(from *Node, a *Arc, to *Node) bool { for _, r := range a.relationships { if r == relationship { ret...
// Package parser provides a way to take a string set of ingredients and turn them into // an array of Ingredient. package parser import ( "github.com/chvck/ingredients-parser/pkg/ingredient" "fmt" "encoding/json" ) // IParser is the interface that wraps the basic Parse method. type IParser interface { isConfigur...
package tool import ( "log" "path/filepath" "github.com/pkg/errors" "github.com/spf13/afero" ) // Config contains configurations to manage development tools. type Config struct { FS afero.Fs WorkingDir string RootDir string ManifestName string BinDirName string Verbose bool Log ...
package myList import ( "container/list" "sync" // "time" ) type MyList struct { lock sync.Mutex l *list.List name string } func NewList(name string) *MyList { return &MyList{ l: list.New(), name: name} } func (l *MyList) Front() interface{} { l.lock.Lock() defer l.lock.Unlock() if l.l.Len() == ...
package db import ( "fmt" "github.com/Maymomo/Switch-Harmony/common" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" "log" ) func DataBaseInit() { config := common.GetConfig().MysqlConfig argsStr := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8&parseTime=true&loc=Local", config.User, config.P...
package mails import ( "fmt" "log" "net/smtp" ) // Setup mail to works func Setup() error { err := loadConfig() if err == nil { log.Println("Mail service set up!") } return err } // SendMessageToContactTeam send a mail message to contact team func SendMessageToContactTeam(msg string) error { msg = fmt.Spri...
package testutils import ( "context" "encoding/hex" "math/rand" "testing" dopts "github.com/libp2p/go-libp2p-kad-dht/opts" routedhost "github.com/libp2p/go-libp2p/p2p/host/routed" datastore "github.com/ipfs/go-datastore" dssync "github.com/ipfs/go-datastore/sync" keystore "github.com/ipfs/go-ipfs-keystore" ...
/* Use var para declarar três variáveis. Elas devem ter package-level scope. Não atribua valores a estas variáveis. Utilize os seguintes identificadores e tipos para estas variáveis: Identificador "x" deverá ter tipo int Identificador "y" deverá ter tipo string Identificador "z" deverá ter tipo bool ...
package api import ( "database/sql" "s3-web-browser/server/go/domain/db" "github.com/gin-gonic/gin" ) func responseError(c *gin.Context, errorcode int, msg string) { c.JSON(errorcode, gin.H{ "result": "error", "message": msg, }) } func getConnTx() (*sql.DB, *sql.Tx, error) { conn, err := db.Connection() ...
package utils import ( "github.com/MShoaei/Pineapple/windows" ) var PwszBuff = make([]rune, 1) var KState = make([]byte, 256) func ToUnicode(key *windows.KBDLLHOOKSTRUCT) string { var ( hkl windows.HKL dwThreadId windows.DWORD dwProcessId windows.DWORD ) hWindowHandle := windows.Get...
package sdk import ( "context" "encoding/json" "fmt" "io" "net/http" "time" rm "github.com/brigadecore/brigade/sdk/v3/internal/restmachinery" "github.com/brigadecore/brigade/sdk/v3/meta" "github.com/brigadecore/brigade/sdk/v3/restmachinery" ) // LogLevel represents the desired granularity of Worker log outp...
package main import ( //"strings" "fmt" ) func main() { var n int fmt.Scan(&n) //var sb strings.Builder var d, k int for i:=0; i<n; i++ { if 1+i*2 <= n { d = 1+i*2 } else { d = n-(1+i*2%n) } k = (n-d)/2 for j:=0; j<k; j++ { ...
package main import "fmt" func main() { a := "abab" b := "abeb" if len(a) == 0 || len(b) == 0 { return } if len(a) != len(b) { fmt.Println("false") } if len(a) == 1 { return false } if len(a) == 2 { if string(a[0]) == string(a[1]) { //fmt.Println("false") return true } else if string(a[...
package main import ( "fmt" "math/rand" "time" ) func main() { array1 := [5]int{1, 2, 3, 4, 5} slice1 := array1[2:4:5] // [start: end : cap] , start是包含的, end是不包含的, fmt.Println("slice is ", slice1) // [3 4] [start .... end - 1] fmt.Println("len is ", len(slice1)) // 2 end - start - 1 fmt.Print...
package main import ( "io/ioutil" "net/http" ) func sendRequest(client *http.Client, addr string) { res, err := client.Get(addr) if err != nil { panic(err) } if res.StatusCode != 200 { panic("request failed") } _, err = ioutil.ReadAll(res.Body) if err != nil { panic(err) } err = res.Body.Close() ...
// Copyright (C) 2019 Cisco Systems 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 agr...
package 路径和问题 /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func hasPathSum(root *TreeNode, sum int) bool { if isNil(root) { return false } nextSearchSum := sum - root.Val if isLeaf(root) { return nextSearchSum == 0 } ...
package ProdService import "strconv" type ProdModel struct { ProdID int `json:"pid"` ProdName string `json:"pName"` } func NewProd(id int, pname string) *ProdModel { return &ProdModel{ id, pname, } } func NewProdList(n int) []*ProdModel { ret := make([]*ProdModel, 0) for i := 0; i < n; i++ { ret = ...
package models import ( "github.com/astaxie/beego/orm" "github.com/astaxie/beego/logs" ) type UserPower struct { UserID string `orm:"pk"` PassWord string //todo 现在没有内加密。明文密码是不被赞许的,现在先偷个懒 PowerLev int PowerInfo string `orm:"size(2048)" ` // json:"power_info" Remark string `orm:"size(64)" json:"remark"...