text
stringlengths
11
4.05M
package cmd import ( "encoding/json" "io" "net/http" "strings" "github.com/textileio/go-textile/pb" "github.com/textileio/go-textile/util" ) func ObserveCommand(threadID string, types []string) error { updates, err := Observe(threadID, types) if err != nil { return err } for { select { case update, ...
package dto import ( "bytes" ) //From: http://golang.org/pkg/sort/#example_ type ByTime []Dto func (this ByTime) Len() int { return len(this) } func (this ByTime) Swap(i, j int) { this[i], this[j] = this[j], this[i] } func (this ByTime) Less(i, j int) bool { a, okA := (this[i]).(*Element) b, okB := (this[j])...
package types // PacketMiddlewareFunc is a function which receives a PacketHandlerFunc and returns another PacketHandlerFunc. type PacketMiddlewareFunc func(PacketHandlerFunc) PacketHandlerFunc // packetMiddleware interface is anything which implements a PacketMiddlewareFunc named Middleware. type packetMiddleware in...
package main import ( "flag" "github.com/yydzero/mnt/libpq" "log" "net" "strconv" "sync" "io" ) var port string var count int func main() { log.SetFlags(log.Ltime | log.Lshortfile) flag.StringVar(&port, "p", "5432", "port to listen on") flag.IntVar(&count, "c", 10, "Default port to connect") flag.Parse(...
package logger import ( "bytes" "encoding/binary" "encoding/json" "fmt" "log" "net" ) type TcpLogAdapter struct { } func (adapter TcpLogAdapter) newLoggerInstance() LoggerInterface { tlw := &TcpLogWriter{} tlw.lg = log.New(tlw, "", (log.Ldate | log.Ltime | log.Lmicroseconds)) return tlw } type TcpLogConfig...
package services import ( "KServer/library/kiface/iwebsocket" "KServer/manage" "KServer/proto" "KServer/server/utils/msg" "fmt" ) type WebSocketDiscovery struct { IManage manage.IManage } func NewWebSocketCustomHandle(m manage.IManage) *WebSocketDiscovery { return &WebSocketDiscovery{IManage: m} } func (c *W...
package mongodb import ( "errors" "testing" "go.mongodb.org/mongo-driver/mongo" ) func TestIsDuplicateKeyError(t *testing.T) { testCases := []struct { name string err error isDuplicateKeyError bool }{ { name: "is not write exception", err: ...
/* You and your sister have to share a large, circular cookie. The cookie is quite stale, so you must break it by striking it with a hammer. When struck at point p, the cookie will break along the shortest chord containing p. You follow the usual strategy of one person breaking the cookie into two parts and the other ...
package providers type JsonRPCReq struct { ID int `json:"id"` Version string `json:"jsonrpc"` Method string `json:"method"` Params interface{} `json:"params"` } type ProviderInterface interface { SendRequest(method string, params interface{}) ([]byte, error) }
package tool import ( "fmt" "strconv" ) func ToString(_v interface{}) string { return fmt.Sprintf("%v", _v) } func StringToInt64(_v string) int64 { n, _ := strconv.ParseInt(_v, 10, 64) return n } func StringToUint64(_v string) uint64 { n, _ := strconv.ParseUint(_v, 10, 64) return n } func StringToInt(_v str...
package main type PluginInterface interface { Create(cmd Command) error Update(cmd Command) error Delete(cmd Command) error IsValid(cmd Command) bool GetType() string } type Command struct { Plugin string Action string Args map[string]interface{} }
// Copyright 2020 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 impl2 import "github.com/sko00o/leetcode-adventure/queue-stack/stack" /* ○ 用栈模拟队列 § 需要两个栈,分别记为 s1 和 s2,入队操作时,把元素压入 s1; 出队操作,先检查 s2 是否为空,如果不为空,直接从 s2 出栈, 如果为空,把 s1 中所有元素依次出栈并压入 s2 再从 s2 出栈。 出栈的时间复杂度是 O(1) 到 O(n)。 */ // Stack is a LIFO Data Structure. type Stack struct { stack.SliceStack } // MyQue...
package main /* * @lc app=leetcode id=85 lang=golang * * [85] Maximal Rectangle */ func maximalRectangle(matrix [][]byte) int { if len(matrix) == 0 || len(matrix[0]) == 0 { return 0 } res := 0 heights := make([]int, len(matrix[0])) for i := 0; i < len(matrix); i++ { // update heights for ...
package conf import ( "os" "os/user" ) var CommonConf struct { Hostname string Username string PrjName string IsDev bool Idc string TmpRoot string ApiPidFile string } func initCommonConf() { CommonConf.Hostname, _ = os.Hostname() curUser, _ := user.Current() CommonConf.Username = curUser.Usern...
package walkngo import ( "bytes" "fmt" "go/ast" "go/importer" "go/parser" "go/token" "go/types" "io" "strings" "sort" "github.com/raff/walkngo/printer" ) // GoWalker is the context for the AST visitor type GoWalker struct { p printer.Printer parent ast.Node parentExpr ast.Expr flush ...
package main import ( "mysql_byroad/model" "net" "net/http" "net/rpc" log "github.com/Sirupsen/logrus" ) type RPCServer struct { protocol string schema string desc string listener net.Listener } func NewRPCServer(protocol, schema, desc string) *RPCServer { server := RPCServer{ protocol: protocol, ...
package model import ( "fmt" "strconv" "strings" ) // NewSemanticVersion creates a SemanticVersion from a string. func NewSemanticVersion(input string) (version *SemanticVersion, err error) { if !reSemanticVersion.MatchString(input) { return nil, fmt.Errorf("the input '%s' failed to match the semantic version p...
package repositories type UpdateData map[string]interface{}
package types import ( "encoding/binary" servicetypes "github.com/irisnet/irismod/modules/service/types" ) // nolint const ( // module name ModuleName = "oracle" // StoreKey is the default store key for oracle StoreKey = ModuleName // RouterKey is the message route for oracle RouterKey = ModuleName // Qu...
package cart // New 创建购物车问题 func New(itemsP []int, pLimit int) *Cart { n := len(itemsP) if n == 0 || pLimit == 0 { panic("error params") } pCap := pLimit * 2 // 初始化状态数组 status := make([][]bool, n) for i := 0; i < n; i++ { status[i] = make([]bool, pCap+1) } return &Cart{itemsP, pLimit, pCap, status} } // ...
package imageutil // #include "c/matchers.c" import "C" // cgo import ( "unsafe" ) // RgbaCheckCrop returns true if an image is a cropped version of another one. // This is image pattern-matching, but only aligns the pattern with the image // in one predetermined position. func RgbaCheckCrop(haystack []byte, hayW...
package kubedatasource import ( "context" "sort" "strings" "time" "github.com/sirupsen/logrus" "github.com/vmware/kube-fluentd-operator/config-reloader/config" kfo "github.com/vmware/kube-fluentd-operator/config-reloader/datasource/kubedatasource/fluentdconfig/apis/logs.vdp.vmware.com/v1beta1" kfoClient "gith...
//go:generate mockgen -destination=./mock/afero_mock.go github.com/spf13/afero Fs,File package afero
package repl import ( "bufio" "compiler/lexer" parser "compiler/parser" "fmt" "io" ) const PROMPT = "<meow>^..^<meow>" //helper function for input and output values func Start(in io.Reader, out io.Writer){ scanner := bufio.NewScanner(in) for{ fmt.Printf(PROMPT) scanned := scanner.Scan() if !scanned{ ...
package main import ( "flag" "fmt" "github.com/oxtoacart/oauther/oauth" "os" ) var ( clientId = flag.String("id", "", "Client ID") clientSecret = flag.String("secret", "", "Client Secret") scope = flag.String("scope", "", "OAuth scope") port = flag.String("port", "9000", "Port for callback ...
package repository_test import ( "goldnoti/repository" "testing" "github.com/stretchr/testify/assert" ) func Test_ToFloat64_Input_Empty_Output_Should_be_Zero(t *testing.T) { input := "" expected := 0.00 actual := repository.ToFloat64(input) assert.Equal(t, expected, actual, "Expecting result should be zero"...
package models import ( "github.com/insisthzr/echo-test/cookbook/twitter/conf" "github.com/insisthzr/echo-test/cookbook/twitter/db" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) // User user type User struct { ID bson.ObjectId `json:"id" bson:"_id,omitempty"` Email string `json:"email" bson:"ema...
package types import ( "fmt" "regexp" "strings" "github.com/docker/docker/api/types" "github.com/docker/go-connections/nat" log "github.com/sirupsen/logrus" ) // FindServiceName gets the a-priori unique name of a service based on mapped volumes func FindServiceName(init string, config types.ContainerJSON) stri...
package main import ( "fmt" ) type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func maxDepth(root *TreeNode) int { if root == nil { return 0 } if root.Left == nil && root.Right == nil { return 1 } var max, max1 int max += maxDepth(root.Left) max1 += maxDepth(root.Right) if max > ...
package terminal import ( "encoding/json" "fmt" ) const ( logFieldDoc = "doc" ) var ( jsonDocumentFields = []string{logFieldMessage, logFieldDoc} ) type jsonDocument struct { message string data interface{} } func (j jsonDocument) Message() (string, error) { data, err := json.MarshalIndent(j.data, "", " ...
package tests import ( "github.com/robfig/revel" "net/url" "regexp" ) type ApplicationTest struct { rev.TestSuite } func (t ApplicationTest) Before() { println("Set up") } func (t ApplicationTest) TestThatIndexPageWorks() { t.Get("/") t.AssertOk() t.AssertContentType("text/html") } func (t ApplicationTest)...
package pasm /* #cgo CFLAGS: -D_UNIX_ #include <stdio.h> #include <stdarg.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include "pasm.h" */ import "C" import ( "fmt" "io/ioutil" "os" "path" "sync" ) const ( OPTION_BINARY = C.OPTION_BINARY OPTION_BINARYBIG = C.OPTION_BINARYBIG OPTIO...
package env import ( "fmt" "go.uber.org/zap" "k8s.io/apimachinery/pkg/api/resource" "knative.dev/eventing-kafka/pkg/common/env" "os" "strconv" "strings" ) // Package Constants const ( // Default Values To Use If Not Available In Env Variables DefaultKafkaOffsetCommitMessageCount = "100" DefaultKafkaOffset...
package main import ( "encoding/json" "fmt" "log" "net/http" "github.com/gorilla/mux" auth "github.com/onelittlenightmusic/opa-entrypoint-authorizer" ) type User struct { Name string Age int } type UserName struct { Name string } type UserAge struct { Age int } type Office struct { Name ...
package client import ( "context" "github.com/IhorBondartsov/csvReader/entity" "github.com/IhorBondartsov/datasaver/web/myproto/pb" "google.golang.org/grpc" ) // ClientForSaver - clent for data saver type ClientForSaver struct { Conn pb.CSVSenderClient } // NewClient create client with connection to server fu...
package domain import ( "testing" "time" "github.com/Tanibox/tania-core/src/tasks/query" "github.com/gofrs/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) type TaskServiceMock struct { mock.Mock } func (m *TaskServiceMock) FindAreaByID(uid uuid.UUID) ServiceResult { args := m...
package text import ( "testing" "time" "github.com/stretchr/testify/assert" ) func TestRemoveExcessiveWhitespace(t *testing.T) { tests := []struct { name string input string want string }{ { name: "nothing to remove", input: "one two three", want: "one two three", }, { name: "whites...
package game_map import ( "fmt" "github.com/faiface/pixel" "github.com/faiface/pixel/pixelgl" "github.com/faiface/pixel/text" "github.com/sirupsen/logrus" "github.com/steelx/go-rpg-cgm/animation" "github.com/steelx/go-rpg-cgm/combat" "github.com/steelx/go-rpg-cgm/gui" "github.com/steelx/go-rpg-cgm/state_machi...
package api import ( "net/http" "encoding/json" "github.com/ONSdigital/dp-map-renderer/analyser" "github.com/ONSdigital/dp-map-renderer/models" "github.com/ONSdigital/go-ns/log" ) func (api *RendererAPI) analyseData(w http.ResponseWriter, r *http.Request) { log.Debug("analyseData", log.Data{"headers": r.Head...
/* * outer: outer product * * input: * vector: a vector of (x, y) points * nelts: the number of points * * output: * matrix: a real matrix, whose values are filled with inter-point * distances * vector: a real vector, whose values are filled with origin-to-point * distances */ package main ...
// @Description jwt中间件 // @Author jiangyang // @Created 2020/11/16 5:12 下午 package middlewares import ( "net/http" "github.com/comeonjy/util/jwt" "github.com/gin-gonic/gin" ) func JwtAuth() func(ctx *gin.Context) { return func(ctx *gin.Context) { token := ctx.GetHeader("Authorization") if len(token...
package lfile import ( "errors" "os" ) var ( LOCK_CONFLICT = errors.New("File already locked") ) type LockType int const ( FLOCK LockType = 0 // Thread-safe if applied to different open() calls; May not allow NFS FCNTL LockType = 1 // Not thread-safe; Allows NFS; Max compatibility ) type LockableFile struct {...
package module import ( "context" "fmt" "path/filepath" "sync" "github.com/moby/buildkit/client" "github.com/openllb/hlb/parser" "github.com/xlab/treeprint" ) // NewTree resolves the import graph and returns a treeprint.Tree that can be // printed to display a visualization of the imports. Imports that transi...
package main import ( "bytes" "testing" "github.com/stretchr/testify/assert" ) func TestReadWriteStartAbort(t *testing.T) { content := []byte("WRITE a hello\nREAD a\nSTART\nWRITE a hello-again\nREAD a\nABORT\nREAD a\nQUIT\n") var stdin bytes.Buffer var stdout bytes.Buffer var stderr bytes.Buffer stdin.Write(...
package validate import ( "fmt" "strings" "github.com/kyleconroy/sqlc/internal/sql/ast" "github.com/kyleconroy/sqlc/internal/sql/astutils" "github.com/kyleconroy/sqlc/internal/sql/catalog" "github.com/kyleconroy/sqlc/internal/sql/sqlerr" ) type funcCallVisitor struct { catalog *catalog.Catalog err error ...
package main import ( "fmt" "time" "github.com/google/gxui" "github.com/google/gxui/drivers/gl" "github.com/google/gxui/math" "github.com/google/gxui/samples/flags" "github.com/xinhuang327/algorithms/common" "github.com/xinhuang327/algorithms/sorting" ) var theDriver gxui.Driver var theme gxui.Theme var winW...
package pulsar import ( "context" "time" "github.com/apache/pulsar-client-go/pulsar" "github.com/pkg/errors" "github.com/batchcorp/plumber-schemas/build/go/protos/opts" "github.com/batchcorp/plumber-schemas/build/go/protos/records" "github.com/batchcorp/plumber/util" "github.com/batchcorp/plumber/validate" )...
package main import ( "flag" "math/rand" "os" ) var ( fPath = flag.String("p", "/tmp/test-file", "") fSize = flag.Int64("s", 1024*1024*100, "") ) func main() { flag.Parse() f, err := os.Create(*fPath) if err != nil { panic(err) } // if err := os.Truncate(*fPath, *fSize); err != nil { // panic(err) // ...
package 链表 func deleteNode(node *ListNode) { node.Val = node.Next.Val node.Next = node.Next.Next } /* 题目链接: https://leetcode-cn.com/problems/delete-node-in-a-linked-list/ */
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package cmd import ( "testing" "github.com/Azure/aks-engine/pkg/api" "github.com/pkg/errors" "github.com/spf13/cobra" ) func TestNewScaleCmd(t *testing.T) { command := newScaleCmd() if command.Use != scaleName || c...
package mysql import ( "InkaTry/warehouse-storage-be/internal/pkg/stores" "context" ) const ( listHistoriesByProductIdQuery = ` SELECT type as edit_type, description, updated_at, updated_by FROM histories WHERE product_id = ? LIMIT ?; ` ) func (c *Client) ListHistoriesByProductId(ctx context.Context, p *stor...
package gotest import "github.com/google/btree" type User struct { ID int Name string UpdateID int } type UserByUpdateID User func (a *UserByUpdateID) Less(b btree.Item) bool { return a.UpdateID < b.(*UserByUpdateID).UpdateID } type ByID []User func (a ByID) Len() int { return len(a) } func...
package main import ( "TR" "adutils" "log" "time" ) func InitData() []TR.TrPerTeam { teams := TR.Init() var tms = []TR.TrPerTeam{} for _, tm := range teams { tm.InitTRInfo(1) //do not display the zero tr team if tm.TtlTrNr != 0 { tms = append(tms, tm) } } return tms } func ...
package main // --------------------------------------------------------- // EXERCISE: Refactor Feet to Meter // // Define your own Feet and Meters types. // // Follow the steps inside the code. // --------------------------------------------------------- func main() { // ---------------------------- // 1. Define...
package blockchain import ( "log" "errors" "github.com/boltdb/bolt" ) // 区块链迭代器结构 type Iterator struct { db *bolt.DB // 数据库 currentHashPointer []byte // 当前Hash指针 } // 获取区块链的迭代器 func (this *BlockChain) GetIterator() *Iterator { return &Iterator{this.db, this.tail} } /* 迭代器的迭代函数: 1. 从最后一个区块开始迭代; 2. 每次...
package main func deadfish(data string) []int { var output []int = nil val := 0 for _, i := range data { switch i { case 105: val++ case 100: val-- case 115: val *= val case 111: output = append(output, val) } } return output }
package goprettytable type Table struct { Fields [][]string // Fields of table Delimeter rune // Column and Row Delimeter symbol of table } // Returns New Table Object func NewTable(del rune) (t *Table) { return &Table{Delimeter: del} } // Add Field to Table func (t *Table) AddField(el []str...
// 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 httputils type HttpError struct { Status int Message string }
// Package service is used to analyze service json files from an installation that failing to bootstrap. package service
// 如果用字典树会有很大的内存优化空间,不过go里实现字典树太麻烦了 type WordFilter struct { pre map[string][]int suf map[string][]int } func Constructor(words []string) WordFilter { w := WordFilter{ make(map[string][]int), make(map[string][]int), } for i, v := range words { tmp := "" w.pre[tmp] = append(w.pre[tmp], i) for _, r := range...
package tsdb import ( "fmt" "testing" "time" ) var ( chain = Chain{ Path: "../test-files/loadFromStorage_testdata/test1.json", LengthElements: 0, Chain: []Block{}, Size: 0, } ) func TestInit(t *testing.T) { blocks := chain.Init() if len(blocks.Chain) == 0 { t.Errorf("tsd...
package helper import ( "encoding/csv" "io" "os" "server/libs/log" "strings" "github.com/bitly/go-simplejson" ) type header struct { name string index int } const ( OP_ADD = iota + 1 OP_SUB OP_MUL OP_DIV OP_SET ) type PropOp struct { Prop string Option int Value string } type PropInfo struct {...
package parser import ( "testing" "github.com/open-policy-agent/opa/ast" "github.com/stretchr/testify/assert" ) func TestArray(t *testing.T) { var _ Value = Array{} t.Run("Clone", func(t *testing.T) { a1 := Array{Number("1"), Number("2"), Number("3")} a2 := a1.Clone() assert.Equal(t, a1, a2) }) t.Run("R...
// Copyright 2020 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable ...
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
package main import "fmt" type Greeter struct { name string } func (g Greeter) Talk() { fmt.Printf("Hello, %s\n", g.name) } func (g *Greeter) Talk2() { fmt.Printf("Hello, %s!\n", g.name) } // END OMIT func main() { var talker = Greeter{"wozozo"} var talkerPtr = &Greeter{"wozozozo"} talker.Talk() ...
// 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 edf /************** * EDF STRUCT * **************/ // Edf is the definition of the EDF structure to be used by this library. type Edf struct { // The variable to hold the EDF's header information. Header map[string]string // The records will be stored in its raw form, each one of them stored in // an a...
package cmd import ( "github.com/spf13/cobra" "github.com/instructure-bridge/muss/config" "github.com/instructure-bridge/muss/proc" ) func newDcCommand(cfg *config.ProjectConfig) *cobra.Command { var cmd = &cobra.Command{ Use: "dc", Short: "Call aribtrary docker-compose commands", Long: `Shortcut for cal...
package win import ( "syscall" "unsafe" ) var ( // Library libuser32 = syscall.NewLazyDLL("user32.dll") // Functions procReleaseDC = libuser32.NewProc("ReleaseDC") procFillRect = libuser32.NewProc("FillRect") ) func ReleaseDC(hwnd HWND, hDC HDC) bool { ret, _, _ := procReleaseDC.Call( uintptr(hwnd), ui...
package http import ( "errors" "strconv" jwt "github.com/dgrijalva/jwt-go" "github.com/smilga/analyzer/api" ) // Error definitions var ( ErrParsingClaims = errors.New("Error parsing token claims") ) type Claims struct { UserID string jwt.StandardClaims } // JWTAuth uses jwt token for authentification type J...
package main import ( "fmt" "github.com/gorilla/websocket" "net/http" ) var upgrader = websocket.Upgrader{ //websocket接口 CheckOrigin: func(r *http.Request) bool { return true }, } type Message struct { //json对象,首字母大写 Name string Localx float64 Localy float64 } var message = make(chan Message) ...
package dao import ( "webapp/entities" ) // DAO interface for Language type LanguageDAO interface { FindAll() []entities.Language Find(code string) *entities.Language Exists(code string) bool Delete(code string) bool Create(language entities.Language) bool Update(language entities.Language) bool }
package proc import ( "defs" "fdops" ) // XXX add all syscalls so that we easily can do syscall interposition. currently no use. type Syscall_i interface { Syscall(p *Proc_t, tid defs.Tid_t, tf *[defs.TFSIZE]uintptr) int Sys_close(proc *Proc_t, fdn int) int Sys_exit(Proc *Proc_t, tid defs.Tid_t, status int) } ...
/* * Copyright 2018- The Pixie 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 gate type Options struct { ID int64 LogLevel string LogPrefix string TCPAddr string MaxConnNum int }
package routes import ( "github.com/labstack/echo" // HOFSTADTER_START import // HOFSTADTER_END import // custom imports ) /* API: server Name: hello-path Route: hello Method: get Path: routes Parent: server */ // HOFSTADTER_START start // HOFSTADTER_END start // HOFSTADTER_START const // HOFS...
// Copyright 2019-2023 The sakuracloud_exporter 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 appl...
package auth import ( "fmt" "log" "net/url" "strconv" "strings" "time" datastruct "BearApp/common/data_struct" "BearApp/common/helper" constant "BearApp/constant" "BearApp/model" "github.com/go-redis/redis" ) // DecryptSession session解密 func DecryptSession(session string) (authData datastruct.SessionData,...
package jarviscore import ( "net/http" ) // InitPprof - init pprof func InitPprof(cfg *Config) error { // if cfg.Pprof.GoRoutineURL != "" { // mux := http.NewServeMux() // mux.HandleFunc("/go", func(w http.ResponseWriter, r *http.Request) { // num := strconv.FormatInt(int64(runtime.NumGoroutine()), 10) //...
package server import ( "net/http" "github.com/ItsJimi/casa/logger" "github.com/labstack/echo" ) // hasPermission func hasPermission(next echo.HandlerFunc, permissionType string, read, write, manage, admin bool) echo.HandlerFunc { return func(c echo.Context) error { reqUser := c.Get("user").(User) row := DB...
package validation import ( "k8s.io/apimachinery/pkg/util/validation/field" "github.com/openshift/installer/pkg/types/nutanix" ) // ValidateMachinePool checks that the specified machine pool is valid. func ValidateMachinePool(p *nutanix.MachinePool, fldPath *field.Path) field.ErrorList { allErrs := field.ErrorLis...
// 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 http import ( "encoding/json" "fmt" "github.com/elves-project/agent/src/g" "github.com/gy-games-libs/seelog" "log" "net/http" _ "net/http/pprof" ) type Dto struct { Msg string `json:"msg"` Data interface{} `json:"data"` } func init() { configPageRoutes() configStatRoutes() configApiRoutes()...
package world /* • name - The name displayed in the browse spell box. • action - Name of a combat action that applies the spell effect to the combat state. • element - Extra data for the element_spell action. Describes the element of the spell. Optional. • mp_cost - How much mana is required to cast the spell. ...
package debugtools import ( "bytes" "fmt" "io" "reflect" "strings" ) // Derived from reflect.DeepEqual // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Deep equality test via reflection // During d...
package ghapp import ( "context" "encoding/json" "fmt" "strings" "testing" "github.com/dollarshaveclub/acyl/pkg/eventlogger" "github.com/google/go-github/github" "github.com/google/uuid" "github.com/dollarshaveclub/acyl/pkg/models" "github.com/dollarshaveclub/acyl/pkg/persistence" "github.com/palantir/...
/* * Tencent is pleased to support the open source community by making Blueking Container Service available. * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except * in compliance with the License. You may obta...
package vugufmt import ( "bytes" "fmt" "io" "io/ioutil" "path/filepath" "strings" "unicode" "github.com/vugu/vugu/internal/htmlx" "github.com/vugu/vugu/internal/htmlx/atom" ) // Formatter allows you to format vugu files. type Formatter struct { // ScriptFormatters maps script blocks to formatting // funct...
//1) Descubra por que não compila //R: Não compila porque o tipo numérico usado é int8, que contempla valores de -128 a 127, e o valor que está sendo armazenado é 150. //2) Erros de compilação nos ajudam a compreender o que precisamos consertar em nosso código. O que o erro ./prog.go:9:14: constant 150 overflows int8...
/* 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 api import ( "bytes" "encoding/json" "net/http" "net/http/httptest" "testing" "github.com/gorilla/mux" ) func TestSanityCheckResponds(t *testing.T) { tests := []toTest{ { // if you leave off the /{userid}, it goes 404 method: "POST", url: "/sanity_check", token: testing_token...
package main import ( "flag" "fmt" "os" "strings" "github.com/gyepisam/fileutils" "github.com/gyepisam/multiflag" "github.com/gyepisam/redux" ) var cmdRedo = &Command{ UsageLine: "redux redo [OPTION]... [TARGET]...", Short: "Builds files atomically.", LinkName: "redo", } func init() { // break loop ...
package main import ( "database/sql" "fmt" _"github.com/go-sql-driver/mysql" ) func main(){ /* production: adapter: mysql database: redmine host: localhost username: redmine password: Netand1410 encoding: utf8 */ db, err := sql.Open("mysql", "redmine:pass@tcp(192.168.0.203:3306)/...
package main import ( "log" "github.com/ChristianSiegert/go-website-quickstart/config" "github.com/ChristianSiegert/go-packages/webapps" flags "github.com/jessevdk/go-flags" ) func init() { // Parse command-line arguments parser := flags.NewParser(config.Options, flags.HelpFlag) if _, err := parser.Parse(); ...
package main import ( "log" "time" "github.com/shanghuiyang/rpi-devices/dev" "github.com/shanghuiyang/rpi-devices/util" "github.com/stianeikeland/go-rpio" ) const ( pin = 17 pinLed = 26 ) func main() { if err := rpio.Open(); err != nil { log.Fatalf("failed to open rpio, error: %v", err) return } de...
package resolver import ( "context" "strconv" "boiler/cmd/server/internal/graphql/entity" lentity "boiler/pkg/entity" "boiler/pkg/errors" "boiler/pkg/service" "boiler/pkg/store" ) // NewUser return a new user resolver func NewUser(srv service.Interface) *User { return &User{ service: srv, } } // User is ...
package main import ( "bufio" "fmt" "log" "net/http" "os" "os/user" "runtime" "strings" "github.com/0xAX/notificator" ) var notify *notificator.Notificator func main() { // Set options for the notifyier notify = notificator.New(notificator.Options{AppName: "GoServerCheck"}) // Default name for the ser...