text
stringlengths
11
4.05M
// chengfa project main.go package main import ( "fmt" ) const PI float32 = 3.1415926 var nCount int func add(x, y int) (sum float32) { sum = float32((x + y)) * PI return } //多值返回函数 func powfun(a, b, c int) (d, e, f int) { d = a * a e = b * b f = c * c return } type book struct { name string author str...
package dbdriver /* sqlite 驱动单元,封装了pgears的数据库中特殊处理部分 */ import( "database/sql" _ "github.com/mattn/go-sqlite3" ) func SqliteConnection(url string) (*sql.DB, error){ conn, err := sql.Open("sqlite3",url) if err != nil { return nil ,err } return conn ,err }
package 单数 func twoSum(n int) []float64 { dices := NewDices() return dices.GetProbabilities(n) } // ------------- Dices -------------- (递归超时,采用计次的递归) type Dices struct { probabilities []float64 combinationsOfDicesSum []int countOfProbabilityCombination int } func NewDices() *Dices { retu...
package service import ( "github.com/taufanmahaputra/forex/pkg/repository" "log" ) type RateService struct { rateRepository repository.RateRepositoryItf } func InitRateService(rateRepository repository.RateRepositoryItf) RateService { return RateService{ rateRepository: rateRepository, } } func (rs RateServi...
// Copyright (c) 2016 Company 0, LLC. // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package sigma import ( "crypto/hmac" "crypto/rand" "crypto/sha256" "crypto/subtle" "errors" "fmt" "hash" "io" "net" "time" "github.com/davecgh/go-xdr/xdr2" "golang.org/...
package kafka import ( "crypto/x509" "encoding/pem" "errors" "io/ioutil" "path/filepath" "time" "github.com/confluentinc/confluent-kafka-go/kafka" ) func CertExpirationTime(path string) (time.Time, error) { pemData, err := ioutil.ReadFile(filepath.Clean(path)) if err != nil { return time.Unix(0, 0), err ...
package system import ( "github.com/javinc/go-space-shooter" "github.com/javinc/go-space-shooter/component" ) // Motion system. type Motion struct{} // NewMotion Motion system constructor. func NewMotion() *Motion { return &Motion{} } // Process Control system implements System interface. func (s *Motion) Proces...
package main import ( "bufio" "os" "strconv" "strings" "fmt" ) func main() { reader := bufio.NewReader(os.Stdin) n_string, _ := Readln(reader) n, err := strconv.Atoi(n_string) if err != nil { panic(err) } clouds_string, _ := Readln(reader) clouds,err := Slice_Atoi(strings.Split(clouds_string," ")) if e...
package httpx_ext import ( "github.com/tal-tech/go-zero/core/logx" "github.com/tal-tech/go-zero/rest/httpx" "net/http" ) const ( ContentTypeHtml = "text/html" ContentTypePng = "image/png" ContentTypeJPEG = "image/jpeg" ContentTypeGif = "image/gif" ContentTypeIcon = "image/x-icon" ContentTypeCss = "text/cs...
/* Copyright (c) 2017 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, distribute, s...
package pie // Filter will return a new slice containing only the elements that return // true from the condition. The returned slice may contain zero elements (nil). // // FilterNot works in the opposite way of Filter. func Filter[T any](ss []T, condition func(T) bool) (ss2 []T) { for _, s := range ss { if conditi...
package base import ( "testing" "github.com/stretchr/testify/assert" ) func TestPacketType(t *testing.T) { at := assert.New(t) tests := []struct { b byte frameType FrameType typ PacketType strbyte byte binbyte byte str string }{ {0, FrameBinary, OPEN, '0', 0, "open"}, {1,...
package day9 func GetFactorial(num int) int { if num == 1 { return num } else { return num * GetFactorial(num-1) } }
/* * Copyright (c) 2014-2015, Yawning Angel <yawning at torproject dot org> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyr...
package transportador import ( "context" "database/sql" "errors" "github.com/go-kit/kit/log" ) var RepoErr = errors.New("Unable to handle Repo Request") type repo struct { db *sql.DB logger log.Logger } func NewRepo(db *sql.DB, logger log.Logger) Repository { return &repo{ db: db, logger: log.Wi...
package main import ( "regexp" "github.com/jessevdk/go-flags" ) type programArgs struct { Date string `short:"d" long:"date" description:"Date of your travel"` Number string `short:"n" long:"number" description:"Flight/Train number"` List bool `short:"l" long:"list" description:"List all watching records"...
package driver import ( "context" "crypto/tls" vmnet "github.com/vlorc/lua-vm/net" "golang.org/x/net/proxy" "net" "net/url" "reflect" "strings" ) type sock5Driver struct { vmnet.NetDriver dialer Dialer } type Dialer interface { DialContext(ctx context.Context, network, address string) (net.Conn, error) D...
/* * Print the list of all regions available in the SBS service. */ package main import ( "flag" "os" "strings" "github.com/grrtrr/clcv2/clcv2cli" "github.com/grrtrr/exit" "github.com/olekukonko/tablewriter" ) func main() { flag.Parse() client, err := clcv2cli.NewCLIClient() if err != nil { exit.Fatal(...
package jarvisbase import ( "context" "fmt" "sync" "testing" "time" "go.uber.org/zap" ) type l2taskMgr struct { sync.RWMutex finishTask int sendTask int totalTask int mapIndex map[int]int cancel context.CancelFunc } func (mgr *l2taskMgr) getOutputString() string { return fmt.Sprintf("l2taskMgr f...
package dependent import ( "github.com/catmorte/go-inversion_of_control/example/pkg/example/independent" ) type Obj struct { IndependentObj *independent.Obj } func NewDependentObj(independentDep *independent.Obj) *Obj { return &Obj{independentDep} }
package service import ( "fmt" "testing" //"zhiyuan/device_server/raying_api/internal/service" ) func TestFeatureGateOverride(t *testing.T) { //hc := service.Httpclient{} username := "test" password := "qwerty123" method := "GET" url := "/api/cgi-bin/subscribe/picture" realm := "Login to 8L94R080029" nonce ...
package store import ( "testing" "time" ) func TestStore(t *testing.T) { st := New(StoreNoExpiration, 0) if st == nil { t.Error("Fail to create store") } x, ok := st.Get("a", false) if ok { t.Error("got value while key is not exists:", x) } st.Lock() st.Set("a", 1, StoreNoExpiration) x, ok = st.Get("...
package main import ( "fmt" "sort" ) type people []string func (p people) Len() int { return len(p) } func (p people) Less(i, j int) bool { return p[i] < p[j] } func (p people) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func main() { studyGroup := people{"Zeno", "Ali", "Sancho", "Messi", "Bale", "Ronaldo"} ...
package graphkb import "github.com/clems4ever/go-graphkb/internal/client" // Transaction represent a graph transaction type Transaction = client.Transaction
package mt type NodeMeta struct { //mt:len32 Fields []NodeMetaField Inv Inv } type NodeMetaField struct { Field Private bool } func (nm *NodeMeta) Field(name string) *NodeMetaField { if nm == nil { return nil } for i, f := range nm.Fields { if f.Name == name { return &nm.Fields[i] } } return ni...
package report import ( "log" "os" "testing" "text/template" "time" ) var pass = 1 var fail = 0 var skip = -1 type ReportRequest interface { ReqestDetail() map[string]string GetModuleName() string ResponseDetail() map[string]string } var HTTPRequest ReportRequest const storeObject = "automation/api/results...
package main import "oop/employee" func main() { //e := employee.Employee{ // FirstName: "anziguoer", // LastName: "杨玉龙", // TotalLeavers: 30, // LeaversTaken: 20, //} // //e.LeavesRemaining() // 定义一个0值的结构体 e := employee.New("Sam", "Adolf", 30, 20) e.LeavesRemaining() }
package controllers // import ( // "net/http" // "github.com/messagedb/messagedb/services/httpd/presenters" // "github.com/messagedb/messagedb/meta/bindings" // "github.com/messagedb/messagedb/meta/models" // "github.com/gin-gonic/gin" // ) // type TeamController struct { // Engine *gin.Engine // } // func n...
package database import ( "log" "sync" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/sqlite" ) var instancesDB *gorm.DB var once sync.Once type DB struct { gormDb *gorm.DB sqlitePath string } func (d *DB) SetPath(sqlitePath string) { d.sqlitePath = sqlitePath } func (d *DB) GetPath() stri...
package handlers import ( "bytes" "encoding/json" "io" "net/http" "strconv" "testing" "github.com/stretchr/testify/require" "github.com/root-gg/plik/server/common" "github.com/root-gg/plik/server/context" ) func createAdminUser(t *testing.T, ctx *context.Context) (user *common.User) { user = common.NewUse...
package config import ( "path/filepath" "github.com/mitchellh/go-homedir" ) var ( TiDiffPath string TiDiffHistoryPath string TiDiffConfigPath string ) func init() { home, err := homedir.Dir() if err != nil { panic(err) } TiDiffPath = filepath.Join(home, ".config/tidiff") TiDiffConfigPath = filep...
// Copyright 2014 The Cockroach 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 ag...
package build import ( "encoding/json" "fmt" "io" "os" "path/filepath" "strings" "github.com/layer5io/meshery-adapter-library/adapter" "github.com/layer5io/meshkit/utils" "github.com/layer5io/meshkit/utils/manifests" walker "github.com/layer5io/meshkit/utils/walker" smp "github.com/layer5io/service-mesh-pe...
// Copyright 2023 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() { for p := 100; p <= 900; p++ { fmt.Printf("When %v is divided by 16, The modulus is %#v\n", p, p%16) } }
// ˅ package main // ˄ // A node corresponding to "program". type Program struct { // ˅ // ˄ commandList INode // ˅ // ˄ } func NewProgram() *Program { // ˅ return &Program{} // ˄ } func (self *Program) Parse(context *Context) { // ˅ context.SlideToken("program") self.commandList = NewCommandList() ...
/* Create a function that returns all subarrays in an array that sum to a particular value. Return the subarrays in the following order: First by ascending length. Second by comparing element-by-element, starting from the leftmost one. Put the array with the smaller element first in the pairwise comparison. ...
package main import ( "fmt" ) type ListNode struct { Val int Next *ListNode } func main() { head := ListNode{4, &ListNode{5, &ListNode{6, &ListNode{7, &ListNode{8, nil}}}}} re := swapPairs(&head) printList(re) } func printList(l *ListNode) { for l != nil { fmt.Println(l) l = l.Next } } func swapPairs(...
/* Description - Write a program that outputs the first recurring character in a string. Formal Inputs & Outputs - Input Description A string of alphabetical characters. Example: ABCDEBC Output description The first recurring character from the input. From the above example: B Challenge Input IKEUNFUVFV PXLJOUDJVZG...
/* GoLang code created by Jirawat Harnsiriwatanakit https://github.com/kazekim */ package kbank type Config struct { BaseUrl string PartnerID string `json:"partner_id"` PartnerSecret string `json:"partner_secret"` }
package main import "fmt" func main() { x := map[int]string{ 123: "muito legal", 98: "menos legal um pouquinho", 983: "esse é massa", 18: "idade de ir pra festa", } fmt.Println(x) for key, value := range x { fmt.Println(key, value) } delete(x, 123) fmt.Println(x) }
package map_slice_array import ( "fmt" "gengine/builder" "gengine/context" "gengine/engine" "reflect" "testing" "time" ) type SS struct { MI []int MM *[]int } const S_1 = ` rule "slice test" "slice dec" begin a = 1 //calculate SS.MI[1] = 22 + 2 - 5 * 6 / 3 println("SS.MI[1]-----> ",SS.MI[1]) println("SS.MI...
package http import ( "net/http" "strings" ) var allowMethods = "GET, HEAD, OPTIONS" func NewCORSMiddleware() func(h http.Handler) http.Handler { return func(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { hs := w.Header() hs.Set("allow", allowMethods)...
package main import ( "github.com/neil-berg/blockchain/blockchain" commandline "github.com/neil-berg/blockchain/cli" "github.com/neil-berg/blockchain/database" ) func main() { db := database.Open() defer db.Close() chain := blockchain.Init(db) cli := commandline.CLI{Chain: chain} cli.Run() // chain.AddBloc...
package controllers import ( "github.com/astaxie/beego" "github.com/astaxie/beego/orm" "nepliteApi/models" "time" "fmt" "nepliteApi/comm" "github.com/astaxie/beego/logs" ) type GoodsRecordController struct { beego.Controller } func (goodRcd *GoodsRecordController) Get() { result := make(map[string]interface...
package main import "fmt" type Student struct { Name string } func checkType(items ...interface{}) { for i, v := range items { switch v.(type) { case int: fmt.Printf("第%d参数类型是%T,值是%v\n", i, v, v) case bool: fmt.Printf("第%d参数类型是%T,值是%v\n", i, v, v) case float64: fmt.Printf("第%d参数类型是%T,值是%v\n", i, v...
package models import ( "encoding/json" "errors" "fmt" "project/app/admin/models/bo" "project/app/admin/models/cache" "project/app/admin/models/dto" "project/common/global" "project/utils" "strconv" "go.uber.org/zap" ) const ForeNeed string = "menu::userNeed:" var ( MenuIsExistError = errors.New("菜单已存在")...
package queue import ( "github.com/appootb/substratum/queue" ) type EmptyIdempotent struct{} // BeforeProcess is invoked before process message. func (p *EmptyIdempotent) BeforeProcess(_ queue.Message) bool { return true } // AfterProcess is invoked after processing. func (p *EmptyIdempotent) AfterProcess(_ queue...
package keeper import ( "fmt" "testing" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" "github.com/irisnet/irishub/app/v2/coinswap/internal/types" sdk "github.com/irisnet/irishub/types" ) func TestNewQuerier(t *testing.T) { ctx, keeper, _ := createTestInput(t, sdk.Ne...
package schemadance func (p PatchSet) EndVersion() int { max := 0 for _, step := range p.Up { if step.To > max { max = step.To } } return max } func (p PatchSet) StartVersion() int { if len(p.Up) == 0 { return 0 } return p.Up[0].From } func sqlOnly(p []Patch) bool { for _, step := range p { if ste...
package main import "fmt" type Vertex struct { Name string Gender string } type Value struct { Name string Gender *string } type Array struct { Name string Goods []string } func main() { t1() } func t1() { v1 := Vertex{ Name: "1", Gender: "2", } v2 := Vertex{ Name: "1", Gender: "2", } ...
package domain import ( _ "fmt" ) type AbstractPageRequest struct { //Pageable page int `json:"page"` size int `json:"size"` } func NewAbstractPageRequest(page int, size int) *AbstractPageRequest { if page < 0 { return nil } if size < 1 { return nil } return &AbstractPageRequest{page: page, size: siz...
package repository import ( "github.com/asdine/storm" "github.com/cswank/quimby/internal/schema" ) // User does database-y things. type User struct { db *storm.DB } func (u User) GetAll() ([]schema.User, error) { var out []schema.User return out, u.db.All(&out) } func (u User) Get(username string) (schema.User...
/** * Fileserver * Programmieren II * * 8376497, Florian Braun * 2581381, Lena Hoinkis * 9043064, Marco Fuso */ package SessionManager import ( "sync" "time" "flag" ) // SESSION_KEY_LENGTH Length of the SessionKey which gets used after Authentication for access control. const ( SESSION_KEY_LENGTH =...
package api import ( "net/http" "github.com/gorilla/mux" "github.com/pkg/errors" "github.com/rancher/go-rancher/api" ) func (s *Server) ListHost(rw http.ResponseWriter, req *http.Request) error { apiContext := api.GetApiContext(req) hosts, err := s.man.ListHosts() if err != nil { return errors.Wrap(err, "f...
package awskinesis import ( "encoding/json" "errors" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/kinesis" "github.com/aws/aws-sdk-go/service/kinesis/kinesisiface" ...
package domain type UserDomain struct { Id int `db:"ID, primarykey, autoincrement"` Username string }
// ----------------------------------------------------------------------------- // Package containing implementation of configurable sensors // that will collect or generate data and deploy it to server // for further processing. This package is also a main package // since sensors will be able to execute as stand-alo...
package json import ( "encoding/json" ) type ( //RawMessage ... RawMessage = json.RawMessage //Delim ... Delim = json.Delim )
package main import "fmt" func main() { fmt.Println("Welcome to the gofullstack repository.") fmt.Printf("sdfsfs %v, %v\n", 12.5, "this is me") x := fmt.Sprintf("sdfsfsf %v\n", 12.34) fmt.Printf(x) }
package jarviscore import ( "bytes" "context" "crypto/md5" "fmt" "io" "net" "os" "os/exec" "path" "path/filepath" "strings" "time" "go.uber.org/zap" "google.golang.org/grpc/peer" "github.com/golang/protobuf/proto" jarvisbase "github.com/zhs007/jarviscore/base" "github.com/zhs007/jarviscore/basedef"...
package azure import ( "context" "fmt" "sort" "strings" survey "github.com/AlecAivazis/survey/v2" "github.com/AlecAivazis/survey/v2/core" "github.com/Azure/go-autorest/autorest/to" "github.com/pkg/errors" "github.com/openshift/installer/pkg/types/azure" ) const ( defaultRegion string = "eastus" ) // Plat...
package intx import ( "errors" "fmt" "regexp" "strconv" ) var jsonArrayReg = regexp.MustCompile(`\[\s*(\d+),\s*(\d+)\s*\]`) // Range defines a range with integer type Range struct { Start int End int } func (r *Range) MarshalJSON() ([]byte, error) { return []byte(fmt.Sprintf("[%d,%d]", r.Start, r.End)), ni...
package main import ( "fmt" "io" "os" ) func copyFile() { readFile, err := os.Open("./write.txt") defer readFile.Close() if err != nil { fmt.Println(err) return } writerFile, err := os.OpenFile("./read.txt", os.O_WRONLY | os.O_CREATE, 0666) defer writerFile.Close() if err != nil { fmt.Println(err) ...
package orm import ( "github.com/jinzhu/gorm" "xorm.io/xorm" ) type Page struct { PageNo int `json:"page_no"` PageSize int `json:"page_size"` } func (p *Page) ApplyGorm(db *gorm.DB) { if p.PageSize > 100 { p.PageSize = 20 } *db = *db.Offset((p.PageNo - 1) * p.PageSize) *db = *db.Limit(p.PageSize) } func...
// Copyright 2015 Walter Schulze // // 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 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 archiver import ( "errors" "fmt" "io" "log" "os" "sync" "time" "github.com/luci/luci-go/client/internal/common" "github.com/luci/luci-g...
package main import ( "flag" "fmt" "os" "path/filepath" unique "github.com/jasonmccallister/unique/pkg" ) var ( fileArg string columnArg int hasHeaderArg bool countOnlyArg bool ) func main() { if len(os.Args) != 2 { fmt.Printf("usage: %s <filename>\n", filepath.Base(os.Args[0])) os.Exit(1) } ...
// Copyright 2014 David Persson. 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 ( "fmt" "strings" "time" "github.com/kr/beanstalk" ) type Tubes struct { Names []string Conns []beanstalk.Tube All bool // Fla...
package client_test import ( "os" "testing" ) func TestNewUserNoPhoneNumber(test *testing.T) { _, err := satisClient.CreateUser("", "") if err == nil { test.Fatalf("Expecting error not nil but instead is %v", err) } test.Logf("The beautifull error message is %v", err) } func TestNewUserInvalid(test *testing....
package main import "fmt" var dataA = make([]int, 10, 10) var dataB = make([]int, 10, 10) func init() { for i := 0; i < 10; i++ { dataA[i] = i * 10 dataB[i] = i * 20 } } func main() { for i := 0; i < len(dataA); i++ { for j := 0; j < len(dataB); j++ { fmt.Printf("[%d][%d]\n", dataA[i], dataB[j]) } } ...
package tag import ( "net/http" ctl "github.com/go-jar/gohttp/controller" "blog/controller/api" "blog/svc/tag" ) type TagContext struct { *api.ApiContext tagSvc *tag.Svc } func (c *TagContext) BeforeAction() { c.ApiContext.BeforeAction() c.tagSvc = tag.NewSvc(c.TraceId) } type TagController struct { ap...
// Source : https://oj.leetcode.com/problems/letter-combinations-of-a-phone-number/ // Author : Austin Vern Songer // Date : 2016-04-13 /********************************************************************************** * * Given a digit string, return all possible letter combinations that the number could represe...
package dao import ( "log" "time" _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx" ) var ( // dbCon is the connection pool handler dbCon *sqlx.DB ) func init() { var err error // TODO: load DB connection information from .env file dsn := "root:5566@tcp(localhost:3306)/restful"...
// // Copyright (c) 2017 Intel 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...
package gosrc // 报错行号+3 const templateText = `// Generated by github.com/davyxu/tabtoy // DO NOT EDIT!! // Version: {{.Version}} package {{.PackageName}} type {{.CombineStructName}}EnumValue struct { Name string Index int32 } {{range $sn, $objName := $.Types.EnumNames}} type {{$objName}} int32 const ( {{range $fi...
// Copyright (c) 2012-2013 Matt Nunogawa @amattn // This source code is release under the MIT License, http://opensource.org/licenses/MIT package deeperror import ( "fmt" "log" "net/http" "runtime" "strings" ) var gERROR_LOGGING_ENABLED bool func init() { gERROR_LOGGING_ENABLED = false } const ( gDEFAULT_ST...
package session import ( "errors" "time" "github.com/authelia/authelia/v4/internal/authentication" "github.com/authelia/authelia/v4/internal/authorization" ) // NewDefaultUserSession create a default user session. func NewDefaultUserSession() UserSession { return UserSession{ KeepMeLoggedIn: false, Aut...
package collector import ( "encoding/json" "log" "net/url" "strings" ) type mapper func(*page) string func mapDataFormID(p *page) string { psf := postSavedForm{} return psf.get(p) } func mapParamsFormID(p *page) string { v, _ := url.ParseQuery(p.params) if len(v) > 0 { return v["form_id"][0] } else { r...
package main import ( "fmt" "log" "net/http" "os" "strconv" "time" "github.com/hailongz/kk-logic/logic" _ "github.com/hailongz/kk-logic/logic/captcha" _ "github.com/hailongz/kk-logic/logic/http" _ "github.com/hailongz/kk-logic/logic/lib" _ "github.com/hailongz/kk-logic/logic/oss" _ "github.com/hailongz/kk...
package stack_trace import ( "fmt" "github.com/sirupsen/logrus" ) // New returns a new stack_trace instance. // It automatically extracts stack-trace from errors created with "github.com/pkg/errors" func New() LogrusStackHook { return LogrusStackHook{} } // LogrusStackHook is an implementation of logrus.Hook int...
package logging import ( "fmt" "github.com/pkg/errors" "log" "os" "strconv" "strings" "sync/atomic" ) const ( LogDirEnvKey = "SENTINEL_LOG_DIR" LogNamePidEnvKey = "SENTINEL_LOG_USE_PID" // RecordLogFileName represents the default file name of the record log. RecordLogFileName = "sentinel-record.log" ...
package controllers import ( "github.com/canghai908/zbxtable/models" ) //TemplateController a type TemplateController struct { BaseController } //TemplateRes rest var TemplateRes models.TemplateList //URLMapping beego func (c *TemplateController) URLMapping() { c.Mapping("Get", c.GetInfo) c.Mapping("GetALl", c....
package main import ( "database/sql" "fmt" "log" // "os" //"os/user" "time" //_ "github.com/Go-SQL-Driver/MySQL" //_ "github.com/bmizerany/pq" _ "github.com/mattn/go-sqlite3" ) const DB_NAME = "foo_test" const ( //MySQL = iota //Postgres SQLite = 0 ) var engine = map[int]string{ //0: "MySQL", //1: "P...
package main import ( "bufio" "fmt" "os" "regexp" "strconv" "strings" ) const inputPath = "input.txt" type Passport struct { Byr int Iyr int Eyr int Hgt string Hcl string Ecl string Pid string Cid int } func main() { var part2 = 0 input, err := readLines(inputPath) if err != nil { fmt.Println("e...
/* Given a list with number, output the ranges like this: Input: [0, 5, 0] would become [0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0]. This is mapping a range through the array, so we first have to create the range [0, 5], which is [0, 1, 2, 3, 4, 5]. After that, we use the 5 to create the range [5, 0]. Appended at our previous...
package Interfaces type SendMessage interface { SendMessage() bool }
package login import ( _ "pb" "server" "server/libs/log" ) var ( App = &LoginApp{} ) type LoginApp struct { *server.Server } func (l *LoginApp) OnPrepare() bool { log.LogMessage(l.Name, " prepared") return true } func GetAllHandler() map[string]interface{} { return server.GetAllHandler() } func init() { ...
package besttimetobuyandsellstockwithtransactionfee import ( "golang/helper" "testing" ) func Test(t *testing.T) { input := []int{1, 3, 2, 8, 4, 9} helper.AssertInt(maxProfit(input, 2), 8, t) }
package dht import ( "context" "errors" "fmt" "math" "sync" "time" "github.com/libp2p/go-libp2p/core/network" "github.com/libp2p/go-libp2p/core/peer" pstore "github.com/libp2p/go-libp2p/core/peerstore" "github.com/libp2p/go-libp2p/core/routing" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/ote...
//+build dev package main import ( "net/http" "net/http/httputil" "net/url" ) func NewAssetsHandler() http.Handler { url, _ := url.Parse("http://127.0.0.1:3000") return httputil.NewSingleHostReverseProxy(url) }
package core import ( "os" "testing" "github.com/stretchr/testify/require" ) func TestClientPrivate(t *testing.T) { drands, _, dir, _ := BatchNewDrand(5, false) defer CloseAllDrands(drands) defer os.RemoveAll(dir) pub := drands[0].priv.Public client := NewGrpcClientFromCert(drands[0].opts.certmanager) buff...
package timeout import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) func TestWriteHeader(t *testing.T) { code1 := 99 errmsg1 := fmt.Sprintf("invalid http status code: %d", code1) code2 := 1000 errmsg2 := fmt.Sprintf("invalid http status code: %d", code2) writer := Writer{} assert.PanicsWithValu...
package binpath // Text is a slice of strings that can be marshaled as a binary path. type Text []string // String returns p marshaled as a string. func (p Text) String() string { buf := make([]byte, p.EncodedLen()) p.MarshalTextBuffered(buf) return string(buf) } // Bytes returns p marshaled as a slice of bytes. ...
/* package core модуль types модуль содержит новые типы и их конструкторы, которые необходимы для удобства в работе */ package game // сделан доступным так как для приведения к json нужно // что бы объекты были открытыми // coordinates координаты type coordinates struct { X int Y int } type direction int const ( ...
package graphql import ( "context" "encoding/json" time "time" graphql "github.com/99designs/gqlgen/graphql" "github.com/99designs/gqlgen/handler" "github.com/Sirupsen/logrus" "github.com/go-chi/chi/middleware" ) func OnErrorLogger(log *logrus.Logger) handler.Option { return handler.ResolverMiddleware(func(c...
package options import ( "testing" ) func TestConvert(t *testing.T) { name := "StructName" customNameOpts := NewOptions().SetStructName(name) if customNameOpts.StructName() != name { t.Fatalf("failed to set struct name option") } minInt := false minimizeTrueOpts := NewOptions().SetMinimizeIntegerSize(minInt...
package bmxmpp import ( "github.com/alfredyang1986/blackmirror/bmerror" "os" "testing" ) func TestBmXmppConfig_Forward(t *testing.T) { os.Setenv("BM_XMPP_CONF_HOME", "../resource/xmppconfig.json") bxc, err := GetConfigInstance() bmerror.PanicError(err) err = bxc.Forward("test@max.logic", "user forward") bmer...
package main import "fmt" func main() { defer deferredFunction() normalFunction("John Smith") } func deferredFunction() { fmt.Println("This is the deferred function") } func normalFunction(s string) { fmt.Println("Hello", s) }
package model import ( "gorm.io/gorm" ) type Forum struct { gorm.Model ForumId uint64 `gorm:"column:forum_id;type:bigint(20) unsigned;NOT NULL" json:"forum_id"` // 社区id Name string `gorm:"column:name;type:varchar(32);NOT NULL" json:"name"` // 名字 Intro string `gorm:"column:intro;t...