text
stringlengths
11
4.05M
/* Description A Bank plans to install a machine for cash withdrawal. The machine is able to deliver appropriate @ bills for a requested cash amount. The machine uses exactly N distinct bill denominations, say Dk, k=1,N, and for each denomination Dk the machine has a supply of nk bills. For example, N=3, n1=10, D1=1...
package v2 import "switch-onchain/internal/service" //v2 接口升级版本 type APIV2 struct { SVC *service.Service }
// action.go // author:昌维 [github.com/cw1997] // date:2017-05-09 09:00:57 package web import ( "log" "strconv" "cache" "config" "db" "url" "util" ) func storeUrl(longUrl string, ip string) string { var shortUrl string // 遇到随机数碰撞情况重试 retries, err := strconv.Atoi(config.Get("rand.retires")) if err != nil {...
package shardmaster import "../raft" import "../labrpc" import "sync" import "../labgob" import "log" //import "fmt" const Debug = 0 func DPrintf(format string, a ...interface{}) (n int, err error) { if Debug > 0 { log.Printf(format, a...) } return } func TPrintf(format string, a ...interface{}) (n int, err ...
package main import ( "fmt" "io/ioutil" "net/http" "os" "github.com/gorilla/handlers" "github.com/gorilla/mux" ) func main() { r := mux.NewRouter() r.HandleFunc("/api/place/board-bitmap", bitmapHandler) http.ListenAndServe(":4040", handlers.LoggingHandler(os.Stdout, r)) } func bitmapHandler(w http.Response...
package pydict import ( "fmt" "io/ioutil" "testing" ) var _ = fmt.Println func mustReadFile(p string) string { b, err := ioutil.ReadFile(p) if err != nil { panic(err) } return string(b) } func TestLex(t *testing.T) { expect := []string{ "{", "foo", ":", "bar", ",", "[", "a", ",", "b", ",", "c", "]", "...
// Copyright 2021 Kuei-chun Chen. All rights reserved. package keyhole import ( "github.com/simagix/keyhole/mdb" "go.mongodb.org/mongo-driver/mongo" ) // MonitorWiredTigerCache monitor wiredTiger cache func MonitorWiredTigerCache(version string, client *mongo.Client) { wtc := mdb.NewWiredTigerCache(version) wtc....
package dht type Router struct { local ID k int buckets [BucketSize]Peers } func NewRouter(local ID, k int) (*Router, error) { r := new(Router) r.local = local r.k = k for i := range r.buckets { r.buckets[i] = Peers{} } return r, nil } func (r *Router) bucketIndex(id ID) int { var bi int if r.lo...
package main import ( "github.com/davecgh/go-spew/spew" ) // 108. 将有序数组转换为二叉搜索树 // 将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。 // 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。 // 链接:https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree func main() { spew.Dump(sortedArrayToBST2([]int{-10, -3, 0, 5, 9})) } ...
package agenda import ( errors "convention/agendaerror" "entity" "model" "time" log "util/logger" ) type Username = entity.Username type Auth = entity.Auth type UserInfo = entity.UserInfo type UserInfoPublic = entity.UserInfoPublic type User = entity.User type MeetingInfo = entity.MeetingInfo type Meeting = ent...
package query import ( "github.com/juju/errgo" // "github.com/mezis/klask/index" "strings" ) // A generic query, which can combine $and, $or, field filters, and a $by // clause. They will be run in an unspecified order, except the optional $by clause // which is run last. // Represented by a JSON object. type quer...
package opentrace import ( "net/http" "net/http/httptest" "testing" "errors" "github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go/mocktracer" ) func TestTransport_RoundTripper(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) ...
package commands import ( "flag" "fmt" "os" "os/exec" "path/filepath" "strings" "syscall" ) var UNDAEMONIZE = Undaemonize{ workdir: "/var/uhppoted", logdir: "/var/log/uhppoted", config: "/etc/uhppoted/uhppoted.conf", } type Undaemonize struct { workdir string logdir string config string } func (cmd...
package add import "testing" func TestAdd(t *testing.T) { cases := []struct { I int J int Expect int }{ // tc1 { I: 2, J: 3, Expect: 5, }, // tc2 { I: 3, J: 4, Expect: 7, }, } for _, tc := range cases { actual := Add(tc.I, tc.J) t.Errorf("expect: hoge, actual: %s", "fo...
package main import ( "os" "net" "fmt" "time" "runtime" "bufio" "github.com/puslip41/GoStudy/third" ) const MINUTE_FORMAT = "200601021504" const SECOND_FORMAT = "20060102150405" const UDP_READ_BUFFER_SIZE = 1024*1024*10 const WRITE_BUFFER_SIZE = 1024 func main() { port, savePath := getSyslogReceiverArgs() ...
package zmq4_test import ( zmq "github.com/pebbe/zmq4" "fmt" "time" ) func rep_socket_monitor(addr string) { s, err := zmq.NewSocket(zmq.PAIR) if checkErr(err) { return } defer s.Close() err = s.Connect(addr) if checkErr(err) { return } for { a, b, _, err := s.RecvEvent(0) if checkErr(err) { br...
package lsof import ( "encoding/hex" "fmt" ) func getTCPConnections() { } func hexIPToDecimal(ipHex string) string { a, _ := hex.DecodeString(ipHex) s := fmt.Sprintf("%v.%v.%v.%v", a[3], a[2], a[1], a[0]) return s } func hexPortToDecimal(portHex string) string { a, _ := hex.DecodeString(portHex) r := int(a[0...
package slovnik import "strings" // Language of the input string type Language int const ( // Ru represents Russian language Ru Language = iota // Cz represents Czech language Cz ) // Russian alphabet const rusSymbols = "абвгдеёжзийклмнопрстуфхцчшщьыъэюя" // DetectLanguage used to find out which language is us...
// 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 response import ( "time" "github.com/agusbasari29/Skilltest-RSP-Akselerasi-2-Backend-Agus-Basari/entity" "gorm.io/gorm" ) type ResponseUserData struct { User interface{} `json:"user_data"` Credential interface{} `json:"credential"` } type ResponseUser struct { ID uint `jso...
package main // import ( // "io/fs" // "log" // "os" // ) func main() { // if len(os.Args) <= 1 || os.Args[1] == "" { // log.Fatalln("no given file") // } // var ( // a fs.FileInfo // err error // ) // if a, err = os.Stat(os.Args[1]); err != nil { // log.Fatalln(err) // } // log.Println(a.Name()) ...
package mongodb import ( "context" "encoding/json" "errors" "fmt" "log" "sync" "time" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) // DB struct of monge database type DB struct { client *mongo.Client db *mongo.Database } var ins...
/* The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word va...
/* A version control system(VCS) is a repository of files, often the files for the source code of computer programs, with monitored access. Every change made to the source is tracked, along with who made the change, why they made it, and references to problems fixed, or enhancements introduced, by the change. Version...
package services import ( DB "LivingPointAPI/database/database" ) func mapConvert(m map[string]string) map[string]interface{} { mi := map[string]interface{}{} for k, v := range m { mi[k] = v } return mi } func mapToMap(m map[int64]map[string]string) []*DB.Map { // var out []*DB.Map out := make([]*DB.Map, le...
package znet import ( "bytes" "encoding/binary" "errors" "zinx/src/zinx/utils" "zinx/src/zinx/ziface" ) // 封包 拆包的具体模块 type DataPack struct { } // 封包 拆包 实例的一个初始化方法 func NewDataPack() *DataPack { return &DataPack{} } // 获取包的头的长度的方法 func (pD *DataPack)GetHandLen() uint32{ // DataLen uint32(4字节) // ID uint...
package aggregation import ( "fmt" "github.com/emicklei/go-restful" // . "grm-searcher/dbcentral/pg" . "titan-statistics/types" // "grm-service/dbcentral/pg" // "grm-service/log" "grm-service/util" ) var ( volUnit = map[string]string{"K": "KB", "M": "MB", "G": "GB", "T": "TB"} ) func (svc *AggrSvc) GetAggr(r...
package services import ( "github.com/wbreza/go-store/api/models" ) var cache = make(map[int]*models.Product) // ProductManager provides CRUD access to product entities type ProductManager struct { } // NewProductManager creates a new instance of a product manager func NewProductManager() *ProductManager { return...
package configuration_test import ( "bytes" "crypto/ecdsa" "crypto/rsa" "crypto/tls" "crypto/x509" "encoding/pem" "math" "net/mail" "net/url" "reflect" "regexp" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/authelia/authelia/v4/internal/config...
package BLC import ( "bytes" "crypto/sha256" "fmt" "math/big" ) type ProofOfWork struct { Block *Block //当前要验证的区块 target *big.Int // 大数存储 } func (pow *ProofOfWork) prepareData(nonce int64) []byte { data := bytes.Join([][]byte{pow.Block.PrevBlockHash, pow.Block.HashTransactions(), IntToHex(pow.Block.Tim...
package workers import ( "time" "github.com/spf13/viper" "go.uber.org/zap" "github.com/pushaas/push-agent/push-agent/services" ) type ( StatsWorker interface { DispatchWorker() } statsWorker struct { enabled bool expiration time.Duration interval time.Duration logger *zap....
package rc4 import ( "crypto/cipher" "crypto/rc4" "io" ) const defaultBufferSize = 1024 * 1024 func RC4Stream(src io.Reader, dst io.Writer, key []byte) error { stream, err := rc4.NewCipher(key) if err != nil { return err } if _, err = io.CopyBuffer(dst, cipher.StreamReader{S: stream, R: src}, make([]byte,...
// 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 package rolling import ( "compress/gzip" "io" ) type Compression interface { Com...
/***************************************************************** * Copyright©,2020-2022, email: 279197148@qq.com * Version: 1.0.0 * @Author: yangtxiang * @Date: 2020-08-04 16:55 * Description: *****************************************************************/ package netstream import ( "github.com/go-xe2/x/core/lo...
package cmds import ( "github.com/sirupsen/logrus" "github.com/urfave/cli" "github.com/ayufan/docker-composer/compose" ) var composeAppCommands map[string]string = map[string]string{ "build": "Build or rebuild services", "config": "Validate and view the compose file", "create": "Create services", "down": ...
package general_api import ( "log" "time" "net/url" "strings" "github.com/tmaiaroto/aegis/lambda" ) func logger(inner lambda.RouteHandler, name string) lambda.RouteHandler { return lambda.RouteHandler(func(ctx *lambda.Context, evt *lambda.Event, res *lambda.ProxyResponse, ...
package main import "fmt" func main() { x := [...]int{1, 2, 3, 4, 5} y := x[0:2] z := x[1:4] fmt.Println(len(y), cap(y), len(z), cap(z)) }
package seev import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document03800103 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:seev.038.001.03 Document"` Message *CorporateActionNarrativeV03 `xml:"CorpActnNrrtv"` } func (d *Document0380010...
package main import "strings" func replaceWithUnderscores(text string) string { replacer := strings.NewReplacer(" ", "_", ",", "_", "\t", "_", ",", "_", "/", "_", "\\", "_", ".", "_", "-", "_", ":", "_", "=", "_") return replacer.Replace(text) }
package route import ( "net/http" "path/filepath" "strings" ) type filesSystem struct { fs http.FileSystem } func (fs filesSystem) Open(path string) (http.File, error) { f, err := fs.fs.Open(path) if err != nil { return nil, err } s, err := f.Stat() if err != nil { return nil, err } if s.IsDir() { ...
package config import ( "crud-product/constant" "crud-product/model" "encoding/json" "io/ioutil" ) func GetConfig() (*model.Config, error) { cfg := &model.Config{} jsonFile, err := ioutil.ReadFile(constant.ConfigProjectFilepath) if err != nil { return nil, err } err = json.Unmarshal(jsonFile, &cfg) ret...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-10-14 09:00 # @File : lt_81_Search_in_Rotated_Sorted_Array_II.go # @Description : # @Attention : */ package array /* 判断值是否存在 有序数组在某个下标进行了反转,然后判断是否存在 有序中查找,肯定是二分最快 */ func search(nums []int, target int) bool { if len(nums) == 0 { return false } ha...
package model import ( "math/rand" ) const ( SuitSpade Suit = iota SuitClub SuitDiamond SuitHeart ) const ( JokerNumber Number = 14 InvalidCardNumber Number = -1 ) var ( Suits = []Suit{SuitSpade, SuitClub, SuitDiamond, SuitHeart} Numbers = []Number{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, JokerNu...
package main import ( "strings" ) // Define the top level swagger defintion structs here. // These definitions are good enough for parsing goa generated swaggers but definately // don't reflect the complete swagger spec as of yet. // Doc holds the swagger data structure type Doc struct { SwaggerVersion string...
package main import ( "fmt" "os" "time" "github.com/iovisor/gobpf/elf" ) func main() { module := elf.NewModule("./program.o") err := module.Load(nil) if err != nil { fmt.Fprintf(os.Stderr, "Failed to load program from elf: %v\n", err) os.Exit(1) } defer func() { if err := module.Close(); err != nil { ...
package extractors type VersionExtractor interface { GetVersion() string GetAppName() string }
package _744_Find_Smallest_Letter_Greater_Than_Target import ( "fmt" "testing" ) func TestNextGreatestLetter(t *testing.T) { letters := []byte{'c', 'f', 'j'} target := byte('z') fmt.Println(string(nextGreatestLetter(letters, target))) target = byte('c') fmt.Println(string(nextGreatestLetter(letters, target))) ...
package _14_Longest_Common_Prefix import ( "testing" ) func TestLongestCommonPrefix(t *testing.T) { if ret := longestCommonPrefix([]string{"a", "ab"}); ret != "a" { t.Error("not a with test1.") } }
package mars func runMOV(core *Core, process *process, addrA, addrB int, modifier instructionModifier) { switch modifier { case modifierAB: core.cells[addrB].bField = core.cells[addrA].aField case modifierB: core.cells[addrB].bField = core.cells[addrA].bField case modifierI: core.cells[addrB] = core.cells[ad...
package handler import ( "bytes" "github.com/tealeg/xlsx" "io/ioutil" "net/http" "net/url" "time" "tpay_backend/export" "tpay_backend/merchantapi/internal/common" _func "tpay_backend/merchantapi/internal/handler/func" "tpay_backend/merchantapi/internal/logic/export" "tpay_backend/merchantapi/internal/svc" ...
package frontend import ( "encoding/json" "fmt" "io" "net/http" "github.com/getaceres/payment-demo/persistence" ) func ReadBody(reader io.Reader, result interface{}) error { decoder := json.NewDecoder(reader) if err := decoder.Decode(result); err != nil { return fmt.Errorf("Invalid payload: %s", err.Error()...
package main import ( "flag" "fmt" "io/ioutil" "os" "path/filepath" "time" "gopkg.in/yaml.v2" "github.com/eiannone/keyboard" "tezos-contests.izibi.com/backend/signing" "tezos-contests.izibi.com/tc-node/api" "tezos-contests.izibi.com/tc-node/block_store" "tezos-contests.izibi.com/tc-node/clien...
package config import ( "encoding/json" "fmt" "io/ioutil" ) type Config struct { Web web `json:"web"` Database database `json:"database"` } type web struct { Host string `json:"host"` Port int `json:"port"` } type database struct { Host string `json:"host"` Password string `json:"password"...
package main import ( "fmt" "math/rand" "sort" ) type Hero struct { Name string Age int } type HeroSlice []Hero func (hs HeroSlice) Len() int { return len(hs) } // less方法就是决定你用什么标准进行排序 // 按照年龄进行排序 func (hs HeroSlice) Less(i, j int) bool { return hs[i].Age < hs[j].Age } func (hs HeroSlice) Swap(i, j int) {...
package main import "fmt" var java , python bool func main(){ var temp int var varcheck1 = true varcheck2 := true varcheck3, varcheck4 := 10, "string" fmt.Println(temp, java, python, varcheck1, varcheck2) fmt.Println(varcheck3, varcheck4) }
package action import ( "fmt" "html/template" "regexp" "strings" "github.com/GoAdminGroup/go-admin/context" "github.com/GoAdminGroup/go-admin/modules/config" "github.com/GoAdminGroup/go-admin/modules/constant" "github.com/GoAdminGroup/go-admin/modules/language" "github.com/GoAdminGroup/go-admin/modules/utils...
// Accessing fields of a struct // To access individual fields of a struct you have to use dot (.) operator. // Golang program to show how to // access the fields of struct package main import "fmt" // defining the struct type Car struct { Name, Model, Color string WeightInKg float64 } // Main Function f...
package config import ( "fmt" "log" "os" ) const ( mongoDBURIStr = "mongodb://%s:%s@%s/?authSource=admin&readPreference=primary&ssl=false" ) var ( //MongoDBURI ... MongoDBURI string //RedisURI ... RedisURI string //KafkaHost ... KafkaHost string //EmpAPILogger ... EmpAPILogger *log.Logger ) //Initialize...
// Copyright (c) 2019 Leonardo Faoro. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package security import ( "testing" "github.com/stretchr/testify/assert" ) func TestNewToken(t *testing.T) { assert.Panics(t, func() { NewToken(4, f...
package mocks import ( "strings" "github.com/stretchr/testify/mock" ) type ExecCmd struct { mock.Mock Args []string } func (cmd *ExecCmd) Run() error { args := cmd.Called() return args.Error(0) } func (cmd *ExecCmd) CombinedOutput() ([]byte, error) { args := cmd.Called() return args.Get(0).([]byte), args.E...
package main import ( "flag" "fmt" "time" "github.com/PuerkitoBio/goquery" "github.com/gotokatsuya/incidents/util/slack" ) var ( incidentID int slackURL string cacheIncidentInfoMap map[string]struct{} ) func init() { flag.IntVar(&incidentID, "i", 18022, "incident") flag.StringVar(&slackURL, "u", "", "...
package main import ( "context" "crypto/sha256" "encoding/base64" "encoding/json" "fmt" "io" "log" "net/http" "os" "strconv" "time" "golang.org/x/oauth2" "golang.org/x/oauth2/clientcredentials" ) const ( authServerURL = "http://localhost:9096" ) var ( config = oauth2.Config{ ClientID: "222222",...
package main import "fmt" import "sort" func main() { votes := []int{3, 1, 1, 3, 1} k := 2 //votes := make([]int, len(votes)) //var winners []int count := 0 sort.Ints(votes) if k == 0 { // sort.Sort(votes) if votes[len(votes)-1] == votes[len(votes)-2] { fmt.Println("0") return } } // copy(vo...
package hzutils import "html" // HTMLPre return html of string. // @param shtml // @return string func HTMLPre(shtml string) string { return `<html>` + html.EscapeString(shtml) + `</html>` }
// This package contains tests related to dnf-json and rpmmd package. // +build integration package main import ( "fmt" "io/ioutil" "os" "path" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/osbuild/osbuild-composer/internal/blueprint" "github.com/osbuild/...
package logger import ( "go.uber.org/zap" "go.uber.org/zap/zapcore" "gopkg.in/natefinch/lumberjack.v2" "os" ) type LogConfig struct { Develop bool `json:"develop"` Level string `json:"level"` Structured bool `json:"structured"` Path string `json:"path"` ErrorPath string `json:"errorPath"` MaxFileSize int `...
package entity type Vehicle interface { Cambio() string }
package updatetodb import ( "errorhandlers" "errors" "storage" ) /*StoreUser handles saving the user object to the db */ func UpdateUserNickname(id int, newNickname string) error { var db = storage.GetDb() stmt, err := db.Prepare("UPDATE users " + "SET nickname = ? " + "WHERE id = ?;") if err != nil { err...
// A part of go-tour package main // +build ignore import ( "fmt" ) type Fetcher interface { // Fetch returns the body of URL and a slice of URLs fond on that page. Fetch(url string) (body string, urls []string, err error) } // Crawl uses fetcher to recursively crawl pages starting with url, // to a maximum of ...
package datamodel import ( "github.com/GoAdminGroup/go-admin/context" "github.com/GoAdminGroup/go-admin/modules/db" "github.com/GoAdminGroup/go-admin/plugins/admin/modules/table" "github.com/GoAdminGroup/go-admin/template/types/form" ) // GetAuthorsTable return the model of table author. func GetAuthorsTable(ctx ...
package levenshtein import ( "testing" ) // LevRec method benchmarks. func BenchmarkRecursiveLen5(b *testing.B) { s1 := "about" s2 := "above" for i := 0; i < b.N; i++ { LevRec(s1, s2) } } func BenchmarkRecursiveLen10(b *testing.B) { s1 := "abbanition" s2 := "abaptiston" for i := 0; i < b.N; i++ { LevR...
package build import ( "context" "github.com/werf/logboek" "github.com/werf/logboek/pkg/style" "github.com/werf/logboek/pkg/types" ) type ExportPhase struct { BasePhase ExportPhaseOptions } type ExportPhaseOptions struct { ExportTagFuncList []func(string) string } func NewExportPhase(c *Conveyor, opts Expor...
package log import ( "log" "os" "runtime" ) // now we need log promptly //var logger *zap.SugaredLogger var logger *log.Logger func init() { logger = log.New(os.Stdout, "", log.Lshortfile) } func Info(a ...interface{}) { logger.Println(a...) } func Infof(format string, a ...interface{}) { logger.Printf(forma...
package main import ( "fmt" "os" "github.com/lubovskiy/app" ) func main() { a := app.New() _ = a fmt.Println(os.Getenv("GOPATH")) }
package pool import ( "testing" ) func TestPool_AddingOnBeforeRunningServer(t *testing.T) { t.Run("A simple information", func(t *testing.T) { ch := make(chan struct{ ID string }) p := New(1) xid := add(t, p, func(taskID string) error { ch <- struct{ ID string }{ID: taskID} return nil }) go p.Ser...
package main import ( "github.com/spf13/pflag" "net" "log" "os" "io" ) // your own dns server var ( local = pflag.String("local", ":53", "please input dns server listen addr") remote = pflag.String("remote", "", "please remote dns server addr") ) func init() { pflag.Parse() if *remote == "" { log.Printl...
package apichannels // ChannelError types of errors that can be thrown type ChannelError string func (che ChannelError) Error() string { return string(che) } // ChannelNotFound error for when the channel is not found const ChannelNotFound = ChannelError("Channel not found") // MessageNotFound error for when the ch...
// ˅ package main // ˄ type INumber interface { Generate() // ˅ // ˄ } // ˅ // ˄
package database import ( "database/sql" "fmt" "github.com/go-sql-driver/mysql" ) var DB *sql.DB func Connect() { cfg := mysql.Config{ User: "debian-sys-maint", Passwd: "YZkKRHnDn0I8XsvK", Net: "tcp", DBName: "test", } db, err := sql.Open("mysql", cfg.FormatDSN()) DB = db fmt.Println("Databa...
package main import ( "adutils" "fmt" "html/template" "io/ioutil" "log" "mime" "net/http" ) const ( STATIC_DIR = "../static/" VIEW_DIR = "../view/" ) type home struct { Title string } func ext2Mime(ext string) string { switch ext { case ".css": return "text/css" case ".js": return "text/js" case...
/* A distributed block-chain transactional key-value service Assignment 7 of UBC CS 416 2016 W2 http://www.cs.ubc.ca/~bestchai/teaching/cs416_2016w2/assign7/index.html Created by Harlan Sim and Sean Blair, April 2017 This package represents the kvnode component of the system. The kvnode process command line usage m...
package main import ( "bytes" "io" "io/ioutil" "os" "path/filepath" "reflect" "testing" ) const ( tmpdir = "tmp" ) var ( testWALPath = filepath.Join(tmpdir, "test.log") testDBPath = filepath.Join(tmpdir, "test.db") testTmpPath = filepath.Join(tmpdir, "test.tmp") ) func createTestStorage(t *testing.T) *S...
/* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
package chat // Create creates a chat func (m *Model) Create(id int64) (*Chat, error) { row := m.getInsertBuilder().Columns("id").Values(id).RunWith(m.db).QueryRow() chat, err := scanRow(row) if err != nil { if err.Error() == "UNIQUE constraint failed: chats.id" { return nil, ErrChatAlreadyExist } return ...
package pretty_poly func validateSolveArguments (order int, extreme int, filename string) error { if order <= 0 { return ErrOrderArgumentSize } return nil } func Solve (order int, extreme int, precision int8, filename string) error { err := validateSolveArguments(order, extreme, filename) if (err != n...
// okaq web server // wbegl 2.0 vectors // aq@okaq.com // 2020-03-17 package main import ( "fmt" "math/rand" "net/http" "sync" "sync/atomic" "time" ) const ( INDEX = "mazu.html" THREE = "js/three.min.js" ) var ( R *rand.Rand C uint64 M *sync.Map ) func motd() { fmt.Println("serving now on $PUBLIC_IP:808...
package blob import ( "fmt" "net/http" "github.com/iotaledger/wasp/packages/hashing" "github.com/iotaledger/wasp/packages/webapi/httperrors" "github.com/iotaledger/wasp/packages/webapi/model" "github.com/iotaledger/wasp/packages/webapi/routes" "github.com/iotaledger/wasp/plugins/registry" "github.com/labstack...
package oidc import ( "context" "github.com/brigadecore/brigade/v2/apiserver/internal/api" "github.com/coreos/go-oidc" "github.com/pkg/errors" "golang.org/x/oauth2" ) // OAuth2Config is an interface for the subset of *oauth2.Config functions used // for Brigade Session management. Dependence on this interface i...
package main import ( "errors" "github.com/caos/orbos/internal/operator/orbiter/kinds/clusters/core/infra" "github.com/spf13/cobra" ) func RebootCommand(getRv GetRootValues) *cobra.Command { return &cobra.Command{ Use: "reboot", Short: "Gracefully reboot machines", Long: "Pass machine ids as arguments,...
package aoc2016 import ( "testing" aoc "github.com/janreggie/aoc/internal" "github.com/stretchr/testify/assert" ) func Test_littleScreen_rect(t *testing.T) { assert := assert.New(t) testCases := []struct { width, height uint want littleScreen wantErr bool }{ { width: 3, height: 2,...
package article import ( "github.com/hardstylez72/bblog/internal/storage/article" "time" ) type ArticleWithBody struct { Article Body string `json:"body" validate:"required"` } type Article struct { Id string `json:"id"` Title string `json:"title" validate:"required"` UserId string `...
/* Copyright 2022 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, softw...
package middleware import ( "log" myerror "my-app/error" "my-app/interface/response" "net/http" "github.com/gin-gonic/gin" ) func ErrorMiddleware() gin.HandlerFunc { return func(c *gin.Context) { c.Next() err := c.Errors.Last() if err == nil { return } ge, ok := err.Err.(myerror.GeneralError) i...
/* * Strava API v3 * * The [Swagger Playground](https://developers.strava.com/playground) is the easiest way to familiarize yourself with the Strava API by submitting HTTP requests and observing the responses before you write any client code. It will show what a response will look like with different endpoints depen...
package patcher // Config represents a set of options that can be passed into an Apply action. type Config struct { // AllowCreate specifies wether or not we should be able to create the // object or not. If this is disabled, when an object does not exist on the // server and a patch is requested, Kubekit will retu...
package api import ( "bytes" "errors" "fmt" "io/ioutil" "os" "path" "sync" "sync/atomic" "time" "github.com/gholt/flog" "github.com/gholt/ring" "github.com/gholt/store" "github.com/pandemicsyn/ftls" "github.com/pandemicsyn/oort/oort" synpb "github.com/pandemicsyn/syndicate/api/proto" "golang.org/x/net...
package command import ( "context" "github.com/quintans/go-clean-ddd/internal/app" "github.com/quintans/go-clean-ddd/internal/domain" ) // this command handler would belong to a separate microservice responsible to send emails type SendEmailHandler interface { Handle(context.Context, SendEmailCommand) error } ...
package testutils import ( "bytes" "io/ioutil" "net/http" "testing" "github.com/dnaeon/go-vcr/cassette" "github.com/dnaeon/go-vcr/recorder" ) // RecordHTTP wraps tests and records all http requests made with the default // http transport in a file with the given name. If the file exists, // requests are replay...
// auth package auth import ( "io" "net/http" "aliyun/oss/common" "strings" "bytes" "crypto/hmac" "encoding/base64" "crypto/sha1" "sort" "hash" ) //build Signature func Sign(accessKeySecret string, verb string, header http.Header, resource string) string{ hs := make([]string, 0, len(header)) for k, _ :=...
package main import ( "bytes" "flag" "io/ioutil" "net/http" "os/exec" "regexp" "strconv" "sync" "gopkg.in/yaml.v2" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/prometheus/common/log" ) var ( showVersion = flag.Bool("version", f...