text stringlengths 11 4.05M |
|---|
package main
import (
"fmt"
"math/rand"
"sort"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func main() {
array := make([]int, 0)
for i := 0; i < 500; i++ {
num := rand.Intn(1000)
array = append(array, num)
}
//fmt.Println("---array----", array)
// 冒泡法
tBegin := time.Now().UnixNano()
fo... |
package currency
import (
"strconv"
)
// ConvertPenniesToDollarString takes a penny amount as
// an int64 and returns a dollar string representation
func ConvertPenniesToDollarString(amount int64) string {
// parse the pennies as a base 10 int
result := strconv.FormatInt(amount, 10)
// check if negative, will se... |
package user
import (
"GP/db"
"GP/model"
"database/sql"
"log"
)
func GetOneUser(id string) (userInfo []*model.User, err error) {
userInfo = []*model.User{}
querySql := "select id, username, nickname, role, phone, label, fonttype, fontcolor, isban from gp.user where id = ?;"
stmt, err := db.DB.Prepare(querySql)... |
package main
import "fmt"
func main() {
fmt.Println("sum is", 45+59)
fmt.Println("string concat of go and lang is", "go"+"lang")
fmt.Println("division of floats", 7.0/3, 7.0/3.0, 7/3.0)
fmt.Println("testing and, or operations", true || false, true && false)
}
|
package middleware
import (
"net/http"
"net/url"
"strings"
"github.com/gobuffalo/buffalo"
"github.com/gomods/athens/pkg/errors"
"github.com/gomods/athens/pkg/module"
"github.com/gomods/athens/pkg/paths"
)
// NewFilterMiddleware builds a middleware function that implements the
// filters configured in the filt... |
package main
import (
"github.com/beego/beego/v2/client/orm/migration"
)
// DO NOT MODIFY
type User_20210628_144749 struct {
migration.Migration
}
// DO NOT MODIFY
func init() {
m := &User_20210628_144749{}
m.Created = "20210628_144749"
migration.Register("User_20210628_144749", m)
}
// Run the migrations
fun... |
package frida_go
type RemoteDeviceOptions struct {
Certificate string
Origin string
Token string
KeepaliveInterval int
} |
package mysqldb
import (
"context"
"path/filepath"
"testing"
"time"
"github.com/jinmukeji/jiujiantang-services/service/auth"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
)
// TokenTestSuite 是 Token 的 testSuite
type TokenTestSuite struct {
suite.Suite
db *DbClient
}
// SetupSuite... |
package Problem0290
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
// tcs is testcase slice
var tcs = []struct {
pattern string
str string
ans bool
}{
{"abba", "dog cat cat dog", true},
{"abba", "dog cat cat fish", false},
{"aaaa", "dog cat cat dog", false},
{"abba", "dog dog dog ... |
package grap
import (
DDBB "github.com/siulfe/gql/Database"
"github.com/siulfe/gql/crypto"
"errors"
)
func (u *User) Create() error{
err := DDBB.GetDB().QueryRow(DDBB.CREATE_USER, u.Name,u.LastName,u.Identification,u.Age,u.Direccion.ID,u.Password,u.Rol).Scan(&u.ID)
return err
}
func (u *User) Delete() error{... |
package main
import "fmt"
const LIM = 40
func fibonacci() (func() int) {
back1, back2 := 0, 1
return func() int {
// 重新赋值
back1, back2 = back2, (back1 + back2)
return back1
}
}
func main() {
f := fibonacci() //返回一个闭包函数
var array [LIM]int
for i := 0; i < LIM; i++ {
array[i] = f()
}
fmt.Println(array)... |
package function
func NextPermutation(arr []int) bool {
// calculate the left index to swap
l := len(arr) - 2
for l >= 0 && arr[l] >= arr[l+1] {
l--
}
if l < 0 {
return false
}
// calculate the right index to swap
r := len(arr) - 1
for arr[l] >= arr[r] {
r--
}
// swap
arr[l], arr[r] = arr[r], arr[l]
... |
package machine
// RigStat is a status of machine
type RigStat struct {
GHS5s string
GHSAvarage string
MHS5s string
MHSAvarage string
KHS5s string
KHSAvarage string
Accepted string
Rejected string
HardwareErrors string
Utility string
System SystemStat
Devices []DeviceSt... |
package game
import (
"fmt"
"testing"
"github.com/stretchr/testify/require"
)
func TestSuit_Left(t *testing.T) {
checkSuit := func(s, expected Suit) func(*testing.T) {
return func(t *testing.T) {
require.Equal(t, expected, s.Left())
}
}
t.Run("Clubs", checkSuit(SuitClubs, SuitSpades))
t.Run("Diamonds"... |
package database
import (
"reflect"
"testing"
"github.com/DATA-DOG/go-sqlmock"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"github.com/sumelms/microservice-course/internal/course/domain"
utils "github.com/sumelms/microservice-course/tests"
)
var (
course = domain.Course{
ID: 1,
UUID: ... |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package helpers
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"fmt"
"math/big"
"net"
"time"
"golang.org/x/sync/errgroup"
log "github.com/sirupsen/logrus... |
package base
import (
"errors"
"fmt"
"gengine/context"
"gengine/internal/core"
"reflect"
)
//support map or array
type MapVar struct {
SourceCode
Name string // map name
Intkey int64 // array index
Strkey string // map key
Varkey string // array index or map key
}
func (m *MapVar) Evaluate(dc *context.D... |
package openssl
import (
"github.com/root-gg/utils"
)
// Config object
type Config struct {
Openssl string
Cipher string
Passphrase string
Options string
}
// NewOpenSSLBackendConfig instantiate a new Backend Configuration
// from config map passed as argument
func NewOpenSSLBackendConfig(params map[s... |
package auth
import (
"context"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
"github.com/gofor-little/xerror"
)
// ChangePassword changes a user's password.
//
// - Use auth.ForgotPassword if the user doesn't know their password.
//
// - Use auth.UpdateExpired... |
package i2pgateconfig
import (
"os"
"testing"
"github.com/RTradeLtd/go-garlic-tcp-transport"
fsrepo "github.com/ipfs/go-ipfs/repo/fsrepo"
)
var configPath = "./"
// Test_config tries to create a config file
func Test_Config(t *testing.T) {
err := os.Setenv("KEYS_PATH", configPath)
if err != nil {
t.Fatal(... |
package toggle
var Symbol = map[string]map[string]string{
"star": map[string]string{
"filled": "★",
"empty": "☆",
},
"flag": map[string]string{
"filled": "⚑",
"empty": "⚐",
},
"heart": map[string]string{
"filled": "♡",
"empty": "♡",
},
}
|
package schema
import (
"time"
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
)
// GroupBandwidth holds the schema definition for the GroupBandwidth entity.
type GroupBandwidth struct {
ent.Schema
}
// Fields of the GroupBandwidth.
func (GroupBandwidth) Fields() []ent.Field {
return []e... |
package main
import (
"errors"
"fmt"
"strconv"
"strings"
)
// This file is the most likely to change between years and contains specific intcode instruction implementations
const IntCodeCpy = "cpy";
const IntCodeInc = "inc";
const IntCodeDec = "dec";
const IntCodeJump = "jnz";
func ParseIntcodeInstruction(line ... |
package resources
import (
"code.cloudfoundry.org/cli/cf/api/resources"
"encoding/json"
"fmt"
"github.com/andreasf/cf-mysql-plugin/cfmysql/models"
"strconv"
"strings"
)
type ServiceBindingResource struct {
resources.Resource
Entity ServiceBindingEntity
}
type ServiceBindingEntity struct {
AppGUID ... |
package main
import (
"example.com/greetings"
"fmt"
"log"
//"rsc.io/quote"
)
func main() {
//fmt.Println(quote.Go())
log.SetPrefix("greetings: ")
//log.SetFlags(0)
explore_multiple_return_values()
explore_slice()
explore_map()
}
func explore_multiple_return_values() {
message, err := greetings.Hello("R... |
/*
Images can be described as 3D arrays.
// This image has only one white pixel:
[
[[255, 255, 255]]
]
// This one is a 2 by 2 black image:
[
[[0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0]]
]
Your task is to create a function that takes a 3D array representation of an image and returns the grayscale version ... |
package main
import(
"fmt"
"errors"
"os"
"net"
"net/rpc"
"math"
)
type Args struct{
A, B int
}
type Response struct{
Quo, res int
}
type Math byte
func (m*Math)Add(args *Args, res *int) error {
*res = args.A + args.B
return nil
}
func (m *Math) Divide(args *Args, res *Response) error {
if args.B ==... |
/*
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 models
type RankModel struct {
FBId string `json:"fb_id" bson:"fb_id"`
Name string `json:"name" bson:"name"`
Data []LevelModel `json:"data" bson:"data"`
} |
package skylark
import (
"github.com/google/skylark"
"github.com/google/skylark/skylarkstruct"
"github.com/pkg/errors"
)
// inconsistent behaviour described here
// https://docs.bazel.build/versions/master/skylark/rules.html#files
// https://docs.bazel.build/versions/master/skylark/lib/ctx.html#outputs
func proces... |
// Copyright (c) 2020 by meng. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
/**
* @Author: meng
* @Description:
* @File: condition
* @Version: 1.0.0
* @Date: 2020/4/9 20:23
*/
package base_behavior
import (
"math/rand"
"time"
... |
package model
import (
"context"
"github.com/k-komarov/passbase-currency-api/internal/pkg/constants"
)
func ProjectFromContext(ctx context.Context) *Project {
if p, ok := ctx.Value(constants.CTX_PROJECT).(*Project); ok {
return p
}
return nil
}
|
package api
import (
"github.com/kataras/iris/v12"
"github.com/qor/admin"
"github.com/qor/qor"
"go-tenancy/config/application"
"go-tenancy/config/db"
"go-tenancy/models/users"
)
// New new api app
func New(config *Config) *App {
if config.Prefix == "" {
config.Prefix = "/api"
}
return &App{Config: config}
... |
package acronym
import (
"strings"
"unicode"
)
// Abbreviate will create an acronym of the given string
// hyphenated words are treated as separate words
func Abbreviate(s string) (acronym string) {
var abbreviation []byte
s = strings.Replace(s, "-", " ", -1)
s = strings.ToUpper(s)
trimmedText := strings.Split(... |
// 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 main
import "fmt"
// https://leetcode-cn.com/problems/word-search/
func exist(board [][]byte, word string) bool {
n := len(board)
if n == 0 {
return false
}
m := len(board[0])
if m == 0 {
return false
}
mark := make([]bool, n*m)
st := &wordStack{nums: make([]int, 0, 3*len(word))}
var search fu... |
/*
* Copyright (c) 2020 - present Kurtosis Technologies LLC.
* All Rights Reserved.
*/
package services
import (
"github.com/kurtosis-tech/kurtosis-go/lib/services"
)
type ExampleService interface {
services.Service
GetHelloWorldSocket() Socket
}
|
package weather_provider
import (
"interface-testing/api/clients/restclient"
"interface-testing/api/domain/weather_domain"
"io/ioutil"
"net/http"
"os"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
var (
getRequestFunc func(url string) (*http.Response, error)
)
type getClientMock struct{}
//We... |
// Bruteforce
package main
import "fmt"
import _ "math/big"
import "github.com/roessland/gopkg/mathutil"
func main() {
var min_value float64 = 2.0/5.0
var max_value float64 = 3.0/7.0
var D int64 = 1000000
// Closest value
var max_f float64 = 0.0
for d := int64(1); d <= D; d++ {
min_n... |
/*
Copyright 2011 Google 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 in writing, software
di... |
// Copyright (c) 2020 by meng. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
/**
* @Author: meng
* @Description:
* @File: idecorate
* @Version: 1.0.0
* @Date: 2020/4/9 15:46
*/
package interf
/************************************... |
package services
import (
"strings"
"github.com/ne7ermore/gRBAC/common"
"github.com/ne7ermore/gRBAC/plugin"
)
func Build(s plugin.Store) {
s.Build()
// init permissions
p := s.GetPermissionPools()
if err := initPerm(p); err != nil {
panic(err)
}
// init roles
r := s.GetRolePools()
if err := initRole(r... |
package mhfpacket
import (
"errors"
"github.com/Andoryuuta/Erupe/network"
"github.com/Andoryuuta/Erupe/network/clientctx"
"github.com/Andoryuuta/byteframe"
)
// TODO(Andoryuuta): Make up a name for this packet, not reserved anymore. Called "Is_update_guild_msg_board"
// MsgSysReserve203 represents the MSG_SYS_r... |
package version
import (
"fmt"
"runtime"
)
var (
ver string //nolint:gochecknoglobals
date string //nolint:gochecknoglobals
commit string //nolint:gochecknoglobals
)
// Info - version info.
type Info struct {
Version string
Date string
Commit string
}
// GetInfo - get version stamp information.
fun... |
package stack
import "testing"
func TestNewStack(t *testing.T) {
stack := NewStack()
stack.Push("a")
stack.Push("b")
stack.Push("c")
stack.Push("d")
stack.Push("e")
stack.Push("f")
t.Log(stack.Top())
t.Log(stack.Pop())
t.Log(stack.Pop())
t.Log(stack.Pop())
t.Log(stack.Pop())
t.Log(stack.Pop())
t.Log(sta... |
package html
import (
"github.com/elliotchance/gedcom"
"github.com/elliotchance/gedcom/html/core"
"io"
)
// IndividualInList is a single row in the table of individuals on the list
// page.
type IndividualInList struct {
individual *gedcom.IndividualNode
document *gedcom.Document
visibility LivingVisibility
... |
// Copyright 2016 Walter Schulze
//
// 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... |
package main
// https://leetcode-cn.com/problems/create-sorted-array-through-instructions/
// 树状数组
func createSortedArray(ins []int) int {
const mod = 1000000007
N := len(ins)
NN := 200000
tree := make([]int, NN+1)
add := func(i int) {
for i <= NN {
tree[i]++
i += i & -i
}
}
sum := func(i int) int {... |
package utils
import (
"github.com/Shopify/sarama"
"github.com/howbazaar/loggo"
"strings"
"os"
"os/signal"
"encoding/json"
"go-temp-project/model"
)
var producer sarama.AsyncProducer
var signals chan os.Signal
var kafkaUp bool
func KafkaInit() {
config := sarama.NewConfig()
var err error
producer, err = s... |
package main
import (
"log"
"time"
"github.com/dustin/go-broadcast"
)
// Example of a simple broadcaster sending numbers to two workers.
func main() {
// create the broadcaster
broadcaster := broadcast.NewBroadcaster(100)
// start workers
go worker(1, broadcaster)
go worker(2, broadcaster)
// sending 5 m... |
package main
import "testing"
func BenchmarkPredict(b *testing.B) {
bst, err := NewBooster()
if err != nil {
b.Fatal(err)
}
defer bst.Free()
err = bst.LoadModel("../model/dump.model")
if err != nil {
b.Fatal(err)
}
dm, err := NewDMatrix("../data/test_libsvm_oneline.txt")
if err != nil {
b.Fatal(err)
... |
package main
import (
"fmt"
"reflect"
)
func makeFunction(f interface{}) interface{} {
rf := reflect.TypeOf(f)
if rf.Kind() != reflect.Func {
return nil
}
vf := reflect.ValueOf(f)
wrapperF := reflect.MakeFunc(rf, func(in []reflect.Value) []reflect.Value {
// start := time.Now()
out := vf.Call(in)
// e... |
package example
func main() {
o, q, t, err := CreateOrder("product id", "customer id", "shipment id")
if err != nil {
panic(err)
}
}
// Return Transaction to show the transaction info in dashboard
func CreateOrder(productID, customerID, shipmentID string) (Order, Quote, Transaction, error) {
return Order{}, Quo... |
package BLC
import (
"bytes"
"crypto/ecdsa"
"crypto/rand"
"crypto/sha256"
"encoding/gob"
"encoding/hex"
"log"
)
//UTXO
type Transaction struct {
// 1. 交易 Hash
TxHash []byte
// 2. 输入
Vins []*TXInput
// 3. 输出
Vouts []*TXOutput
}
// 判断是否创世区块的交易
func (tx *Transaction) IsCoinbaseTransactions() bool {
ret... |
package version
const Version = "0.1.3+git"
|
package krong
import (
"fmt"
)
type Agent struct {
Endpoint string
Command string
Secret string
}
func (a *Agent) String() string {
return fmt.Sprintf("Endpoint: %s, Command: %s, Secret: %s", a.Endpoint, a.Command, a.Secret)
}
|
package main
import "fmt"
// func functionname(parameters type) returntype {
// //body
// }
//Area function ....
func Area(w, l float64) float64 {
result := w * l
return result
}
//Perimeter function ...
func Perimeter(w float64, l float64) float64 {
result := 2 * (w + l)
return result
}
func geometryMetrics(... |
package eviction
import (
"context"
"fmt"
"sort"
"strconv"
"strings"
"time"
autoscalingv1alpha1 "github.com/containers-ai/alameda/operator/api/v1alpha1"
utilsresource "github.com/containers-ai/alameda/operator/pkg/utils/resources"
"github.com/containers-ai/alameda/pkg/utils"
logUtil "github.com/containers-a... |
package scheduler
import (
"context"
"time"
"github.com/andywow/golang-lessons/lesson-calendar/internal/calendar"
"github.com/andywow/golang-lessons/lesson-calendar/internal/calendar/msgsystem"
"go.uber.org/zap"
"github.com/andywow/golang-lessons/lesson-calendar/internal/calendar/repository"
)
// options
typ... |
package atlas
import (
"testing"
. "github.com/smartystreets/goconvey/convey"
)
type tObjStr struct {
X string
}
func TestTransformBuilder(t *testing.T) {
Convey("Building atlases using transforms:", t, func() {
Convey("string->struct->string happy path should build without error", func() {
_, err := Build... |
/*
* @lc app=leetcode.cn id=8 lang=golang
*
* [8] 字符串转换整数 (atoi)
*/
// @lc code=start
package main
import "fmt"
import "math"
// import "strings"
func myAtoi(s string) int {
if len(s) == 0 {
return 0
}
size := len(s)
i := 0
for i < size && s[i] == ' ' {
i++
}
if i == size {
return 0
}
s = s[i:]
... |
// Copyright 2016 Walter Schulze
//
// 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... |
package env
import (
"fmt"
"os"
"strings"
)
// GetStringSlice extracts slice of strings value with format "foo,bar,baz" from env.
// if not set, returns default value.
func GetStringSlice(key string, def []string) []string {
s, ok := os.LookupEnv(key)
if !ok {
return def
}
if len(s) == 0 {
return []string... |
package main
import "testing"
// +build integration
func TestFullFlow(t *testing.T) {
//TODO add test for entire flow using local dynamo and mocked sqs
} |
package usecase
import (
"fmt"
"strings"
"time"
entity "silverfish/silverfish/entity"
"github.com/PuerkitoBio/goquery"
"github.com/axgle/mahonia"
"github.com/sirupsen/logrus"
)
// FetcherBookbl export
type FetcherBookbl struct {
Fetcher
charset string
decoder mahonia.Decoder
}
// NewFetcherBookbl export
... |
package main
import (
"encoding/json"
"log"
"net/http"
"time"
)
const (
tree = "Sequoia"
)
type resp struct {
MyFavouriteTree string `json:"myFavouriteTree"`
}
func main() {
staticResponse := resp{tree}
http.HandleFunc(
"/tree",
func(w http.ResponseWriter, r *http.Request) {
log.Printf("\"%s\" reque... |
package main
import "fmt"
func strStr(haystack string, needle string) int {
l1 := len(haystack)
l2 := len(needle)
for i := 0; i+l2 <= l1; i++ {
if string(haystack[i:i+l2]) == needle {
return i
}
}
return -1
}
func main() {
s1 := "aaabbbcdefff"
s2 := "bbcd"
fmt.Println(strStr(s1, s2))
}
|
package cpu
import (
"log"
"github.com/cgimenes/gomenes-boy/hardware/cpu/registers"
"github.com/cgimenes/gomenes-boy/hardware/memory"
"github.com/cgimenes/gomenes-boy/hardware/types"
)
type Instruction struct {
cycles uint8
exec func()
}
type CPU struct {
mmu memory.MMU
registers registers.Registers
}
func ... |
package repository
import (
db "bareksa-test/database"
fx "bareksa-test/function"
md "bareksa-test/model"
st "bareksa-test/struck"
"context"
)
type TagsRepository struct {
DB db.Database
}
func InitiateTagsRepository(db db.Database) md.TagsRepository {
return &TagsRepository{
DB: db,
}
}
func (r *TagsRepo... |
package main
type land struct {
r, c int
}
func numIslands(grid [][]byte) int {
var lands []*land
mark := make([][]bool, len(grid))
for i := 0; i < len(grid); i++ {
mark[i] = make([]bool, len(grid[i]))
for j := 0; j < len(grid[i]); j++ {
if grid[i][j] == '1' {
lands = append(lands, &land{i, j})
}
... |
package httptools
import (
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"text/template"
"time"
"github.com/elitah/fast-io"
"github.com/elitah/utils/bufferpool"
)
const (
flagOutput = iota
flagDebug
flagMax
flagOutputE... |
package main
import (
"fmt"
)
type S1 struct{}
func (s *S1) M() string {
return "from S1.M"
}
type S2 struct {
*S1
}
func main() {
s := new(S2)
fmt.Println(s.M())
fmt.Println(s.S1.M())
}
|
package apis
import (
"math"
"net/url"
"strconv"
"github.com/ololko/simple-HTTP-server/pkg/events/models"
log "github.com/sirupsen/logrus"
)
func fillRequestStruck(u *url.URL) (models.RequestT, error) {
q := u.Query()
var to int64 = math.MaxInt32
var from int64 = math.MinInt32
var err error
if q.Get("from... |
// Inspired by go-bindata, but that seemed too heavyweight.
package main
import (
"flag"
"fmt"
"os"
"io"
"encoding/base64"
)
func main() {
flag.Parse()
target, err := os.OpenFile("data_" + flag.Arg(0) + ".go", os.O_WRONLY | os.O_TRUNC | os.O_CREATE, os.ModePerm)
if err != nil {
panic(err)
}
fmt.Fprintln(... |
/*
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 generator
import (
"bufio"
"fmt"
"io"
"math/rand"
"os"
"strconv"
"strings"
)
type City struct {
Name string
CountryCode string
Country string
Latitude float32
Longitude float32
Ip string
}
func ReadCitiesFromFile(fileName string) ([]City, error) {
var cities []City
fil... |
package server
import (
"fmt"
"github.com/garyburd/redigo/redis"
"github.com/golang/glog"
"time"
)
type RedisConn struct {
host string
port int32
hp string
connTimeOut int32
sockTimeOut int32
database string
passwd string
ctx redis.Conn // is a interface
}
func (rc ... |
package main
import (
"golang.org/x/tour/pic"
)
func Pic(dx, dy int) [][]uint8 {
dySlice := make([][]uint8, dy)
for outerIndex := range dySlice {
dySlice[outerIndex] = make([]uint8, dx)
for innerIndex := range dySlice[outerIndex] {
dySlice[outerIndex][innerIndex] = uint8((innerIndex ^ outerIndex) * (inne... |
package service
import (
"server-monitor-admin/global"
"server-monitor-admin/model"
"server-monitor-admin/model/request"
"server-monitor-admin/utils"
)
func ListServerGroup(page *request.QueryServerGroup) {
var projects []model.SysServerGroup
db := global.DB.Limit(page.Limit).Offset(page.GetOffset()).Order("cre... |
package oss
import (
"bytes"
"encoding/base64"
"errors"
"fmt"
"io"
"mime/multipart"
"net/textproto"
"os"
"path"
"strings"
)
// PostOption is the option type for configuration multipart.Writer
type PostOption func(*multipart.Writer) error
// PostObject posts an object to OSS in MIME multipart format
func (a... |
package main
import (
"fmt"
"github.com/dah8ra/ch7/eval713"
)
func main() {
expr, _ := eval713.Parse("1+2*3-4/8")
fmt.Println(expr)
env := eval713.Env{"x": 1, "y": 2}
expr.String(env)
}
|
// Copyright 2021 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 discord
import (
"fmt"
"math"
"math/rand"
"github.com/bwmarrin/discordgo"
)
func (b *Bot) specials(s *discordgo.Session, m *discordgo.MessageCreate) {
if m.Author.ID == s.State.User.ID || m.Author.Bot {
return
}
if b.startsWith(m, "rob") {
b.checkuser(m)
if !(len(m.Mentions) > 0) {
s.Channe... |
package api
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"testing"
"time"
"github.com/jinzhu/gorm"
)
func TestCheckSchedules(t *testing.T) {
// create dummy db
f, _ := ioutil.TempFile("", "")
db, err := gorm.Open("sqlite3", f.Name())
defer os.Remove(f.Name())
defer db.Close()
if err != nil ... |
package util
// Abs returns the absolute value of x.
func Abs(x int) int {
if x < 0 {
return -x
}
return x
}
func TowardZero(num int) int {
if num == 0 {
return 0
} else {
if num < 0 {
return num + 1
} else {
return num - 1
}
}
}
func Max(a int, b int) int {
if a > b {
return a
} else {
r... |
package main
import (
"fmt"
"math/rand"
"net/http"
"time"
"github.com/ajvb/kala/client"
"github.com/ajvb/kala/job"
)
// Manager is the basic unit to represent consumer to maintain their own worker
type Manager struct {
ID string
Name string
Workers []Worker
}
// Worker represents the base simulatio... |
package main
import (
"bitbucket.org/kyrra/sandbox/auth"
"flag"
"fmt"
)
func main() {
listen := flag.String("listen", ":8080", "Hostname and address to listen on")
source := flag.String("datasource", "users.json", "Filename to load JSON user data from")
flag.Parse()
err := auth.Serve(*listen, *source)
if err... |
//go:generate go run gen/uikit.go
//go:generate go fmt
package uikit
|
package list
import "errors"
var (
outRangeError = errors.New("out of range")
)
type LinkList struct {
headNode *Node
len int
}
func (l *LinkList) IsEmpty() bool {
return l.len == 0
}
func (l *LinkList) Length() int {
return l.len
}
func (l *LinkList) GetHeadNode() *Node {
return l.headNode
}
// 从头部增加
func... |
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use ... |
// Licensed to SolID under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. SolID licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compli... |
package common
import (
"fmt"
)
// APIError define API error when response status is 4xx or 5xx
type APIError struct {
Code int64 `json:"code"`
Message string `json:"msg"`
}
// Error return error code and message
func (e APIError) Error() string {
return fmt.Sprintf("<APIError> code=%d, msg=%s", e.Code, e.Me... |
package main
import (
"fmt"
"os"
)
func init() {
os.Args = append(os.Args, "-local", "u=admin", "--help")
}
func main() {
cmd := len(os.Args[0])
argCount := len(os.Args[1:])
fmt.Printf("Program Name: %s\n", cmd)
fmt.Printf("Total Arguments: %d\n", argCount)
for i, a := range os.Args[1:] {
fmt.Printf("Arg... |
package main
import (
"encoding/json"
"fmt"
)
/*
@Time : 2020/6/26 3:17 下午
@Author : audiRS7
@File : 2使用map转json
@Software: GoLand
*/
//2、使用map[string]interface{}描述于谦并转json
func main() {
dataMap := make(map[string]interface{})
dataMap["name"] = "于谦"
dataMap["age"] = 50
dataMap["gender"] = "male"
dataMap["hobby... |
package types
// UnemploymentClaims holds the data for unemployment claims based on OAED.
type UnemploymentClaims struct {
Unemployed int `json:"unemployed" fake:"{number:5000,10000}"`
Benefits int `json:"benefits" fake:"{number:1000,5000}"`
AsOfDate string `json:"asofdate" fake:"{year}-{month}-{day}" for... |
/*
Copyright 2018 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 repository_test
import (
"testing"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
"github.com/indrasaputra/aptx/internal/repository"
mock_repository "github.com/indrasaputra/aptx/test/mock/repository"
)
type HealthCheckerExecutor struct {
checker *repository.HealthChecker
deps ... |
/*
* Copyright @ 2020 - present Blackvisor Ltd.
*
* 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 l... |
package euler
import "testing"
func TestQuestion2(t *testing.T) {
v := Question2()
if v != 4613732 {
t.Error(" Expected 4613732, got ", v)
}
}
|
package main
import (
"fmt"
"go_solidity/erc20"
"go_solidity/solidity"
"github.com/ethereum/go-ethereum/common"
)
var (
key string = `{"address":"e1975b35b3db24671cef3d7527797ab09ada0f95","crypto":{"cipher":"aes-128-ctr","ciphertext":"7c7c2b398cb7426238772cd3242bb6109339cca2c43616a5be9001f13... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.