text stringlengths 11 4.05M |
|---|
package main
import "net/smtp"
type SMTPMailer struct{}
func (m *SMTPMailer) Send(to []string, from string, body []byte) error {
return smtp.SendMail("localhost:25", nil, from, to, body)
}
|
package client
import (
"net/http"
"net/url"
)
type GatewayClient interface {
Do(r *http.Request, success interface{}) (*http.Response, error)
Verb(method string)
Base(url string)
Path(path string)
Query(q url.Values)
Header(header http.Header)
Body(data []byte)
Request() (*http.Request, error)
Client(clie... |
package tsin
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document01100101 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:tsin.011.001.01 Document"`
Message *PartyRegistrationAndGuaranteeNotificationV01 `xml:"PtyRegnAn... |
package cli
import (
// "fmt"
"reflect"
"strings"
)
var executables = map[reflect.Type]*executable_t{}
func init() {
Register(Root{})
}
type executable_t struct {
Type reflect.Type
IsGroup bool
Names []string
ParentExec *executable_t
Parent reflect.StructField
Arg0 ... |
// git.
package main
import (
"fmt"
"os"
"os/exec"
"strings"
)
var s = func() string {
b, err := exec.Command("git", "rev-parse", "HEAD").CombinedOutput()
if err != nil {
if workdir, err := os.Getwd(); err != nil {
panic(err)
} else {
fmt.Fprintf(os.Stderr, "work directory:%s\n", workdir)
}
panic(... |
package fabonacci
import "testing"
func BenchmarkRecursion(b *testing.B) {
for i := 0; i < b.N; i++ {
Recursion(10)
}
}
func BenchmarkNoRecusion(b *testing.B) {
for i := 0; i < b.N; i++ {
NoRecusion(10)
}
}
|
// general ref : https://numerics.mathdotnet.com/Distance.html
package distance
import "math"
func (r *req) Chebyshev() float64 {
ln := len(r.a)
x := 0.0
for i := 0; i < ln; i++ {
x = math.Max(x, math.Abs(r.a[i]-r.b[i]))
}
return x
}
func (r *req) Euclidean() float64 {
ln := len(r.a)
x := 0.0
for i := 0; i... |
package common
import (
"encoding/xml"
"io/ioutil"
)
func ReadXmlToStruct(path string, config interface{}) error {
buffer, err := ioutil.ReadFile(path)
if err != nil {
return err
}
err = xml.Unmarshal(buffer, &config)
if err != nil {
return err
}
return nil
}
|
package controller
import (
"github.com/gin-gonic/gin"
"net/http"
)
func missingParam(name string, c *gin.Context) bool {
if c.PostForm(name) == "" {
c.JSON(http.StatusInternalServerError, gin.H{"executed": false, "message": "Missing data POST : " + name})
return true
}
return false
}
|
// Package config represents the configuration for mvm
package config
import (
"fmt"
"os"
"github.com/BurntSushi/toml"
"github.com/DexterLB/mvm/types"
)
// Config contains the general configuration of mvm
type Config struct {
FileRoot string `toml:"file_root"`
Importer Importer `toml:"importer"`
Library Li... |
package twitter
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
// "github.com/davecgh/go-spew/spew"
"github.com/dghubble/go-twitter/twitter"
"github.com/dghubble/oauth1"
)
type Config struct {
Twitter struct {
ScreenName string `json:"screen_name"`
ConsumerKey string `json:"consumer_key"`
Cons... |
// Copyright 2017 Jeff Foley. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
// +build darwin dragonfly freebsd linux netbsd openbsd
package core
import (
"syscall"
"golang.org/x/sys/unix"
)
// GetFileLimit raises the number of open files li... |
package __Go类型系统
/*
1.自定义类型
1.结构体
2.基于已有类型声明新类型
3.Note: 设计类型需要确认其本质是原始的还是非原始的
2.方法: 为类型添加行为
3.接口
1.定义行为,但不实现 ~ 由实现该接口的具体类型实现
2.多态
4.嵌入字段(类型): 为类型提供了扩展能力,而无需继承
*/
|
package main
import "bufio"
import "fmt"
import "os"
import "regexp"
import "strconv"
type input struct {
s []string
}
func main() {
input := getInput()
re := regexp.MustCompile(".*h.*a.*c.*k.*e.*r.*r.*a.*n.*k.*")
for x := range input.s {
matched := re.MatchString(input.s[x])
if matched {
fmt.Println("YE... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-08-16 15:44
# @File : quick_sort.go
# @Description :
# @Attention :
*/
package sort
func QuickSort(data []int) {
qSort(data, 0, len(data)-1)
}
func qSort(data []int, start, end int) {
if start < end {
paration := paration(data, start, end)
qSort(data... |
//import "sort"
func guno(playercount int, moves []string) []int {
var cards map[string]int
cards = make(map[string]int)
var players map[string]int
players = make(map[string]int)
var playerArryString []string
playerArryString = make([]string,playercount)
cards[... |
package rule
import (
"encoding/json"
"errors"
"net/http"
)
// Rule Balancind Rule
type Rule interface {
Execute(req *http.Request) bool
}
// NewRule :
func NewRule(ruleType string, setting map[string]interface{}) Rule {
switch ruleType {
case "DomainRule":
var domainSetting DomainSetting
mapToStruct(setti... |
package main
import (
"fmt"
)
func main() {
x := retornaumafunc()
x()
}
func retornaumafunc() func() {
return func() {
fmt.Println("Olha eu aqui!")
}
}
|
package caaa
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document01300103 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:caaa.013.001.03 Document"`
Message *AcceptorDiagnosticRequestV03 `xml:"AccptrDgnstcReq"`
}
func (d *Document013... |
package collect
import (
"bytes"
"fmt"
"io"
"github.com/kaz/pprotein/internal/storage"
)
type (
Processor interface {
Process(snapshot *Snapshot) (io.ReadCloser, error)
Cacheable() bool
}
cachedProcessor struct {
internal Processor
store storage.Storage
}
)
func newCachedProcessor(internal Proce... |
package controller
import (
"html/template"
"net/http"
)
func NewManga(templates map[string]*template.Template) *Manga {
return &Manga{
htmlTemplate: templates["manga.html"],
}
}
type Manga struct {
htmlTemplate *template.Template
}
func (m *Manga) Process(w http.ResponseWriter, req *http.Request, params map... |
package models
import (
"encoding/json"
"strconv"
"strings"
"time"
"github.com/gorilla/schema"
nats "github.com/nats-io/nats.go"
runner "github.com/nerdynz/dat/sqlx-runner"
"github.com/nerdynz/datastore"
"github.com/pinzolo/casee"
)
const NoRows = "sql: no rows in result set"
// var modelValidator *validat... |
package Problem0442
import (
"sort"
)
func findDuplicates(a []int) []int {
for i := 0; i < len(a); i++ {
for a[i] != a[a[i]-1] {
a[i], a[a[i]-1] = a[a[i]-1], a[i]
}
}
res := make([]int, 0, len(a))
for i, n := range a {
if i != n-1 {
res = append(res, n)
}
}
sort.Ints(res)
return res
}
|
package config
import "path/filepath"
type ResourceConfig struct {
Redis map[string][]*DBConfig `toml:"redis,omitempty" json:",omitempty"` // redis
Etcd map[string][]*DBConfig `toml:"etcd,omitempty" json:",omitempty"` // etcd
Mongo map[string][]*DBConfig `toml:"mongo,omitempty" json:",omitempty"` // mongo
... |
package map_slice
func Crossover(ns []int, xs []int,ys []int) ([]int, []int) {
length := len(xs)
r1 := make([]int, length, length)
r2 := make([]int, length, length)
nsIndex, resIndex := 0, 0
xsAppendR1 := true
for i := range xs {
if nsIndex < len(ns) && i == ns[nsIndex] {
xsAppendR1 = !xsAppendR1
nsInde... |
package lsp
import (
"context"
"encoding/base64"
"fmt"
"net"
"net/http"
"os"
"os/exec"
"runtime"
"time"
"github.com/golangq/q"
"golang.org/x/tools/lsp/protocol"
)
func (svr *server) serveJSON(rw http.ResponseWriter, req *http.Request) {
q.Q(req)
encUri := req.URL.RequestURI()[1:]
q.Q(encUri)
furi, err... |
package chapter1
import (
"bufio"
"fmt"
"os"
"strconv"
"github.com/apbgo/go-study-group/chapter1/lib"
)
// Calc opには+,-,×,÷の4つが渡ってくることを想定してxとyについて計算して返却(正常時はerrorはnilでよい)
// 想定していないopが渡って来た時には0とerrorを返却
func Calc(op string, x, y int) (int, error) {
// ヒント:エラーにも色々な生成方法があるが、ここではシンプルにfmtパッケージの
// fmt.Errorf(“in... |
package provider
import (
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/mrparkers/terraform-provider-keycloak/keycloak"
"strings"
)
func resourceKeycloakGroupRoles() *schema.Resource {
return &schema.Resource{
Create: resourceKeycloakGroupRolesReconcile,
Read: resourceKeycl... |
package hdwal
import (
"bytes"
"encoding/hex"
"fmt"
"github.com/bcbchain/bclib/bcdb"
"github.com/bcbchain/bclib/types"
"github.com/bcbchain/bclib/tendermint/go-crypto"
"testing"
)
func Test1_Mnemonic(t *testing.T) {
db, _ := bcdb.OpenDB("./", "", "")
SetDB(db)
mnemonic, err := Mnemonic("12345rewq!")
if err... |
package logbuf
import (
"syscall"
)
func localDup(oldfd int, newfd int) error {
return syscall.Dup2(oldfd, newfd)
}
|
package main
import "fmt"
var word string = "racecar"
// Graciously borrowed from Russ Cox | http://goo.gl/XrHvrk | slightly modified
func reverse(input string) string {
// Get Unicode code points.
n := 0
rune := make([]rune, len(input))
for _, r := range input {
rune[n] = r
n++
}... |
package main
import (
"fmt"
"github.com/lauyoume/gopinyin"
)
func main() {
fmt.Println(gopinyin.Convert("Hello,四节穇穈穉", false))
fmt.Println(gopinyin.Convert("·经典", false))
}
|
package bot
type Config struct {
PathToIndex string `env:"PATH_TO_INDEX,default=./bin/cities.idx"`
ProxySchema string `env:"TELEGRAM_PROXY_SCHEMA,default=http"`
ProxyAddr string `env:"TELEGRAM_PROXY_ADDR,default=127.0.0.1:8081"`
WebHookURL string `env:"TELEGRAM_WEBHOOK_URL"`
WebHookAddr string `... |
package leetcode
/*Given scores of N athletes, find their relative ranks and the people with the top three highest scores, who will be awarded medals: "Gold Medal", "Silver Medal" and "Bronze Medal".
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/relative-ranks
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/
import (
"so... |
package tstune
import "testing"
func TestParseLineForSharedLibResult(t *testing.T) {
cases := []struct {
desc string
input string
want *sharedLibResult
}{
{
desc: "initial config value",
input: "#shared_preload_libraries = '' # (change requires restart)",
want: &sharedLibResult{
commented: ... |
package bus
import (
"fmt"
"sync"
"github.com/CyCoreSystems/ari"
"github.com/inconshreveable/log15"
"github.com/nats-io/nats"
)
// EventChanBufferLength is the number of unhandled events which can be queued
// to the event channel buffer before further events are lost.
var EventChanBufferLength = 10
// Bus pr... |
package fsm
import (
"fmt"
"strings"
"encoding/json"
"reflect"
"strconv"
"time"
"github.com/aws/aws-sdk-go/service/swf"
. "github.com/sclasen/swfsm/sugar"
)
type HistorySegment struct {
State *HistorySegmentState
Correlator *EventCorrelator
Error *Seria... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//446. Arithmetic Slices II - Subsequence
//A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference ... |
/*
Challenge
The nation of Examplania has the following income tax brackets:
income cap marginal tax rate
¤10,000 0.00 (0%)
¤30,000 0.10 (10%)
¤100,000 0.25 (25%)
-- 0.40 (40%)
If you're not familiar with how tax brackets work, see the section below for an ex... |
package server
import (
"net/http"
)
// Route is a single route that has a handler and a list of middleware for the handler.
type Route struct {
Method string
Path string
Middlewares []func(http.Handler) http.Handler
Handler http.HandlerFunc
}
|
package appMgr
import (
appComm "github.com/HNB-ECO/HNB-Blockchain/HNB/appMgr/common"
"github.com/HNB-ECO/HNB-Blockchain/HNB/common"
"github.com/HNB-ECO/HNB-Blockchain/HNB/contract/hgs"
"github.com/HNB-ECO/HNB-Blockchain/HNB/contract/hnb"
dbComm "github.com/HNB-ECO/HNB-Blockchain/HNB/db/common"
"github.com/HNB-E... |
package linkaja
import (
"io"
"net/url"
"strings"
)
const (
PublicTokenRequestURL = "linkaja-api/api/payment"
CheckTransactionStatusURL = "linkaja-api/api/check/customer/transaction"
RefundTransactionURL = "tcash-api/api/rev/customer/transaction"
)
// CoreGateway struct
type CoreGateway struct {
Clie... |
package controller
import (
"encoding/json"
"errors"
"github.com/code7unner/vk-scrapper/internal/api/service"
"github.com/code7unner/vk-scrapper/internal/app"
"io/ioutil"
"net/http"
"strconv"
)
type PredictionController interface {
GetInRealTime(w http.ResponseWriter, r *http.Request)
Get(w http.ResponseWrit... |
package minedive
import "errors"
var (
ErrUnknownType = errors.New("unknown")
)
|
package filters
import (
"errors"
"fmt"
"strings"
)
const (
DeploymentsCollector = "Deployments"
JobsCollector = "Jobs"
ServiceDiscoveryCollector = "ServiceDiscovery"
)
type CollectorsFilter struct {
collectorsEnabled map[string]bool
}
func NewCollectorsFilter(filters []string) (*CollectorsF... |
package main
import (
"io/ioutil"
"os"
"testing"
"github.com/stretchr/testify/assert"
)
func TestProcess(t *testing.T) {
defer os.Remove("tests/test.html")
prepare(t)
process("tests/config.yml")
actual, err := ioutil.ReadFile("tests/test.html")
if err != nil {
t.Fatal(err)
}
expected, err := ioutil.R... |
package security
import (
"encoding/base64"
"fmt"
"html/template"
"net/http"
"strconv"
"strings"
"time"
"github.com/zaddok/log"
)
var COOKIE_DAYS = 365
type Page struct {
Session Session
Title []string
Class string
}
// Register pages specific to the security package
func RegisterHttpHandlers(am Acc... |
package usecase
import (
"context"
"errors"
"github.com/hezbymuhammad/payment-gateway/domain"
)
type transactionUsecase struct {
merchantRepo domain.MerchantRepository
transactionRepo domain.TransactionUsecase
}
func NewTransactionUsecase(mr domain.MerchantRepository, tr domain.Tran... |
package jwk
import (
"crypto"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/json"
"fmt"
"reflect"
)
type (
rawJSONWebKey struct {
Use string `json:"use,omitempty"`
Kty string `json:"kty,omitempty"`
Kid string `json:"kid,omitempty"`
Alg string `json:"alg,omitempty"`
N *... |
package snapshot
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"golang.org/x/sys/unix"
)
// Copies a file from src to dst. If copyOnWrite is true, attempts to
// use ioctl FICLONE to do the copy. If ioctl FICLONE is not supported
// by the underlying filesystem, falls back to a plain copy. If
// copyOnWrit... |
package main
import (
"fmt"
"runtime"
"sync"
)
/*
Using goroutines, create an incrementer program:
have a variable to hold the incrementer value;
launch a bunch of goroutines;
each goroutine should:
read the incrementer value;
store it in a new variable
yield the processor with runtime.Gosched(... |
package rand
import (
"github.com/irisnet/irishub/app/v1/rand/internal/keeper"
"github.com/irisnet/irishub/app/v1/rand/internal/types"
)
// exported types
type (
MsgRequestRand = types.MsgRequestRand
Rand = types.Rand
Request = types.Request
Requests = types.Requests
Params = type... |
// Copyright 2017 Jeff Foley. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
package dnssrv
/*
import (
"testing"
"time"
)
func TestDNSService(t *testing.T) {
config := DefaultConfig()
config.AddDomains([]string{testDomain})
s := NewDNSSer... |
package cherry
import (
"errors"
"github.com/xo/core"
"golang.org/x/net/context"
"log"
"os"
)
var logger = log.New(os.Stdout, "[cherry]", 0)
const (
cherryKey string = "Cherry"
)
var (
CherryNilError = errors.New("cherry is nil")
)
func CherryValue(ctx context.Context) *Cherry {
c := c... |
package main
import "fmt"
func updateName(name *string) {
*name = "David"
}
func main() {
firstName := "John"
updateName(&firstName)
fmt.Println(firstName)
}
|
package database
import (
"crypto/md5"
"database/sql"
"encoding/hex"
"net/url"
"time"
log "github.com/sirupsen/logrus"
_ "github.com/mattn/go-sqlite3"
"coreydaley.com/mailgoon/api"
)
// Database is the connection to the sqlite database
// and provides methods for interacting with
// the data and tables nee... |
package types
import (
"time"
"github.com/jinzhu/gorm"
uuid "github.com/satori/go.uuid"
)
//
// OauthAuthorizationCode is an outside party signed up to use
// our data
//
type OauthAuthorizationCode struct {
ID uuid.UUID `json:"id" gorm:"type:char(36);primary_key"`
UserID uuid.UUID `json:"us... |
package main
func main() {
}
func isWinner(player1 []int, player2 []int) int {
handle := func(player1 []int) int {
var p int
ten := -1
for i := 0; i < len(player1); i++ {
p += player1[i]
if ten != -1 && i-ten <= 2 {
p += player1[i]
}
if player1[i] == 10 {
ten = i
}
}
return p
}
... |
package database
import (
"log"
mgo "gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
. "../secret"
)
type Database struct {
Server string
Database string
}
var db *mgo.Database
const (
COLLECTION = "secrets"
)
func (m *Database) Connect() {
session, err := mgo.Dial(m.Server)
if err != nil {
log.Fatal(err)
}
... |
package main
import (
"github.com/javinc/go-space-shooter"
"github.com/javinc/go-space-shooter/component"
"github.com/veandco/go-sdl2/sdl"
"golang.org/x/image/colornames"
)
// returns player composition.
func newPlayer() *ecs.Entity {
input := component.NewInput()
input.Map[sdl.SCANCODE_LEFT] = component.InputM... |
package aws
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/service/ecs"
"github.com/gocircuit/runtime/prov"
)
// New returns a new worker provisioner based on Amazon spot instances.
func New() prov.Provisioner {
x
}
type provisioner struct {
ecs *ecs.ECS
}
func init() {
aws.DefaultCon... |
package skpsilk
// silk/src/SKP_Silk_create_init_destroy.c
/************************/
/* Init Decoder State */
/************************/
func init_decoder(psDec *decoder_state) int {
decoder_set_fs(psDec, 24)
psDec.first_frame_after_reset = 1
psDec.prev_inv_gain_Q16 = 65536
CNG_Reset(psDec)
PLC_Reset(psDec)
... |
package issuer
import (
"strconv"
"github.com/golang-jwt/jwt/v4"
"github.com/pkg/errors"
"github.com/kumahq/kuma/pkg/core/user"
)
type UserTokenValidator interface {
Validate(token Token) (user.User, error)
}
func NewUserTokenValidator(keyAccessor SigningKeyAccessor, revocations TokenRevocations) UserTokenVal... |
// Copyright (c) 2020 Blockwatch Data Inc.
// Author: alex@blockwatch.cc
package models
import (
"time"
)
type Chain struct {
RowId uint64 `gorm:"primary_key;column:row_id" json:"row_id"` // unique id
Height int64 `gorm:"column:heigh... |
package configurator
import (
"fmt"
"net"
"sort"
"strings"
"github.com/Cloud-Foundations/Dominator/lib/log"
fm_proto "github.com/Cloud-Foundations/Dominator/proto/fleetmanager"
hyper_proto "github.com/Cloud-Foundations/Dominator/proto/hypervisor"
)
func findMatchingSubnet(subnets []*hyper_proto.Subnet,
ipAdd... |
package sorting
func ShellSort(arr []int) []int {
for step := len(arr) / 2; step > 0 ; step /= 2 {
for i := step; i < len(arr); i++ {
for j := i; j >= step && arr[j] < arr[j - step]; j -= step {
arr[j], arr[j - step] = arr[j - step], arr[j]
}
}
}
return arr
}
|
package main
import (
"context"
"log"
"net"
divpb "github.com/golang-grpc-snippet/drill_exercise_1/division/protobuf"
"google.golang.org/grpc"
)
type server struct{}
func (*server) Division(c context.Context, req *divpb.DivRequest) (*divpb.DivResponse, error) {
first := req.GetNumber().GetFirst()
second := r... |
func jump(nums []int) int {
last_jump, this_jump, jumps := 0, 0, 0
for idx, jump := range nums[:len(nums)-1] {
this_jump = max(this_jump, idx + jump)
if idx == last_jump {
last_jump = this_jump
jumps += 1
}
}
return jumps
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
|
/*
* @lc app=leetcode.cn id=61 lang=golang
*
* [61] 旋转链表
*/
// @lc code=start
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
package main
import "fmt"
type ListNode struct {
Val int
Next *ListNode
}
func main() {
v1 := ListNode{1, nil}
v2 ... |
package main
import (
"fmt"
"strconv"
)
func main() {
var str string = "true"
var b bool
b, _ = strconv.ParseBool(str)
fmt.Printf("b = %v;b = %T\n", b, b)
var str1 string = "99"
var num1 int64
//bitSize可认为实际上做了校验的功能,防止数据越界
num1, _ = strconv.ParseInt(str1, 10, 0)
fmt.Printf("num1 = %v;num1 = %T\n", num1, ... |
package main
import (
"fmt"
"github.com/Kaey/framebuffer"
"log"
)
func main() {
fb, err := framebuffer.Init("/dev/fb0")
if err != nil {
log.Fatalln(err)
}
defer fb.Close()
fb.Clear(0, 0, 0, 0)
fb.WritePixel(200, 100, 255, 0, 0, 0)
fmt.Scanln()
}
|
package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"regexp"
"sort"
"strings"
"github.com/lhopki01/lexer-experiment/ast"
"github.com/lhopki01/lexer-experiment/lexer"
"github.com/lhopki01/lexer-experiment/parser"
)
func main() {
if len(os.Args) < 2 {
panic("no valid file name or path ... |
package myStack
import "testing"
func TestStack_Push(t *testing.T) {
stack := NewStack()
stack.Push(1)
stack.Push("second")
stack.Push(3)
t.Log(stack)
t.Log(stack.Pop())
t.Log(stack)
}
func TestStack_Pop(t *testing.T) {
stack := NewStack()
stack.Push("one")
stack.Push(2)
stack.Push("third")
t.Log(stack)
... |
package main
import "github.com/gin-gonic/gin"
func main() {
var router = gin.Default()
// Akses di localhost:8080/hello
router.GET("/hello", func(context *gin.Context) {
var fullName string = "Salman"
var helloMessage string = "Good morning"
context.JSON(200, gin.H{
"result": gin.H{
"fullName": ... |
package main
import (
"fmt"
"math"
)
func main() {
var n int
fmt.Scanf("%d", &n)
smallest, index := math.MaxInt32, 0
for i := 0; i < n; i++ {
var x int
fmt.Scanf("%d", &x)
if x < smallest {
smallest = x
index = i
}
}
fmt.Printf("Menor valor: %d\n", smallest)
fmt.Printf("Posicao: %d\n", inde... |
package asm
// ARM SMMUL operation
func SMMUL(op1, op2 int32) int32 {
x := int64(op1) * int64(op2)
return (int32)(x >> 32)
}
// ARM SMMULR operation
func SMMULR(op1, op2 int32) int32 {
x := 0x80000000 + int64(op1)*int64(op2)
return (int32)(x >> 32)
}
// ARM SMMLA operation
func SMMLA(op1, op2, op3 int32) int32 {... |
package raftstore
type raftDBWriter struct {
router *router
}
func (writer *raftDBWriter) Open() {
// TODO: stub
}
func (writer *raftDBWriter) Close() {
// TODO: stub
}
// type raftWriteBatch struct {
// ctx *kvrpcpb.Context
// requests []*rcpb.Request
// startTS uint64
// commitTS uint64
// }
// func... |
/*
http://www.apache.org/licenses/LICENSE-2.0.txt
Copyright 2016 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 ... |
package main
import (
"fmt"
"os"
"github.com/codegangsta/cli"
)
func main() {
app := cli.NewApp()
app.Name = "gosub"
app.Usage = "go dependency submodule automator"
app.Version = "0.0.1"
app.Commands = []cli.Command{
{
Name: "list",
ShortName: "e",
Usage: "list all packages required by t... |
package sqlite
import (
"context"
"database/sql"
"log"
"github.com/hezbymuhammad/payment-gateway/domain"
)
type sqliteTransactionRepo struct {
DB *sql.DB
}
func NewTransactionRepository(db *sql.DB) domain.TransactionRepository {
return &sqliteTransactionRepo{
DB: db,
... |
package main
import (
"encoding/json"
"fmt"
"github.com/google/uuid"
"github.com/hyperledger/fabric-contract-api-go/contractapi"
)
// Create adds a new id with value to the world state
func (rc *ResourceTypesContract) Create(
ctx contractapi.TransactionContextInterface,
id string,
name string,
) error {
if i... |
package model
import (
"fmt"
"github.com/zhenghaoz/gorse/base"
"github.com/zhenghaoz/gorse/core"
"math"
)
// KNN for collaborate filtering.
// Type - The type of KNN ('Basic', 'Centered', 'ZScore', 'Baseline').
// Default is 'basic'.
// Similarity - The similarity function. Default ... |
package controllers
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/go-resty/resty/v2"
"github.com/stretchr/testify/assert"
"github.com/ariel17/railgun/api/tests"
"github.com/ariel17/railgun/api/tests/mocks"
)
func TestGetDomainController(t *testing.T) {
r := gin.De... |
package storage
import (
"database/sql"
"fmt"
"testing"
"github.com/DATA-DOG/go-sqlmock"
"github.com/hashicorp/go-hclog"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/jaegertracing/jaeger-clickhouse/storage/clickhousedependencystore"
"github.com/jaegertracing/jaeger-... |
package config
import (
"fmt"
"gopkg.in/yaml.v2"
"github.com/robbiemcmichael/auth-mux/internal/input"
"github.com/robbiemcmichael/auth-mux/internal/output"
)
type Config struct {
Cert string `yaml:"cert"`
Key string `yaml:"key"`
Inputs []Input `yaml:"inputs"`
Outputs []Output `yaml:"outputs"`
}
... |
package none
import (
"crypto/rand"
"github.com/perlin-network/noise/crypto"
)
func RandomKeyPair() *crypto.KeyPair {
kp := &crypto.KeyPair{
PrivateKey: []byte{},
PublicKey: make([]byte, 32),
}
_, err := rand.Read(kp.PublicKey)
if err != nil {
panic(err)
}
return kp
}
type None struct{}
func (p *No... |
package philifence
import (
"github.com/jtejido/hrtree"
"math"
)
var (
MinimumNodeChildren = 50
MaximumNodeChildren = 200
Resolution = 32 // 64-bit resolution for hilbert curve
dim uint64 = 1 << (uint(Resolution) - 1)
)
const (
earthRadius = 6371e3 // assume WGS84... |
package model
import (
"time"
"github.com/jinlicode/jinli-panel/model/request"
)
// GetSiteList
func GetSiteList(info request.PageInfo) (err error, list interface{}, total int64) {
limit := info.PageSize
offset := info.PageSize * (info.Page - 1)
var site []request.Site
err = db.Limit(limit).Offset(offset).Find... |
package middlewares
import (
"net/http"
"ocg-be/util"
)
func IsAuthenticated(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("token")
if err != nil {
if err == http.ErrNoCookie {
http.Error(w, "Unauthorized", http.StatusU... |
package zippy
import (
"archive/zip"
)
func (z ZipReader) Find(path string) *zip.File {
for _, f := range z.reader.File {
if f.Name == path {
return f
}
}
return nil
}
|
package main
import (
"fmt"
)
func main() {
var h Human
//此處可看出 Being嵌入Human , Human嵌入Student 嵌入後卻又保持
s := Student{Grade:1, Major:"English", Human: Human{Name:"MeatTro", Age:31, Being: Being{IsLive:true}}}
fmt.Println("student:", s)
fmt.Println("student:", s.Name, ", isLive:", s.IsLive, ", age:", s.Age, ", gr... |
package bid
import "time"
// Bid is a struct containing bid info
type Bid struct {
BidderName string `json:"name"`
CPM float64
ElapsedTime time.Duration
}
// ProcessedBid is a struct containing bid info + auctioneer info
type ProcessedBid struct {
OK bool
RTElapsedTime time.Duration
Bid
}
|
package index
import (
"context"
"encoding/json"
"errors"
"net/http"
"time"
"github.com/gorilla/mux"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
func DeleteSection(response http.ResponseWriter, request *http.Request) {
response.Header().Add("content-type", "application/... |
package master
import (
"reflect"
"time"
"github.com/baidu/openedge/logger"
"github.com/baidu/openedge/master/engine"
"github.com/baidu/openedge/protocol/http"
"github.com/baidu/openedge/sdk-go/openedge"
)
// Config master init config
type Config struct {
Mode string `yaml:"mode" json:"mod... |
package decryptor
import (
"encoding/base64"
"encoding/hex"
"errors"
"github.com/mukesh0513/RxSecure/internal/utils"
"github.com/sirupsen/logrus"
"github.com/spf13/cast"
"reflect"
)
func AESDecrypt(key string, message string) (interface{}, error) {
inputParams := map[string]interface{}{
"key": key,
... |
package secret
import (
"fmt"
"github.com/spf13/cobra"
"github.com/werf/werf/cmd/werf/common"
"github.com/werf/werf/pkg/deploy/secrets_manager"
)
var commonCmdData common.CmdData
func NewCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "generate-secret-key",
DisableFlagsInUseLine: true... |
// DO NOT EDIT. This file was generated by "github.com/frk/gosql".
package testdata
import (
"github.com/frk/gosql"
"github.com/frk/gosql/internal/testdata/common"
)
func (q *DeleteWithReturningSingleAfterScanQuery) Exec(c gosql.Conn) error {
const queryString = `DELETE FROM "test_user" AS u
WHERE u."id" = $1
R... |
package engine
import "github.com/cascade/protocol"
// Executer ...
type Executer interface {
Prepare(protocol.Inputs, *protocol.Parameters) error
Execute() error
Finalize(protocol.Outputs) error
}
|
package mysql
import (
"database/sql"
"strings"
"time"
. "../../base"
"github.com/golang/glog"
)
func (p *Mysql) createDayTdataTable(table string) {
sql := "CREATE TABLE IF NOT EXISTS `" + table + "` (" +
"`time` DATETIME NOT NULL," +
"`open` INT(11) NOT NULL DEFAULT 0," +
"`high` INT(11) NOT NULL DEFAU... |
package main
var _bindata = map[string]func() ([]byte, error){
"data/char.dic": data_char_dic,
"data/connection.dic": data_connection_dic,
"data/contents.dic": data_contents_dic,
"data/costs.dic": data_costs_dic,
"data/index.dic": data_index_dic,
"data/unk.dic": data_unk_dic,
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.