text
stringlengths
11
4.05M
// Copyright 2023 Google LLC. 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 applica...
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package engine import ( "testing" "github.com/Azure/aks-engine/pkg/api" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/go-autorest/autorest/to" "github.com/google/go-cm...
package main import ( "fmt" "math" "github.com/kavehmz/prime" ) func main() { // ans: 1739023853137 var limit uint64 = 100000000 ps := prime.Primes(limit) m := make(map[uint64]struct{}, len(ps)) for _, p := range ps { m[p] = struct{}{} } var sum uint64 var candidat...
package httpclient import ( "bytes" "context" "encoding/json" "io" "net/http" "net/url" "strings" "time" "github.com/pkg/errors" ) // Request is builder for http.Request type Request struct { method string url string header http.Header body io.Reader } // NewRequest func NewRequest(method string, ...
/* 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 distributed under the License...
package storage import ( "errors" "github.com/arxdsilva/olist/bill" "github.com/arxdsilva/olist/record" ) type FakeStorage struct { records []record.Record bills []bill.Bill calls []bill.Call } func (f FakeStorage) SaveRecord(r record.Record) (err error) { f.records = append(f.records, r) return } func...
package contracts import "culture/cloud/base/internal/service" // PlatformService 平台可定制服务接口 type PlatformService interface { // Name 获取服务名称 Name() string // Ident 获取服务标识 Ident() string // InitService 初始化服务 InitService(cloudId uint64) service.Error // CheckService 检查服务是否可用 CheckService(cloudId uint64) (bool, s...
package main import "fmt" func main() { fmt.Println(maxCoins([]int{3, 1, 5, 8}) == 167) } // 注意:go 代码由 chatGPT🤖 根据我的 java 代码翻译,旨在帮助不同背景的读者理解算法逻辑。 // 本代码还未经过力扣测试,仅供参考,如有疑惑,可以参照我写的 java 代码对比查看。 func maxCoins(nums []int) int { n := len(nums) points := append([]int{1}, nums...) points = append(points, 1) dp := m...
package main import ( "fmt" "io" "net" "os" reuse "gx/ipfs/QmXD921xzL9EDRpD6gRm1cb7Khm8VEpZ3NT3nPK7uTX6Fq/go-reuseport" ) func main() { l1, err := reuse.Listen("tcp", "0.0.0.0:11111") maybeDie(err) fmt.Printf("listening on %s\n", l1.Addr()) l2, err := reuse.Listen("tcp", "0.0.0.0:22222") maybeDie(err) f...
package listen import ( "errors" "fmt" "github.com/lib/pq" "time" ) type Insert struct{ Listen } func (insert Insert) Listener(event Event) (*pq.Listener, error) { db := connect(event.ConnParams) err := createNotifyEvent(db) if err != nil { return nil, err } _, err = db.Query( fmt.Sprintf(` DROP TRI...
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may ...
package local import ( "io" "io/ioutil" "mime" "os" "path/filepath" "strings" "github.com/vasyahuyasa/july/opds/storage" ) var _ storage.Storage = &FsStorage{} var mimes = map[string]string{ ".epub": "application/epub+zip", ".fb2": "application/fb2+zip", ".mobi": "application/x-mobipocket-ebook", } type...
package constant const ( ConfigProjectFilepath = "config/config.json" )
package installer import ( "strings" "github.com/peterh/liner" ) func Rerun(dir string) (string, error) { lnr := liner.NewLiner() defer lnr.Close() lnr.SetCtrlCAborts(true) hist := GetHistory(dir) for i := len(hist) - 1; i >= 0; i-- { words := strings.Fields(hist[i]) if len(words) <= 1 { continue }...
package main import ( "errors" "flag" "fmt" "log" "net/http" "net/url" "strings" "github.com/gocolly/colly" "github.com/popstk/olddriver/core" ) const ( startURL = "http://taohuale.us/" spiderName = "taohua" ) func init() { log.SetFlags(log.Lshortfile | log.LstdFlags) } func mainPage() (*url.URL, err...
// benchmark. // // go test -bench Shift // package main import ( "fmt" "testing" ) var tests = []string{"hello", "world", "foo", "bar", "fizz", "buzz"} func BenchmarkShiftAppend(b *testing.B) { ss := make([]string, 3) ps := fmt.Sprintf("%p", ss) b.ResetTimer() for i := 0; i < b.N; i++ { for _, s := range te...
package sentinel import ( "fmt" "sync" "testing" "time" "github.com/garyburd/redigo/redis" ) func TestSentinel(t *testing.T) { st := NewSentinel( []string{"127.0.0.1:26379"}, "mymaster", ) defer st.Close() err := st.Discover() if err != nil { t.Log(err) t.FailNow() } addrs, err := st.SentinelAd...
// time: O(n); space: O(n) func convert(s string, numRows int) string { slopeLen := numRows - 2 if slopeLen < 0 { slopeLen = 0 } res := []byte{} for i := 0; i < numRows; i++ { if i == 0 || i == numRows-1 { for j := 0; i + (numRows + slopeLen) * j < len(s); j++ { ...
/* * @lc app=leetcode.cn id=1662 lang=golang * * [1662] 检查两个字符串数组是否相等 */ // @lc code=start package main func arrayStringsAreEqual(word1 []string, word2 []string) bool { i1 := 0 j1 := 0 i2 := 0 j2 := 0 for i1 < len(word1) && i2 < len(word2) { if word1[i1][j1] != word2[i2][j2] { return false } if j1 =...
package main import "fmt" func main() { num := 5 len := 2 for i, draw := range zigzag(num) { fmt.Printf("%*d ", len, draw) if i%num == num-1 { fmt.Println(" ") } } } func zigzag(n int) []int { arr := make([]int, n*n) i := 0 m := n * 2 for p := 1; p <= m; p++ { x := p - n if x ...
package c39_rsa import "math/big" func InvMod(a, b *big.Int) *big.Int { g, x := EGCD(a, b) if g.Cmp(bi(1)) != 0 { return nil } return x.Mod(x, b) } func DivMod(a, b *big.Int) (*big.Int, *big.Int) { q := new(big.Int).Div(a, b) return q, a.Sub(a, new(big.Int).Mul(q, b)) } func EGCD(a, b *big.Int) (*big.Int, *...
// Package storage contains handling with db(Postgesql) package storage import ( "errors" "fmt" "log" "github.com/jmoiron/sqlx" _ "github.com/lib/pq" "github.com/saromanov/gleek/config" ) var ( errNoConfig = errors.New("config is not defined") errNoCreds = errors.New("name, password or user is not defined f...
package main import "fmt" func main() { //fmt.Println(generate(1)) fmt.Println(generate(5)) } func generate(numRows int) [][]int { dp := make([][]int, numRows) for i := 0; i < numRows; i++ { dp[i] = make([]int, i+1) left, right := 0, i dp[i][left] = 1 dp[i][right] = 1 left++ right-- for left <= ...
package server import ( "context" "encoding/json" "errors" "fmt" "net/http" "net/http/httptest" "regexp" "strings" "testing" "time" "github.com/calvinmclean/automated-garden/garden-app/pkg" "github.com/calvinmclean/automated-garden/garden-app/pkg/influxdb" "github.com/calvinmclean/automated-garden/garden...
// This is a fork of code in Go's image/png package. // // Package apng is used to do low-level APNG encoding. The APNG format is not // widely supported in browsers, however, it can be an efficient way to // represent raster graphics in a lossless encoding, for instance to overlay // over a video with ffmpeg. // // F...
func removeDuplicates(nums []int) int { s:=0 f:=1 for f<len(nums){ if nums[s]==nums[f]{ f++ }else{ if f-s>1 { nums[s+1]=nums[f] } f++ s++ } } return s+1 }
package day05 import "fmt" func BigToSmallInt() { var big int64 = 1234567890 fmt.Printf("big: %b\t %d\n", big, big) fmt.Printf("BigToSmallInt: %d\t %b\n", uint8(big), uint8(big)) /* 十进制 二进制 1234567890 1001001100101100000001011010010 210 11010010 1001001100101100000001011010010 ---> 高位截断 ---> 1...
package http import ( "context" "encoding/json" "net/http" "time" "github.com/dheerajgopi/todo-api/common" todoErr "github.com/dheerajgopi/todo-api/common/error" "github.com/dheerajgopi/todo-api/common/middlewares" "github.com/dheerajgopi/todo-api/models" "github.com/dheerajgopi/todo-api/task" "github.com/g...
package rule import ( "database/sql" "encoding/json" "fmt" "ism.com/common/db" ) type FieldGroup struct { Id string `json:"id"` Name string `json:"name"` FieldDelimeter NullString `json:"fDelimeter"` Fields []FieldMap `json:"fields"` } type FieldMap struct { FieldIndex i...
package authentication import ( "fmt" "strings" ber "github.com/go-asn1-ber/asn1-ber" ldap "github.com/go-ldap/ldap/v3" ) func ldapEntriesContainsEntry(needle *ldap.Entry, haystack []*ldap.Entry) bool { if needle == nil || len(haystack) == 0 { return false } for i := 0; i < len(haystack); i++ { if haysta...
package cryptobox_test import ( "crypto/rand" "crypto/sha512" "encoding/base64" "errors" "github.com/GoKillers/libsodium-go/cryptobox" generichash "github.com/GoKillers/libsodium-go/cryptogenerichash" "github.com/GoKillers/libsodium-go/cryptosign" "github.com/agl/ed25519/extra25519" "github.com/btcsuite/btcut...
package jarviscore import ( "io/ioutil" "os" "go.uber.org/zap/zapcore" yaml "gopkg.in/yaml.v2" jarvisbase "github.com/zhs007/jarviscore/base" "go.uber.org/zap" ) // Config - config type Config struct { //------------------------------------------------------------------ // base configuration RootServAddr...
package api import ( "fmt" "github.com/alec-z/interests-back/model" "github.com/labstack/echo/v4" "golang.org/x/net/websocket" "math" "net/http" ) func Calculate(c echo.Context) (err error) { m := new(echo.Map) if err = c.Bind(m); err != nil { return } interestInput := new(model.InterestsInput) interest...
package goproxy // Router routes to some plugin type Router struct { tree *node } // NewRouter ... func NewRouter() (*Router, error) { return &Router{ tree: &node{}, }, nil } // AddRoute add plugin for a given path mask func (r *Router) AddRoute(mask string, f Plugin) error { return r.tree.addNode(mask, f) } ...
/* Copyright IBM Corporation 2020 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 testdata // NOTE: THIS FILE WAS PRODUCED BY THE // ZEBRAPACK CODE GENERATION TOOL (github.com/glycerine/zebrapack) // DO NOT EDIT import ( "github.com/glycerine/zebrapack/msgp" ) // MSGPfieldsNotEmpty supports omitempty tags func (z *A) MSGPfieldsNotEmpty(isempty []bool) uint32 { if len(isempty) == 0 { r...
package leetcode import ( "reflect" "testing" ) func TestReplaceElements(t *testing.T) { if !reflect.DeepEqual(replaceElements([]int{17, 18, 5, 4, 6, 1}), []int{18, 6, 6, 6, 1, -1}) { t.Fatal() } }
// Copyright 2018 gf Author(https://gitee.com/johng/gf). All Rights Reserved. // // This Source Code Form is subject to the terms of the MIT License. // If a copy of the MIT was not distributed with this file, // You can obtain one at https://gitee.com/johng/gf. // 文件监控. // 使用时需要注意的是,一旦一个文件被删除,那么对其的监控将会失效。 package gfs...
package implwin import ( "fmt" "draw" "win" ) type BitmapWin struct { hBmp win.HBITMAP hPackedDIB win.HGLOBAL size draw.Size oldHandle win.HGDIOBJ hdc win.HDC } func NewBitmap(size draw.Size) (bmp *BitmapWin, err error) { bmp = &BitmapWin{} bmp.hBmp = win.CreateBitmap(int32(size.Width)...
package handler import ( "io" "testing" generalpb "github.com/jinmukeji/proto/v3/gen/micro/idl/ptypes/v2" "github.com/stretchr/testify/suite" ) // SubmitMeasurementInfoTestSuite 测试提交测量数据 type SubmitMeasurementInfoTestSuite struct { suite.Suite jinmuHealth *JinmuHealth Account *Account } /* // SetupSuite ...
package mongo import ( // External Imports "github.com/globalsign/mgo" "github.com/sirupsen/logrus" ) const ( logError = "datastore error" logConflict = "resource conflict" logNotFound = "resource not found" logNotHashable = "unable to hash secret" ) // logger provides the package scoped logger im...
package route import ( "time" action "github.com/felixa1996/go-plate/adapter/api/action/charity_mrys" "github.com/felixa1996/go-plate/adapter/logger" presenter "github.com/felixa1996/go-plate/adapter/presenter/charity_mrys" "github.com/felixa1996/go-plate/adapter/repository" usecase "github.com/felixa1996/go-pl...
// example: // 123 // 456 // --- // 738 // 615 = 6888 // 492 = 56088 // ----- // func multiply(num1 string, num2 string) string { if num1[0] == '0' || num2[0] == '0' { return "0" } res := []int{0} for i := 0; i < len(num2); i++ { k := int(num2[len(num2)-i-1] - 48) n...
// Package utilities Internal Amazon Token struct package utilities import "time" // AmazonToken Describes what the token will look like type AmazonToken struct { AccessToken string `json:"amazon_access_token"` AccessTokenExpiry time.Duration `json:"amazon_accessToken_expiry"` }
package ping // // import ( // "testing" // "time" // ) // // var pingtests = []struct { // host string // ping bool // err string // }{ // {"127.0.0.1", true, ""}, // // {"8.8.8.8", true, ""}, // // {"google.com", true, ""}, // // {"128.0.0.1", false, "read ip 128.0.0.1: i/o timeout"}, // // {"fail.ping.gg...
package postgres import ( "database/sql" "errors" "math/rand" "time" "github.com/Boostport/migration" "github.com/Boostport/migration/driver/postgres" "github.com/gobuffalo/packr" "github.com/jmoiron/sqlx" "github.com/lib/pq" "github.com/dimuls/swan/entity" ) type Storage struct { uri string db *sqlx.D...
// 26. CTR bitflipping package main import ( "crypto/aes" "crypto/cipher" "crypto/rand" "fmt" "net/url" "strings" ) func main() { c, err := aes.NewCipher(RandomBytes(aes.BlockSize)) if err != nil { panic(err) } iv := RandomBytes(c.BlockSize()) data := []byte("XXXXX;admin=true") mask := xorMask(data) ...
package newrelic import ( "context" awssdk "github.com/aws/aws-sdk-go-v2/aws" "github.com/b2wdigital/goignite/pkg/cloud/aws/v2" "github.com/b2wdigital/goignite/pkg/log" "github.com/newrelic/go-agent/v3/integrations/nrawssdk-v2" ) type Integrator struct { options *Options } func NewIntegrator(options *Options...
package main import "github.com/julienschmidt/httprouter" // Route represents single API route and stores its handler function. type Route struct { Name string Method string Path string HandlerFunc httprouter.Handle } // Routes groups API routes for passing them between functions. type Routes ...
package file_common_test import ( "ms/sun/servises/file_service/file_common" "net/url" "testing" ) func BenchmarkRowReqParsingNotExists(b *testing.B) { url, _ := url.Parse("http://localhost:5151/post_file/1518506476136010007_180.jpg") for i := 0; i < b.N; i++ { req:= file_common.NewRowReq(file_common.HttpCateg...
// Copyright 2018 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 redisDB type ResTask struct { UID uint64 ID int16 Result int16 Data []byte }
package parquet import "github.com/segmentio/parquet-go/internal/unsafecast" type allocator struct{ buffer []byte } func (a *allocator) makeBytes(n int) []byte { if free := cap(a.buffer) - len(a.buffer); free < n { newCap := 2 * cap(a.buffer) if newCap == 0 { newCap = 4096 } for newCap < n { newCap *=...
package main import "github.com/vanishs/gwsrpc/services/demo" import "github.com/vanishs/gwsrpc/services/aaa" import "github.com/vanishs/gwsrpc/services/bbb" //Sain Services Main function is Sain func Sain(democh, aaach, bbbch chan string) { go func() { for { <-democh demoService.Start(10000, false, "", "", ...
// Copyright 2020 astaxie // // 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,...
// Frank Nanez // 4-25-20 // program to display my top 25 games played on steam and give information for user to learn more about the game. //load main package and import fmt, math/rand, time, and strconv packages into program. package main import ( "fmt" "math/rand" "time" "strconv" "strings" ) // create ...
/* Copyright 2021 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, ...
// Copyright (c) 2015-2017 Marcus Rohrmoser, http://purl.mro.name/recorder // // 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 t...
package handler // GetSensitiveWords 判断答案是否包含敏感词 func GetSensitiveWords(in string) []string { //TODO: return []string{} } // GetReservedWords 判断答案是否包含保留词 func GetReservedWords(in string) []string { //TODO: return []string{} } // GetMaskWords 判断答案是否包含屏蔽词 func GetMaskWords(in string) []string { //TODO: return []...
package main /* Types which don't support comparisons Following types don't support comparisons: map slice function struct types containing uncomparable fields array types with uncomparable elements Types which don't support comparisons can't be used as the key types of map types. Please note, although m...
// Copyright 2023 Google LLC. 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 applica...
// @Description TODO // @Author jiangyang // @Created 2020/11/16 5:04 下午 package ctx_test
package sessions import ( "encoding/base64" "encoding/json" "github.com/go-http-utils/cookie" ) // Version is this package's version const Version = "1.0.0" // Store is an interface for custom session stores. type Store interface { // Load should load data from cookie and store, set it into sessio...
package main import ( "bufio" "fmt" "log" "os" "regexp" "strconv" ) func main() { input := parseLines("day10/input.txt") points := make([]Point, len(input)) for i, line := range input { points[i] = linesToPoint(line) } fmt.Printf("Day 10 Part 1: %s is the order the steps should be completed\n", partOne...
package po import ( "context" "time" "github.com/ChowRobin/fantim/client" "github.com/jinzhu/gorm" ) type UserRelationApply struct { Id int64 `gorm:"primary_key"` FromUserId int64 `gorm:"column:from_uid"` ToUserId int64 `gorm:"column:to_uid"` // 存储uid 或 群id ApplyType int8 `gorm:"column:ap...
package main import "fmt" //这个不涉及指针的运算,不能像c语言一样直接操作指针,也不会导致内存溢出 //其实也就是&取地址,*根据地址取值 func main(){ n := 18 fmt.Println(&n) p := &n fmt.Println(*p) }
package keycloak import ( "bytes" "strconv" "strings" "time" ) type KeycloakBoolQuoted bool func (c KeycloakBoolQuoted) MarshalJSON() ([]byte, error) { var buf bytes.Buffer buf.WriteString(strconv.Quote(strconv.FormatBool(bool(c)))) return buf.Bytes(), nil } func (c *KeycloakBoolQuoted) UnmarshalJSON(in []by...
package filter type Group []Filter // GroupMap is a collection of filter "groups" // // Each key corresponds to a single group, and each group consists of every filter for the given key. // Filters ought to be applied in the order they are added, and the results of one filter are the inputs of the next. // // e.g. if...
package fare import ( "context" "fmt" "log" "github.com/go-kit/kit/endpoint" distancetypes "github.com/stamm/wheely/apis/distance/types" "github.com/stamm/wheely/apis/fare/types" ) type FareService struct { distanceCalc endpoint.Endpoint tariff types.Tariff } var ( _ IFareService = FareService{} ) f...
// Written in 2014 by Petar Maymounkov. // // It helps future understanding of past knowledge to save // this notice, so peers of other times and backgrounds can // see history clearly. package basic import ( "github.com/hoijui/escher/pkg/be" cir "github.com/hoijui/escher/pkg/circuit" ) type Repeat struct{} func ...
package main import ( "fmt" "strings" "github.com/istarli/fileParse/parser" ) func main() { files := []string{ // "JTT1022-2016.txt", // "JTT1055-2016.txt", // "JTT1057-2016.txt", // "JTT1075-2016.txt", // "JTT7353-2009.txt", // "JTT9792-2015.txt", // "GBT 1948-2-2008.txt", // "...
// main.go package main func main() { initialize(4, "P,1,1,p,N,1,1,n,B,1,1,b,R,1,1,r") drawBoard() }
package middleware import ( "net/http" "github.com/gin-gonic/gin" "github.com/pkg/errors" "gorm.io/gorm" ) func ErrorHandler(c *gin.Context) { c.Next() err := c.Errors.Last() if err != nil { // すでにステータスコードが指定されていれば何もしない if c.Writer.Status() != 0 { return } cause := errors.Cause(err.Err) if error...
package chain import ( "os" "strings" "github.com/iotaledger/wasp/tools/wasp-cli/log" "github.com/spf13/pflag" ) func InitCommands(commands map[string]func([]string), flags *pflag.FlagSet) { commands["chain"] = chainCmd fs := pflag.NewFlagSet("chain", pflag.ExitOnError) initDeployFlags(fs) initUploadFlags(f...
package main import ( "finrgo/exhanges" "finrgo/exhanges/poloniex" "finrgo/strategy/arb" "fmt" "runtime" "sync" ) const ( BittrexExchange string = "bittrex" PoloniexExchange string = "poloniex" ) func main() { numcpu := runtime.NumCPU() fmt.Println("NumCPU", numcpu) // runtime.GOMAXPROCS(numcpu) NewArb...
package main import ( "code.google.com/p/go-sqlite/go1/sqlite3" "fmt" "hash/fnv" "html/template" "io" "net/http" "net/url" "regexp" "strconv" ) type Message struct { Text string Type string } var validPath = regexp.MustCompile("^/(save|([a-zA-Z0-9]*))$") func saveUrlHandler(w http.ResponseWriter, r *http...
package model import ( "github.com/dgrijalva/jwt-go" "main/conf" "time" ) type JwtClaims struct { Name string `json:"name"` jwt.StandardClaims } func CreateJwtToken(name string, id string) (string, error) { jwtClaims := JwtClaims{ name, jwt.StandardClaims{ Id: id, ExpiresAt: time.Now().Add(24 ...
package main // Stolen from https://github.com/sabhiram/go-wol import ( "bytes" "encoding/binary" "errors" "log" "net" "regexp" ) // Define globals for the MacAddress parsing var ( delims = ":-" reMAC = regexp.MustCompile(`^([0-9a-fA-F]{2}[` + delims + `]){5}([0-9a-fA-F]{2})$`) ) type MA...
package user import ( "camp/lib" "camp/week2/api" "camp/week2/model" "camp/week2/util" ) func (userService *UserService) getUserByIBase(base lib.IBase) (user *api.User, err error) { // 获取 token 中的 uid uid, err := util.TokenToUid(base) if err != nil { return nil, err } userModel := model.NewUser() user, e...
package httpmanager import ( "encoding/json" "net/http" ) // GetHandler returns a function metadata func (m* Manager) GetHandler(w http.ResponseWriter, r *http.Request) { r.ParseForm() funcName := r.FormValue("funcName") res, err := m.platformManager.GetFunction(funcName) if err != nil { http.Error(w, err.Er...
package Problem0420 import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) // tcs is testcase slice var tcs = []struct { s string ans int }{ {"", 6}, {"aB3aB3", 0}, {"aaaaaaaaaaaaaaaaaaaaa", 7}, {"aaaaaaaaaaaaaaaaaaaaaa", 8}, {"aaaAaaaAaaaAaaaAaaaAa", 5}, {"aadssfasfASDaaaaaaaaaaASDfA2352...
package main import ( "os" "github.com/therecipe/qt/widgets" ) func main() { os.Setenv("QT_IM_MODULE", "qtvirtualkeyboard") widgets.NewQApplication(0, nil) window := widgets.NewQMainWindow(nil, 0) window.SetMinimumSize2(250, 200) widget := widgets.NewQWidget(nil, 0) widget.SetLayout(widge...
package scale import ( "strings" ) var ( scaleWithSharps = []string{"A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#"} scaleWithFlats = []string{"A", "Bb", "B", "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab"} ) // Scale returns a scale that starts at tonic and follows the interval pattern. // Supp...
package info import ( "context" "github.com/coredns/coredns/plugin" "github.com/miekg/dns" clog "github.com/coredns/coredns/plugin/pkg/log" ) var log = clog.NewWithPlugin("info") type info struct { Next plugin.Handler } func (i *info) Name() string { return "info" } func (i *info) ServeDNS(ctx context.Conte...
package main import ( "fmt" ) var _ Match = (*AndMatch)(nil) type AndMatch struct { SubMatch []Match } func (am *AndMatch) AssembleMatch(counter *IDCounter, ruleEndLabel, actionLabel string) ([]string, error) { andAsm := []string{ "# And", } for i, match := range am.SubMatch { matchAsm, err := match.Assem...
/* ** description(""). ** copyright('open-im,www.open-im.io'). ** author("fg,Gordon@open-im.io"). ** time(2021/3/5 14:31). */ package logic import ( push "Open_IM/internal/push/jpush" rpcChat "Open_IM/internal/rpc/chat" "Open_IM/pkg/common/config" "Open_IM/pkg/common/constant" "Open_IM/pkg/common/log" "Open_IM/...
package gojson import ( "fmt" "testing" ) var js *GoJSON var data = []byte(`{ "person": { "id": "d50887ca-a6ce-4e59-b89f-14f0b5d03b03", "name": { "fullName": "Leonid Bugaev", "givenName": "Leonid", "familyName": "Bugaev" }, "email": "leonsbox@gmail.com", "gender": "male", ...
package hashtable //hashtable的go语言实现,使用数组加链表的方法,实现了增加,删除,查询等功能 import ( "container/list" ) //键值对的结构体 type Node struct { key int value int } //哈希表的结构体 type HashTable struct { size int array []*list.List } //产生一个新的哈希表,size参数用于设置哈希表里面链表数组的大小 func CreateHashTable(size int) HashTable { ha...
package jsonstore import ( "context" "encoding/json" "os" "sync" "sync/atomic" "time" ) type Value interface { Clone() Value } type Store interface { Load() (x Value) Store(x Value) Save() error Close() Context() context.Context } type jsonStore struct { mu *sync.Mutex ctx context.Con...
package main import ( "fmt" "strconv" ) var text = "pesan rahasia ..." func kali(angka1 int, angka2 int) int { return angka1 * angka2 } func infoMultiReturn(umur int, nama string, status string) (string, string) { umurSekarang := strconv.Itoa(umur) return "nama : " + nama + " umur :" , umurSekarang + " hubung...
package handler import "github.com/gin-gonic/gin" type Data gin.H
package wallet_interface import "strings" // CoinType represents a cryptocurrency that has been // implemented the wallet interface. type CoinType string // CurrencyCode returns the coins currency code. func (ct CoinType) CurrencyCode() string { return strings.ToUpper(string(ct)) } const ( // Mainnet CtMock ...
package user_test import ( "auth/user" "github.com/stretchr/testify/assert" "testing" ) func TestValidateUser(t *testing.T){ service := user.NewService() t.Run("invalid user", func(t *testing.T) { err := service.ValidateUser("eminetto@gmail.com", "invalid") assert.NotNil(t, err) assert.Equal(t, "Invalid us...
package config import ( "testing" "github.com/stretchr/testify/assert" ) func TestErrorShouldReturnColorizedTextWhenColorEnabled(t *testing.T) { EnableColor(true) assert.Equal(t, "\x1b[31mhello\x1b[0m", Error("hello")) } func TestErrorShouldReturnNonColorizedTextWhenColorDisabled(t *testing.T) { EnableColor(fa...
// Copyright (c) 2019 VMware, Inc. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package exec import ( "os" "strings" "testing" ) func TestExampleScripts(t *testing.T) { tests := []struct { name string scriptPath string args ArgMap }{ { name: "api objects", scriptPa...
package handler import ( "context" "encoding/json" "errors" "io/ioutil" "net/http" "net/http/httptest" "strings" "testing" "time" "github.com/golang/mock/gomock" "github.com/google/uuid" "github.com/gorilla/mux" "github.com/stretchr/testify/require" "2019_2_IBAT/pkg/app/auth" "2019_2_IBAT/pkg/app/auth...
package log import ( "dev-framework-go/conf" "fmt" "github.com/gin-gonic/gin" "strings" ) //日志中间件 func DiyLogger() gin.HandlerFunc { // 请求日志 return gin.LoggerWithFormatter(func(p gin.LogFormatterParams) string { if strings.HasPrefix(p.Path, "/swagger/") == true { return "" } return fmt.Sprintf("[%s] %d...
package owm import ( "encoding/json" "fmt" "math" "net/http" "net/url" "path" "strconv" "strings" "time" "github.com/tada3/triton/weather/model" ) const ( CurrentWeatherPath string = "weather" WeatherForecastPath string = "forecast" tempStrFormatP string = "%d度" tempStrFormatN string = "氷点下%...
package main import ( "context" "fmt" "github.com/hunterhug/gorlock" "time" ) func main() { gorlock.SetDebug() // 1. config redis // 1. 配置Redis redisHost := "127.0.0.1:6379" redisDb := 0 redisPass := "hunterhug" // may redis has password config := gorlock.NewRedisSingleModeConfig(redisHost, redisDb, redis...
package ber import ( "bytes" "io" "math" "testing" ) func TestEncodeDecodeInteger(t *testing.T) { for _, v := range []int64{0, 10, 128, 1024, math.MaxInt64, -1, -100, -128, -1024, math.MinInt64} { enc := encodeInteger(v) dec, err := ParseInt64(enc) if err != nil { t.Fatalf("Error decoding %d : %s", v, e...