text stringlengths 11 4.05M |
|---|
package saetoauthv2
import (
"fmt"
)
func NewAuthV2(ClientID, ClientSecret, AccessToken, RefreshToken string) (auth *AuthV2) {
fmt.Println("NewAuthV2")
auth = &AuthV2{
ClientID:ClientID,
ClientSecret:ClientSecret,
AccessToken:AccessToken,
RefreshToken:RefreshToken,
Host:"https://api.weibo.com/2/",
... |
package parsing
import (
"github.com/s2gatev/sqlmorph/ast"
)
const LimitWithoutNumberError = "LIMIT statement must be followed by a number."
// LimitState parses LIMIT SQL clauses along with the value.
// ... LIMIT 10 ...
type LimitState struct {
BaseState
}
func (s *LimitState) Name() string {
return "LIMIT"
}
... |
package core
import (
"monitoring/internal"
"fmt"
"os"
"time"
)
func (r *System)initHost() int {
internal.CheckErr(r.Host.new(),"couldn't load host info")
internal.CheckErr(r.CPU.PollingInfo(), "couldn't load cpu info")
internal.CheckErr(r.Disk.PollingInfo("/"), "couldn't load disk info")
fmt.Fprintf(os.Stdo... |
/*
Create a function that takes a division equation $str and checks if it will return a whole number without decimals after dividing.
Examples
validDivision("6/3") ➞ true
validDivision("30/25") ➞ false
validDivision("0/3") ➞ true
Notes
Return "invalid" if division by zero.
*/
package main
import "fmt"
func m... |
package errutil
import (
"fmt"
)
// First returns first non-nil error out of errs, or nil.
func First(errs ...error) error {
for _, e := range errs {
if e != nil {
return e
}
}
return nil
}
// FatalIf panics if err is not nil.
func FatalIf(err error) {
if err == nil {
return
}
panic(fmt.Sprintf("FATA... |
// Copyright © 2014 Alienero. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package comet
import (
"fmt"
"github.com/Alienero/spp"
"github.com/golang/glog"
)
// Tcp write queue
type PackQueue struct {
// The last error in the tcp co... |
/*
* @lc app=leetcode.cn id=929 lang=golang
*
* [929] 独特的电子邮件地址
*/
package main
import (
"strings"
)
// @lc code=start
func numUniqueEmails(emails []string) int {
emailMap := make(map[string]bool)
for i := 0; i < len(emails); i++ {
email := strings.Split(emails[i], "@")
index := strings.Index(email[0], "+"... |
package web
import (
"net/http"
"fmt"
)
func handleError(err error, w http.ResponseWriter, r *http.Request) {
w.WriteHeader(500)
fmt.Fprintf(w, err.Error())
}
func handleNotFound(w http.ResponseWriter, r *http.Request) {
http.NotFound(w, r)
} |
package dushengchen
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
/**
https://leetcode.com/submissions/detail/740046542/
Runtime: 20 ms, faster than 32.24% of Go online submissions for Lowest Common Ancestor of a Binary Tree.
M... |
package option
import "fmt"
type Search struct {
title string
limit int
}
type SearchOption func(*Search)
func SearchTitle(title string) SearchOption {
return func(s *Search) {
s.title = title
}
}
func SearchLimit(limit int) SearchOption {
return func(s *Search) {
s.limit = limit
}
}
func Option(options... |
package collectors
import (
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/bosh-prometheus/bosh_exporter/deployments"
)
type DeploymentsCollector struct {
deploymentReleaseInfoMetric *prometheus.GaugeVec
deploymentStemcellInfoMetric *prometheus.GaugeVec
deploy... |
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"time"
"cloud.google.com/go/storage"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
var (
bucketName = os.Getenv("BUCKET_NAME")
googleAccessID = os.Getenv("GOOGLE_ACCESS_ID")
privateKeyPath = os.Getenv("PRIVATE_K... |
package ptr
// String returns a pointer to the given string
func String(x string) *string { return &x }
|
// Web Server
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", handler) // ada petición llama a un handler
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
// handler each request
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Printf("URL.Path = %q", r.URL.P... |
// Copyright (c) 2020 Hirotsuna Mizuno. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
package speedio
import (
"fmt"
"sync"
"time"
"github.com/tunabay/go-infounit"
)
// limiter limits the transfer.
type limiter struct {
rate float... |
// Copyright 2019 Kuei-chun Chen. All rights reserved.
package mdb
import (
"context"
"fmt"
"log"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// ChangeStream defines what to watch? client, database or collection
type ChangeStream struct ... |
package main
import (
"context"
"fmt"
"time"
"github.com/yandex-cloud/examples/serverless/serverless_voximplant/scheme"
"github.com/yandex-cloud/ydb-go-sdk"
"github.com/yandex-cloud/ydb-go-sdk/table"
)
func listDocs(ctx context.Context, req *doctorsRequest) ([]*scheme.Doctor, error) {
switch {
case len(req.S... |
package constants
const (
CacheDuration = "10s"
)
|
package isValidBST
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
/*
// wrong
func isValidBST(root *TreeNode) bool {
if root == nil {
return true
}
return validBST(root.Left, root.Val, -2147483648, true) &&
validBST(root.Right, 2147483647, root.Val, false)
}
func validBST(root *TreeNode... |
package poker
import (
"encoding/json"
"fmt"
"io"
)
type Player struct {
Name string
Wins int
}
type League []Player
func (l League) Find(name string) *Player {
for i, p := range l {
if p.Name == name {
return &l[i]
}
}
return nil
}
func LeagueFromReader(r io.Reader) ([]Player, error) {
var league ... |
package telegraph
import "testing"
func TestContentFormatByWTF(t *testing.T) {
_, err := ContentFormat(42)
if err == nil {
t.Error()
}
t.Log(err.Error())
}
func TestCreateInvalidAccount(t *testing.T) {
_, err := CreateAccount("", "", "")
if err == nil {
t.Error()
}
t.Log(err.Error())
}
func TestCreateIn... |
package econtext
import (
"github.com/labstack/echo"
"golang.org/x/net/context"
)
const (
ckey = "echo.Context"
contextkey = "context.Context"
)
// FromContext extracts the bound golang.org/x/net/context.Context from a Echo
// context if one has been set, or nil if one is not available.
func FromContext(c ... |
package lib
import (
"fmt"
"io/ioutil"
"math"
"sort"
)
type Searcher struct {
CompleteWorks *string
WorksIndex *[]Work
NGramRules *[]*NGramRule
//SuffixArray *suffixarray.Index
}
type SearchResultHighlight struct {
SubContentBefore string
Token string
SubContentAfter string
}
type Searc... |
package dao
import (
"database/sql"
"github.com/google/wire"
"github.com/Eric-WangHaitao/Go-0712/Week04/internal/model"
"log"
)
type UserRepository interface {
AddUser()
}
type userRepo struct {
*sql.DB
}
func (u *userRepo) AddUser() {
user := &model.User{}
user.Id = 1
user.Name = "xiaoming"
log.Println("... |
package domain
import (
"errors"
"fmt"
)
// errors
var (
// ErrValidSessionNotFound is returned when a valid session is not found
ErrValidSessionNotFound = errors.New("Valid session not found")
// ErrSessionExpired is returned when the requested session has expired
ErrSessionExpired = errors.New("Session is ex... |
// This file contains a bit reworked methods from:
// https://github.com/bwmarrin/dgvoice/blob/master/dgvoice.go
//
// License:
// https://github.com/bwmarrin/dgvoice/blob/master/LICENSE
package main
import (
"bufio"
"encoding/binary"
"fmt"
"github.com/bwmarrin/discordgo"
"github.com/layeh/gopus"
"io"
"net/htt... |
package main
import (
"bytes"
"encoding/json"
"github.com/pkg/errors"
"github.com/sethgrid/pester"
"io/ioutil"
"log"
"math/rand"
"net/http"
"time"
)
const eventAPI = "http://127.0.0.1:8080/event/update"
const betsAPI = "http://127.0.0.1:8081/bets?status=active"
type eventUpdateDto struct {
Id string `... |
package ipproxy
import (
"context"
"fmt"
"net"
"github.com/google/netstack/tcpip"
"github.com/google/netstack/tcpip/buffer"
"github.com/google/netstack/tcpip/network/ipv4"
"github.com/google/netstack/tcpip/transport/udp"
"github.com/getlantern/errors"
"github.com/getlantern/eventual"
)
func (p *proxy) onUD... |
package suggest
import (
"fmt"
"testing"
)
func TestSuggest(t *testing.T) {
query := "apples and oranges"
suggestions, err := Suggest(query)
if err != nil {
t.Error(err)
}
if len(suggestions) <= 0 {
t.Error("expected suggestions, got none")
}
}
func ExampleSuggest() {
query := "apples and oranges"
... |
package main
// 剑指 Offer II 083. 没有重复元素集合的全排列
// 给定一个不含重复数字的整数数组 nums ,返回其 所有可能的全排列 。可以 按任意顺序 返回答案。
// 输入:nums = [1,2,3]
// 输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
func main() {
nums := []int{1, 0}
permute(nums)
}
func permute(nums []int) [][]int {
var answer [][]int
visited := make([]bool, len(nums)... |
/*
Crie uma função que retorna uma função.
Atribua a função retornada a uma variável.
Chame a função retornada.
*/
package main
import (
"fmt"
"math"
)
func main() {
f := retornaNúmeroAoCubo()
fmt.Println("2 elevado ao cubo é:", f(2.0))
}
func retornaNúmeroAoCubo() func(num float64) float64 {
return func(nu... |
package export
import (
"fmt"
"github.com/shopspring/decimal"
"github.com/tealeg/xlsx"
"strconv"
"time"
)
type CreateWalletLogFileRequest struct {
Sheet string // 工作表
Title string // 文件标题
Timezone string // 时区
IsDivideHundred bool // 金额是否需要除以100,币种单位为分的都需要
Co... |
package pgsql
import (
"database/sql"
"database/sql/driver"
"strconv"
)
// Int4RangeFromIntArray2 returns a driver.Valuer that produces a PostgreSQL int4range from the given Go [2]int.
func Int4RangeFromIntArray2(val [2]int) driver.Valuer {
return int4RangeFromIntArray2{val: val}
}
// Int4RangeToIntArray2 return... |
package logic
import (
ccmd "github.com/pip-services3-go/pip-services3-commons-go/commands"
cconv "github.com/pip-services3-go/pip-services3-commons-go/convert"
"github.com/pip-services3-go/pip-services3-commons-go/run"
cvalid "github.com/pip-services3-go/pip-services3-commons-go/validate"
)
type AppExampleComman... |
package main
import (
"fmt"
"sort"
)
func main() {
mapTest := make(map[int]int, 5)
mapTest[1] = 1000
mapTest[3] = 4
mapTest[4] = 3
mapTest[2] = 2
var keys []int
for k, _ := range mapTest {
keys = append(keys, k)
}
sort.Ints(keys)
fmt.Println(keys)
for _, val := range keys {
fmt.Printf("k=%v,v=%v\n", ... |
package luasrc
import (
"github.com/davyxu/tabtoy/v3/gen"
"github.com/davyxu/tabtoy/v3/model"
"strings"
"text/template"
)
var UsefulFunc = template.FuncMap{}
func WrapValue(globals *model.Globals, value string, valueType *model.TypeDefine) string {
if valueType.IsArray() {
var sb strings.Builder
sb.WriteSt... |
package leetcode
/*We distribute some number of candies, to a row of n = num_people people in the following way:
We then give 1 candy to the first person, 2 candies to the second person,
and so on until we give n candies to the last person.
Then, we go back to the start of the row, giving n + 1 candies to the first ... |
/*
Copyright 2018 The HAWQ Team.
*/
// Api versions allow the api contract for a resource to be changed while keeping
// backward compatibility by support multiple concurrent versions
// of the same resource
// +k8s:openapi-gen=true
// +k8s:deepcopy-gen=package,register
// +k8s:conversion-gen=github.com/hawq-cn/... |
package hardcoding
import "github.com/chitoku-k/ejaculation-counter/reactor/repository"
var (
ThroughVariants = []string{
"doruȝ-",
"dorw",
"dorwe",
"dorwgh",
"dourȝh",
"drowgȝ",
"durghe",
"durwe",
"-thogh",
"thorch",
"thorew",
"thorewe",
"thorffe",
"thorg",
"Thorgh",
"thorgh",
"-th... |
package domain
import "github.com/hyeyoom/go-web-app-boilerplate/domain/base"
type Product struct {
base.DefaultModel
Name string
}
type ProductRepository interface {
Create(*Product)
}
|
package main
import (
_ "github.com/jcallow/covid19map/internal/controllers"
)
func main() {
}
|
package main
import (
"fmt"
"time"
)
var locales map[string]map[string]string
func main() {
locales = make(map[string]map[string]string)
en := make(map[string]string, 10)
en["pea"] = "pea"
en["bean"] = "bean"
en["how old"] = "I am %d years old"
en["time_zone"] = "America/Chicago"
locales["en"] = en
// 设置中文... |
package service
import (
"fmt"
"github.com/parnurzeal/gorequest"
"net/http"
)
//mesher listen 127.0.0.1:30101
var proxy = gorequest.New().Proxy("http://127.0.0.1:30101")
//use proxy way to connect provider demo-mesher-server's api /demo/hello
func Greeting() ([]byte, error) {
resp, body, errs := proxy.Get("http:... |
package main
import (
"bufio"
"encoding/json"
"log"
"fmt"
"os"
"os/user"
"github.com/tskinn/pomogo"
)
func main() {
reader := bufio.NewReader(os.Stdin)
// get old task
oldRaw, _, _ := reader.ReadLine()
oldTask := pomogo.Task{}
err := json.Unmarshal(oldRaw, &oldTask)
if err != nil {
log.Println(err)
... |
package types
import (
"encoding/json"
"fmt"
"time"
)
type Timestamp struct {
time.Time
}
// UnmarshalJSON decodes an int64 timestamp into a time.Time object
func (p *Timestamp) UnmarshalJSON(bytes []byte) error {
// 1. Decode the bytes into an int64
var raw int64
err := json.Unmarshal(bytes, &raw)
if err !... |
package main
import (
"encoding/json"
"fmt"
"sort"
"testing"
)
func TestSortMap(t *testing.T) {
m := map[string]string{
"1":"222",
"2":"2212",
"3":"2232",
}
keys := []string{}
for k, _ := range m {
keys = append(keys, k)
}
sort.Strings(keys)
for _, v := range keys {
fmt.Println(m[v])
}
}
func T... |
package main
import "fmt"
func sum(xi ...int) int {
var s int
for _, v := range xi {
s = s + v
}
return s
}
func main() {
fmt.Println(sum(2, 4, 5, 4, 3))
fmt.Println(sum(5, 0, 8))
fmt.Println(sum(5, 4))
}
|
package service
import (
"github.com/makishi00/go-vue-bbs/model"
"github.com/makki0205/gojwt"
)
var Token = token{}
type token struct {
}
func (t *token) Store(token model.Token) model.Token {
db.Create(&token)
return token
}
func (t *token) ExistByToken(token string) bool {
var tokens []model.Token
db.Where("... |
package leetcode
type Trie struct {
t []*Trie
e bool
p bool
}
/** Initialize your data structure here. */
func Constructor() Trie {
var trie = Trie{t: make([]*Trie, 26), e: false, p: false}
return trie
}
/** Inserts a word into the trie. */
func (this *Trie) Insert(word string) {
if len(word) == 0 {
this.... |
package action_fanout_service
import (
"ms/sun_old/base"
"ms/sun/shared/helper"
"ms/sun/servises/mem_user_service"
"ms/sun/shared/x"
)
func resetActionFanoutForUser(userId int) {
var toSaveArr []x.ActionFanout
x.NewActionFanout_Deleter().ForUserId_Eq(userId).Delete(base.DB)
um, ok := mem_user_service.GetForUs... |
package routes
import (
"github.com/gorilla/mux"
"github.com/ipastushenko/simple-chat/server/controllers/session"
)
func appendAuthAuthRouter(router *mux.Router) {
router.Handle("/auth/sign_out", session.NewSignOutHandler()).Methods("GET")
}
func appendAnonymousAuthRouter(router *mux.Router) {
router... |
package mining
import (
"encoding/json"
"strconv"
"github.com/yggie/github-data-challenge-2014/models"
)
type EventsResult struct {
PushEvents []*models.PushEvent
}
func (r *EventsResult) AddPushEvent(event *models.PushEvent) {
r.PushEvents = append(r.PushEvents, event)
}
func ParseEvents(data []byte) *Events... |
package postgres_backend
import (
"bytes"
"fmt"
"github.com/straumur/straumur"
"strings"
)
func writeArray(paramCount int, args *[]interface{}, key string, arr []string) (int, string) {
var buffer bytes.Buffer
buffer.WriteString(fmt.Sprintf("%s @> ARRAY[", key))
for arrIdx, i := range arr {
buffer.WriteStrin... |
package PDU
import (
"github.com/andrewz1/gosmpp/Data"
"github.com/andrewz1/gosmpp/Exception"
"github.com/andrewz1/gosmpp/Utils"
)
type EnquireLinkResp struct {
Response
}
func NewEnquireLinkResp() *EnquireLinkResp {
a := &EnquireLinkResp{}
a.Construct()
return a
}
func (c *EnquireLinkResp) Construct() {
d... |
package main
import (
"image"
"image/png"
"log"
"net/http"
"os"
)
type endpoint struct {
// store in a git repo?
// might help to survive cloudburst
counts map[string]int
source image.Image
}
// http://localhost:8080/counter/${{identifier}}
func (e *endpoint) ServeHTTP(w http.ResponseWriter, r *http.Reques... |
package main
import "fmt"
type T struct {
Name string
Port int
State State
}
type State int
const (
Running State = iota + 1
Stopped
Rebooting
Terminated
)
func (s State) String() string {
switch s {
case Running:
return "Running"
case Stopped:
return "Stopped"
case Rebooting:
return "Rebooting"... |
package article
import (
"context"
"errors"
"github.com/jmoiron/sqlx"
"time"
)
type pgStore struct {
db *sqlx.DB
}
func NewPgStorage(db *sqlx.DB) *pgStore {
return &pgStore{db: db}
}
func (p pgStore) UpdateArticle(ctx context.Context, article *Article) (id string, err error) {
query := `
update ad.articl... |
package application
import (
"fmt"
"github.com/akosgarai/opengl_playground/examples/model-loading/pkg/interfaces"
"github.com/go-gl/glfw/v3.3/glfw"
"github.com/go-gl/mathgl/mgl32"
)
const (
DEBUG = glfw.KeyH
)
type Camera interface {
Log() string
GetViewMatrix() mgl32.Mat4
GetProjectionMatrix() mgl32.Mat4
... |
package decode
import (
"testing"
"github.com/golang/go/src/fmt"
)
func TestEnDe(t *testing.T){
ru:=RSAUtils()
fmt.Println(ru.init())
fmt.Println(ru)
//公钥加密 私钥解密
eby,err:=ru.RsaEncrypt([]byte("hello world"),ru.PublicKey)
fmt.Println(err)
dby,err:=ru.RsaDecrypt(eby,ru.PrivateKey)
fmt.Println(string(dby),e... |
package main
import (
"context"
"fmt"
proto "micro_test/proto"
micro_client "github.com/micro/go-micro/client"
)
func main() {
// Create a new service. Optionally include some options here.
//service := micro.NewService(micro.Name("server.client"))
/*serviceName := "server.client"
service := micro.NewServic... |
package main
import (
"fmt"
"reflect"
)
func main() {
a:=1
var b string
fmt.Println(reflect.TypeOf(a)) // 打印数据类型
fmt.Println(reflect.TypeOf(b))
c := string(a) // 类型转换
fmt.Println(reflect.TypeOf(c))
//小案例 A
//编程实现107653秒是几天几小时几分钟几秒?
time := 107653
e:= time/60/60/24
fmt.Println(e)
fmt.Println("... |
package font
type Weight string
const WeightNormal = "normal"
const WeightBold = "bold"
const WeightBolder = "bolder"
const WeightLighter = "lighter"
const WeightInitial = "initial"
const WeightInherit = "inherit"
const Weight100 = "100"
const Weight200 = "200"
const Weight300 = "300"
const Weight400 = "400"
const W... |
package util
import (
"github.com/satori/go.uuid"
)
func CreateUUID() (string, error) {
newUUID, err := uuid.NewV4()
if err != nil {
return "", err
}
return newUUID.String(), nil
}
func ValidUUID(uuid string) bool {
return true
}
|
package camt
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document03900101 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:camt.039.001.01 Document"`
Message *CaseStatusReport `xml:"camt.039.001.01"`
}
func (d *Document03900101) AddMessage() *Cas... |
package router
import (
"dappapi/middleware"
"github.com/gin-gonic/gin"
)
func InitRouter() *gin.Engine {
r := gin.New()
middleware.InitMiddleware(r)
authMiddleware, _ := middleware.AuthInit()
// 注册系统路由
InitSysRouter(r, authMiddleware)
return r
}
|
package service
import (
"bytes"
"encoding/json"
"fmt"
"github.com/bearname/videohost/internal/common/infrarstructure/amqp"
"github.com/bearname/videohost/internal/common/util"
"github.com/bearname/videohost/internal/video-scaler/domain"
"github.com/bearname/videohost/internal/videoserver/domain/model"
log "gi... |
package main
import (
"fmt"
)
type TrackType uint32
const (
UnknownTrack TrackType = iota
AudioTrack
VideoTrack
SubtitleTrack
)
// encryption scheme type
var (
encryptionSchemeTypeCENC uint32 = 0x63656E63 // "cenc"
encryptionSchemeTypeCENS uint32 = 0x63656E73 // "cens"
encryptionSchemeTypeCBCS uint32 = 0x63... |
package problem
func Main() {
notSync()
syncWithMutex()
syncWithChan()
}
|
// Copyright (c) OpenFaaS Author(s) 2018. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package handlers
import (
"net/http"
"net/http/httptest"
"testing"
"time"
)
func Test_MakeNotifierWrapper_ReceivesHttpStatusInNotifier(t *testing.T)... |
// Wallet system
package ds
type Wallet struct {
bal int
}
func balance(w *Wallet) int {
return (*w).bal
}
func deposit(w *Wallet, amount int) {
(*w).bal += amount
}
|
package util_test
import(
"testing"
"util"
"fmt"
"time"
)
func Test_ParseDate(t *testing.T){
l := "201301"
d := util.ParseDate(l)
fmt.Println(d)
if d.Year() == 2013 && int(d.Month()) == 1 && d.Day() == 31 {
t.Log("Success to parse: ", l)
} else {
t.Error("Cannot parse:... |
package main
import "fmt"
/*
/* func number returns number
*/
func number() int {
return 75
}
func main(){
switch num:=number(); {
case num < 50:
fmt.Println("num less then 50")
fallthrough
case num < 100:
fmt.Println("num less then 100")
fallthrough
case num < 200:
fmt.Println("num less then 200")
}
... |
// Package imageutil is a collection of low-level image processing tools.
package imageutil
|
package main
import (
"io"
)
var _ = declareDay(9, func(part2 bool, inputReader io.Reader) interface{} {
if part2 {
return day09Part2(inputReader)
}
return day09Part1(inputReader)
})
func day09Part1(inputReader io.Reader) interface{} {
var computer computer
computer.init(inputReader)
go computer.run()
retu... |
/*
Challenge
Given a colour raster image* with the same width and height, output the image transformed under Arnold's cat map. (*details see below)
Definition
Given the size of the image N we assume that the coordinates of a pixel are given as numbers between 0 and N-1.
Arnold's cat map is then defined as follows:... |
package db_mysql
import (
"database/sql"
"fmt"
"github.com/astaxie/beego"
_ "github.com/go-sql-driver/mysql"
)
var Db *sql.DB
func ConnectDB(){
config :=beego.AppConfig
dbdriver :=config.String("db_driverName")
dbuser :=config.String("db_user")
dbpassword:=config.String("db_password")
dbip:=config.String("db... |
package main
import (
"fmt"
"image"
"image/color"
"image/png"
"math/rand"
"os"
"runtime/trace"
"strings"
"sync"
log "github.com/cihub/seelog"
"github.com/grindlemire/seezlog"
"github.com/jessevdk/go-flags"
"github.com/pkg/profile"
)
// Opts ...
type Opts struct {
File string `short:"f" long:"f... |
// 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... |
package main
func main() {
s := "abcdefg"
s1 := s[:3]
s2 := s[1:4]
s3 := s[2:]
println(s1, s2, s3)
}
|
// Package for declaring types that will be used by various other packages. This is useful
// for preventing import cycles. For example, pkg/pods depends on pkg/auth. If both
// wish to use pods.ID, an import cycle is created.
package types
type PodID string
func (p PodID) String() string {
return string(p)
}
|
// break on switch statements.
package main
import "fmt"
func main() {
loop:
for i := 0; i < 10; i++ {
switch i {
case 2:
fmt.Printf("%d break from switch\n", i)
break
case 3:
fmt.Printf("%d break from loop\n", i)
break loop
default:
fmt.Println(i)
}
}
}
|
package module
import (
"fmt"
"io"
"os"
"buddin.us/eolian/dsp"
"github.com/mitchellh/mapstructure"
)
func init() {
Register("Debug", func(c Config) (Patcher, error) {
var config struct {
RateDivisor int
Output io.Writer
}
if err := mapstructure.Decode(c, &config); err != nil {
return nil, ... |
package sshkeymanager
import (
"strings"
)
type User struct {
Name string
UID string
Home string
Shell string
}
var users []User
func (c *Client) GetUsers() ([]User, error) {
if err := c.NewSession(); err != nil {
return nil, err
}
defer c.CloseSession()
raw, err := c.Ses.CombinedOutput("cat /etc/pas... |
package main
import (
"fmt"
"sort"
)
func arrayPairSum(nums []int) int {
sort.Slice(nums, func(i, j int) bool {
return nums[i] < nums[j]
})
sum := 0
for i:=0; i<len(nums)/2; i++ {
sum += nums[2*i]
}
return sum
}
func main() {
fmt.Println(arrayPairSum([]int{1,4,3,2}... |
package main
import (
"context"
"fmt"
"log"
"net/http"
"github.com/sfomuseum/go-flags/flagset"
"github.com/aaronland/go-http-server"
)
func NewHandler() http.Handler {
fn := func(rsp http.ResponseWriter, req *http.Request) {
msg := fmt.Sprintf("Hello, %s", req.Host)
rsp.Write([]byte(msg))
}
h := http... |
package optionsgen_test
import (
"testing"
testcase "github.com/kazhuravlev/options-gen/options-gen/testdata/case-09-custom-validator"
"github.com/stretchr/testify/assert"
)
func TestOptionsWithCustomValidator(t *testing.T) {
t.Run("valid options", func(t *testing.T) {
opts := testcase.NewOptions(100, 19)
as... |
/*
Create a function that takes an array of strings and return an array, sorted from shortest to longest.
Examples
sortByLength(["Google", "Apple", "Microsoft"])
➞ ["Apple", "Google", "Microsoft"]
sortByLength(["Leonardo", "Michelangelo", "Raphael", "Donatello"])
➞ ["Raphael", "Leonardo", "Donatello", "Michelangelo... |
--- caddy.go.orig 2022-09-22 16:12:41 UTC
+++ caddy.go
@@ -824,6 +824,10 @@ func InstanceID() (uuid.UUID, error) {
return uuid.ParseBytes(uuidFileBytes)
}
+// VersionString uses a predefined version string to short-circuit
+// the Version() function below, to simplify vendor packaging.
+var VersionString string
+
... |
package wip
// Attachment is an uploaded file (seems to define an image)
type Attachment struct {
ID string `json:"id"`
URL string `json:"url"`
AspectRatio float32 `json:"aspect_ratio"`
Filename string `json:"filename"`
Size uint32 `json:"size"`
MimeType string `json:"mime_type... |
/*
Tencent is pleased to support the open source community by making Basic Service Configuration Platform 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 obtain... |
package main_test
import (
. "github.com/dgruber/playascii"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Template", func() {
Context("HTML generation", func() {
It("should generate the index.html", func() {
index, err := CreateIndexTemplate()
Ω(err).Should(BeNil())
Ω(ind... |
/*
* Copyright (c) 2020. Ant Group. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package daemon
import (
"fmt"
"os"
"path/filepath"
"github.com/pkg/errors"
"github.com/dragonflyoss/image-service/contrib/nydus-snapshotter/config"
"github.com/dragonflyoss/image-service/contrib/nydus-snaps... |
// +build ignore
package main
import (
"log"
"net/http"
"strings"
)
const dir = "."
func main() {
fs := http.FileServer(http.Dir(dir))
log.Print("Serving " + dir + " on http://localhost:8080")
http.ListenAndServe(":8080", http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
resp.Header().Add... |
package main
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"strings"
)
type DiskStats struct {
Name string
ReadsCompleted, WritesCompleted uint64
}
func GetDiskStats() ([]DiskStats, error) {
file, err := os.Open("/proc/diskstats")
if err != nil {
return nil, fmt.Errorf("Could not... |
/*
Your challenge for today is to create a program which is password protected, and wont open unless the correct user and password is given.
For extra credit, have the user and password in a seperate .txt file.
For even more extra credit, break into your own program :)
*/
package main
import (
"crypto/sha512"
"cr... |
package main
import "fmt"
func findMaxConsecutiveOnes(nums []int) int {
count := 0
max := 0
for _, v := range nums {
if v == 1 {
count++
}
if v == 0 {
if count > max {
max = count
}
count = 0
}
}
if count > max {
max = count
}
return max
}
func main() {
nums := []int{1, 1, 1, 1, 0... |
package myos
import (
"fmt"
"io"
"reflect"
"strings"
"testing"
)
func TestUnicode(t *testing.T) {
str := "Go 爱好者 "
fmt.Printf("The string: %q\n", str)
fmt.Printf(" => runes(char): %q\n", []rune(str))
// rune == int32 四个字节存储
fmt.Printf(" => runes(hex): %x\n", []rune(str))
fmt.Printf(" => ... |
// 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 main
import (
"fmt"
"strconv"
"strings"
)
type TreeNode struct {
left, right *TreeNode
data int
}
func serialize(root *TreeNode) string {
sxd := []string{}
stack := []*TreeNode{}
if root == nil {
return ""
}
stack = append(stack, root)
for len(stack) > 0 {
top := stack[len(stack)-1]
... |
package pg
import (
"encoding/json"
"fmt"
"strings"
. "grm-service/dbcentral/pg"
"applications/data-collection/types"
)
type MetaDB struct {
MetaCentralDB
}
// 添加数据记录
func (db MetaDB) AddDataObject(data, name, dataset, device, user, shpType string) error {
metajson := fmt.Sprintf(`
{
"full_valid" : fa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.