text stringlengths 11 4.05M |
|---|
package coinpayments
import "net/url"
//getBasicInfoResponse is the api response of a "get_basic_info" call
type getBasicInfoResponse struct {
Username string `json:"username"`
MerchantID string `json:"merchant_id"`
Email string `json:"email"`
PublicName string `json:"public_name"`
}
//GetBasicInfo calls ... |
package machinery
import "k8s.io/client-go/tools/clientcmd/api"
func (d *Diff) Apply(existing, incoming *api.Config, handler ConflictResolver) error {
for _, item := range d.Items {
// isComplex := (item.ChangeType & ChangeTypeComplex) != 0
switch {
case (item.ChangeType & ChangeTypeNew) != 0:
clusterName :... |
package field
import (
"encoding/binary"
"fmt"
"io"
"time"
)
// StartTime is the date/time the track started playing in Serato.
type StartTime struct {
header *Header
data []byte
}
// Value returns the start time.
func (f *StartTime) Value() time.Time {
ts := binary.BigEndian.Uint32(f.data)
return time.Uni... |
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestStart(t *testing.T) {
gps := gpsTracker{}
assert.NotNil(t, gps)
}
|
package mongodb
import (
"context"
"log"
"os"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type MongoDB struct {
conn *mongo.Client
}
func New() *MongoDB {
uri := os.Getenv("MONGO_URI")
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
def... |
package api
import "errors"
var userIDValue = 0
var userDataStore = []user{}
//UserDao exposes the methods to be able to store everything in the database
type UserDao interface {
isEmailIDUnique(email string) (bool, error)
saveUser(u *UserSignUpRequest)
}
//InMemoryUserDao handles the user populationg mechanism ... |
package main
import (
"encoding/json"
)
const configFile = ".deltarc"
// Config represents user-provided options (via the file specified by configFile)
type Config struct {
Context *int `json:"context"`
ShowEmpty *bool `json:"showEmpty"`
ShouldCollapse *bool `json:"shouldCollapse"`... |
// A file will only be deleted from disk once all hard links are removed.
package main
import (
"fmt"
"log"
"os"
)
func main() {
// Create a hard link. We will create two file names that point to the same
// contents, changing the contents of one will change the other.
// Deleteing/renaming one will not affect... |
package dev
import (
"encoding/json"
"errors"
"flag"
"fmt"
"github.com/open-horizon/anax/cli/cliutils"
cliexchange "github.com/open-horizon/anax/cli/exchange"
"github.com/open-horizon/anax/cli/register"
"github.com/open-horizon/anax/cutil"
"github.com/open-horizon/anax/events"
"github.com/open-horizon/anax/e... |
package cos418_hw1_1
import (
"bufio"
"io"
"os"
"strconv"
)
// Sum numbers from channel `nums` and output sum to `out`.
// You should only output to `out` once.
// Do NOT modify function signature.
func sumWorker(nums chan int, out chan int) {
// TODO: implement me
// HINT: use for loop over `nums`
result := 0... |
/*
* Copyright (c) 2020 - present Kurtosis Technologies LLC.
* All Rights Reserved.
*/
package basic_datastore_test
import (
"github.com/kurtosis-tech/kurtosis-go/lib/networks"
"github.com/kurtosis-tech/kurtosis-go/lib/services"
"github.com/kurtosis-tech/kurtosis-go/lib/testsuite"
"github.com/kurtosis-tech/kur... |
package three
func Three() string {
return "three"
}
|
package filters
import (
"topazdev/stocks-game-api/app/controllers"
"topazdev/stocks-game-api/app/models"
"github.com/revel/revel"
"gopkg.in/mgo.v2/bson"
"strings"
)
// AuthFilter ...
func AuthFilter(c *revel.Controller, fc []revel.Filter) {
if strings.Contains(c.Request.URL.String(), "@tests") {
fc[0](c, fc[... |
package model
import (
"database/sql"
//"github.com/CourseComment/conf"
_ "github.com/go-sql-driver/mysql"
//"os"
"time"
)
// var (
// db *sql.DB
// )
// func init() {
// db = conf.DB
// }
type Lecture struct {
Id idtype
Course
Professor
Student_score float32
Level float32
Student... |
package minikube
import (
"bytes"
b64 "encoding/base64"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"text/template"
"github.com/docker/machine/libmachine/state"
"github.com/hashicorp/terraform/helper/schema"
"k8s.io/minikube/cmd/minikube/cmd"
"k8s.io/minikube/pk... |
package person
type Person struct {
ID string
Name string
LastName string
Age int
}
|
package main
// hack in imports to make godep happy about some binaries we vendor
import (
_ "github.com/jteeuwen/go-bindata/go-bindata"
)
func main() {}
|
package main
import "fmt"
func main() {
fmt.Println("Valid Parenthesis String")
doTest("(())(())(((()*()()()))()((()()(*()())))(((*)()")
doTest("(((()*())))((()(((()(()))()**(*)())))())()()*")
doTest("(()())")
doTest("")
doTest("(())")
doTest("(***")
doTest("((**")
doTest("((***))(((")
doTest("((***)***)((... |
package main
import "fmt"
// Panic function adalah function yg bisa kita gunakan untuk menghentikan program
// Panic function biasanya dipanggil ketika terjadi error pada saat program kita berjalan
// Saat panic function dipanggil, program akan terhenti, namun defer function tetap akan dieksekusi
func endApp() {
fm... |
package controllers
import (
"github.com/labstack/echo/v4"
"github.com/minuchi/go-echo-auth/lib"
userService "github.com/minuchi/go-echo-auth/services/user"
"gorm.io/gorm"
"net/http"
"time"
)
type (
loginRequest struct {
Email string `json:"email" validate:"required,email"`
Password string `json:"passwo... |
package worker
import (
"log"
"os"
"github.com/agusbasari29/Skilltest-RSP-Akselerasi-2-Backend-Agus-Basari/tasks"
"github.com/hibiken/asynq"
)
func Workers() {
r := asynq.RedisClientOpt{Addr: os.Getenv("REDIS_ADDR_PORT")}
srv := asynq.NewServer(r, asynq.Config{
Concurrency: 10,
})
mux := asynq.NewServeMux... |
package tumblr
import (
"bytes"
"encoding/json"
"net/http"
"net/url"
)
const (
// Version is the current version of this lib
Version = "0.0.1"
// BaseURL is the shared path to the tumblr api
BaseURL = "http://api.tumblr.com/v2/"
// UserAgent is the user agent when making requests
UserAgent = "github.com/les... |
package controllers
import (
"bwa-startup/auth"
"bwa-startup/helpers"
"bwa-startup/users"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
type userController struct {
userService users.Service
authService auth.Service
}
func NewUserController (userService users.Service, authService auth.Service) *userControl... |
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
type job struct {
x int64
}
type result struct {
*job
result int64
}
var jobChan = make(chan *job, 100)
var resultChan = make(chan *result, 100)
var wg sync.WaitGroup
func a(a chan<- *job) {
defer wg.Done()
for {
x := rand.Int63()
newJob := &job{
... |
package lecimg
import (
"image"
"image/color"
"log"
"testing"
)
func testAutoCrop(t *testing.T, img image.Image, option AutoCropOption, expectedWidth, expectedHeight int) {
// Run Filter
result := NewAutoCropFilter(option).Run(NewFilterSource(img, "filename", 0))
// Test result image size
destBounds := resul... |
package main
import (
"fmt"
"time"
)
// Default unbuffered
func main() {
channel := make(chan string, 1)
// buffer = 1 so sender goroutine in this case following func doesnt block
// if we add channel <- "test2" to following func, buffer will be filled so func will be blocked
go func() {
channel <- "test"
... |
package util
import (
"testing"
"fmt"
"flag"
)
func TestConfig(t *testing.T) {
// NewConfigWithFile("/Users/derek/go/src/sixedu/data/config.json")
// c := GetConfig()
fmt.Println("")
args := []string{
"-conf=这是测试命令行参数",
}
flag.CommandLine.Parse(args)
GetConfig()
... |
/*
Copyright 2021 The KubeVela Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softw... |
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/hex"
"fmt"
"os"
)
// To encode publicKey use:
// publicKeyBytes, _ = x509.MarshalPKIXPublicKey(&private_key.PublicKey)
// Private Key:
// 3081a40201010430d35b96ee7ced244b5a47de8968b07ecd38a6dd756f0ffb40a72ccd5895e96f2... |
package gotten
import (
"github.com/Hexilee/gotten/headers"
"io"
"net/http"
"net/url"
)
type (
Response interface {
StatusCode() int
Header() http.Header
Body() io.ReadCloser
ContentType() string
Cookies() []*http.Cookie
// Location returns the URL of the response's "Location" header,
// if prese... |
package http
import (
"context"
"fmt"
"github.com/tppgit/we_service/pkg/auth"
"github.com/tppgit/we_service/pkg/services"
"net/http"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"google.golang.org/grpc"
)
type HandlerFunc func(ctx context.Context, mux *runtime.ServeMux, address string, opts []grpc.DialOp... |
package main
import (
"net/http"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
func main() {
// Echo Instance
e := echo.New()
//Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())
// Route => handler
e.GET("/", func(c echo.Context) error... |
package queries
import (
"database/sql"
"log"
"gitlab.com/semestr-6/projekt-grupowy/backend/obsluga-formularzy/attributes/models"
"gitlab.com/semestr-6/projekt-grupowy/backend/obsluga-formularzy/configuration"
)
const EDIT_FACTOR_ATTRIBUTE_SQL = `
UPDATE attributes."Attributes"
SET
"AttributeEnumId" = $1
,"Sou... |
package service
import (
"math"
"github.com/helloferdie/stdgo/db"
"github.com/helloferdie/stdgo/language"
"github.com/helloferdie/stdgo/libresponse"
"github.com/helloferdie/stdgo/libslice"
"github.com/helloferdie/stdgo/libvalidator"
)
// FormatOutput -
func FormatOutput(obj *language.Language, format map[strin... |
package model
import "time"
type RealAgent struct {
Name string `json:"name"`
Version string `json:"version"`
Status string `json:"status"`
Timestamp string `json:"timestamp"`
}
type DesiredAgent struct {
Name string `json:"name"`
Version string `json:"version"`
Tarball string `json:"tarball"`
Md... |
package data_test
import (
"testing"
"math/rand"
data "github.com/bgokden/veri/data"
)
func randFloats64(min, max float64, n int) []float64 {
res := make([]float64, n)
for i := range res {
res[i] = min + rand.Float64()*(max-min)
}
return res
}
func randFloats32(min, max float32, n int) []float32 {
res :=... |
package nes
import (
"encoding/gob"
"log"
)
type Mapper4 struct {
*Cartridge
console *Console
register byte
registers [8]byte
prgMode byte
chrMode byte
prgOffsets [4]int
chrOffsets [8]int
reload byte
counter byte
irqEnable bool
}
func NewMapper4(console *Console, cartridge *Cartridge... |
package model
import (
"database/sql"
"goTodo/initialization"
"goTodo/mylog"
"goTodo/util"
)
type UserModel struct {
Username string `form:"username"`
Password string `form:"password"`
}
type RegisterModel struct {
UserModel
PasswordAgain string `form:"passwordAgain"`
}
func (user *UserModel) ValidUser() bo... |
package s3
import (
"fmt"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"k8s.io/apimachinery/pkg/util/uuid"
corev1 "k8s.io/api/core/v1"
installer "... |
/*
* Copyright 2018, CS Systemes d'Information, http://www.c-s.fr
*
* 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 requir... |
package eks
import (
"github.com/aws/aws-sdk-go/service/ec2/ec2iface"
api "github.com/weaveworks/eksctl/pkg/apis/eksctl.io/v1alpha5"
"github.com/weaveworks/eksctl/pkg/ssh"
)
// A NodeGroupService provides helpers for nodegroup creation
type NodeGroupService struct {
cluster *api.ClusterConfig
ec2API ec2iface.EC... |
package main
import (
"fmt"
)
func main() {
//2 ways to declare an array
//1st
var arr [3]int
arr[0] = 1
arr[1] = 2
arr[2] = 3
fmt.Println(arr)
//Declare with initialize
arr2 := [3]int{2, 3, 4}
fmt.Println(arr2)
//Slice
//Dynamic Array
slice := []int{1, 2, 3}
fmt.Println("Slice Value", slice)
//we... |
package map_slice_array
import (
"fmt"
"gengine/builder"
"gengine/context"
"gengine/engine"
"reflect"
"testing"
"time"
)
type MS struct {
MII *map[int]int
MSI map[string]int
MIS map[int]string
}
const m_1 = `
rule "map test" "m dec"
begin
//map in struct
a = -1
MS.MII[-1] = 22
println("MS.MII[-1]--->",MS.... |
package rc
import (
"github.com/square/p2/Godeps/_workspace/src/github.com/Sirupsen/logrus"
"github.com/square/p2/pkg/kp"
"github.com/square/p2/pkg/kp/consulutil"
"github.com/square/p2/pkg/kp/rcstore"
"github.com/square/p2/pkg/labels"
"github.com/square/p2/pkg/logging"
"github.com/square/p2/pkg/rc/fields"
)
/... |
package admin
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
m "github.com/im2kl/ProxyShed/Client/models"
)
// rawlist to be returned after scrapping.
var rawlist []m.ProxySource
// GetURLList retreive latest url list for scraping
func GetURLList() []m.ProxySource {
client := http.Client{}
req, err ... |
package simplegfs
import (
"bufio"
"fmt"
"github.com/wweiw/simplegfs/pkg/testutil"
log "github.com/Sirupsen/logrus"
"time"
"os"
"testing"
"strings"
"strconv"
"sync"
"runtime"
)
// Global test config.
const MasterAddr = ":4444"
const ck1Addr = ":5555"
const ck2Addr = ":5556"
const ck3Addr = ":555... |
// 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 entity
type CmsTopicCategory struct {
Id int64 `json:"id" xorm:"pk autoincr BIGINT(20) 'id'"`
Name string `json:"name" xorm:"default 'NULL' VARCHAR(100) 'name'"`
Icon string `json:"icon" xorm:"default 'NULL' comment('分类图标') VARCHAR(500) 'icon'"`
SubjectCount int `json:"subject... |
package caaa
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document00900105 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:caaa.009.001.05 Document"`
Message *AcceptorReconciliationRequestV05 `xml:"AccptrRcncltnReq"`
}
func (d *Do... |
// Package api will hopefully implement a go wrapper around the trailforks api
package api
|
package cmd
import "github.com/spf13/cobra"
var cmdNew = &cobra.Command{
Use: "new",
Short: "Creates a new project",
Long: "",
Run: func(cmd *cobra.Command, args []string) {
},
}
|
package main
import (
"fmt"
"net/http"
)
func main() {
fmt.Println("starting up...")
go func() {
for i := 0; i < 10; i++ {
go func() {
i := 0
for {
i++
}
}()
}
}()
http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Healthy")
})
if err := htt... |
/*
* Copyright © 2020-2022 Software AG, Darmstadt, Germany and/or its licensors
*
* SPDX-License-Identifier: Apache-2.0
*
* 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://... |
package config
import (
"../structs"
"github.com/jinzhu/gorm"
"github.com/joho/godotenv"
"log"
"os"
)
// DBInit create connection to database
func DBInit() *gorm.DB {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
dbHost := os.Getenv("HOST_DB_DEV")
dbName := os.Getenv("NAME... |
package vsphere
import (
"encoding/hex"
"encoding/json"
"fmt"
"net"
"net/netip"
"strings"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
machineapi "github.com/openshift/api/machine/v1beta1"
"github.com/openshift/installer/pkg/asset/installconfig"
"github.com/openshift/installer/pkg/tfvars/internal/... |
/*
* Copyright (c) 2020 - present Kurtosis Technologies LLC.
* All Rights Reserved.
*/
package testsuite
/*
An object that will be passed in to every test, which the user can use to manipulate the results of the test
*/
type TestContext struct {}
/*
Fails the test with the given error
*/
func (context TestConte... |
package monitor_step_test
import (
"errors"
"net/http"
"net/url"
"time"
"github.com/cloudfoundry-incubator/executor/sequence"
"github.com/cloudfoundry-incubator/executor/sequence/fake_step"
. "github.com/cloudfoundry-incubator/executor/steps/monitor_step"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega... |
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%s %s %s\n", r.URL, r.Method, r.Proto)
for key, val := range r.Header {
fmt... |
package handler
import (
e "crud/error"
"crud/model"
"github.com/gofiber/fiber/v2"
log "crud/logger"
)
func ErrorResponseHandler(c *fiber.Ctx, err error) error {
// DefinedError
if definedError, ok := err.(e.DefinedError); ok {
log.Logger().Warn("Handle DefinedError.")
errorResponse := model.ErrorResponse(... |
package managers
var lang = []string{"en",
"fr",
"it",
"es",
"se",
"nl",
"tr",
"pt",
"pl",
"ru",
"ir",
"id",
"jp",
}
|
//go:build go1.13
// +build go1.13
package socketmode
import (
"context"
"errors"
"testing"
"time"
"github.com/slack-go/slack"
"github.com/slack-go/slack/slacktest"
"github.com/stretchr/testify/assert"
)
func Test_passContext(t *testing.T) {
s := slacktest.NewTestServer()
go s.Start()
api := slack.New("... |
/*
Challenge
Sandbox post
Given a positive integer (K) Output a uniformly-random integer (Y) between [0, K).
If Y > 0 Assume K = Y and repeat the process until Y = 0.
Rules
Input must be printed at first
Output format as you wish
Your program must finish.
0 must be the final output, Optionally an ... |
package version
var (
// BuildDate is provided at build time.
BuildDate string
// Revision is provided at build time.
Revision string
)
|
// 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 cmd
import (
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var (
cfgFile string
rootCmd = &cobra.Command{
Use: "yakshop",
Short: "A cli to work with YakShop",
Long: "YakShop CLI allows you to query data or start an HTTP server",
}
)
func Execute() error {
return rootCmd.Exe... |
package main
import (
"fmt"
"net"
)
func whois(dom, server string) string {
conn, err := net.Dial("tcp", server+":43")
if err != nil {
fmt.Println("Error")
}
conn.Write([]byte(dom + "\r\n"))
buf := make([]byte, 1024)
res := []byte{}
for {
numbytes, err := conn.Read(buf)
sbuf := buf[0:numbytes]
res = ... |
package types
import (
"html/template"
"net/url"
"github.com/GoAdminGroup/go-admin/context"
"github.com/GoAdminGroup/go-admin/modules/utils"
"github.com/GoAdminGroup/go-admin/plugins/admin/models"
)
type Button interface {
Content() (template.HTML, template.JS)
GetAction() Action
URL() string
METHOD() strin... |
package tccpoutputs
import "github.com/giantswarm/microerror"
var invalidConfigError = µerror.Error{
Kind: "invalidConfigError",
}
// IsInsserts invalidConfigError.
func IsInvalidConfig(err error) bool {
return microerror.Cause(err) == invalidConfigError
}
var executionFailedError = µerror.Error{
Kind:... |
package main
import (
"database/sql"
"encoding/json"
"log"
"net/http"
)
type UserHandler struct {
*sql.DB
}
func (h *UserHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
var head string
head, req.URL.Path = ShiftPath(req.URL.Path)
match := Matcher(req.Method, head)
switch {
case match("GE... |
package main
import (
"flag"
"fmt"
"os"
"time"
yaml "gopkg.in/yaml.v2"
)
var (
yamlFile = "cidrs.yaml" // Stores YAML filename (default 'cidrs.yaml')
apiToken = os.Getenv("PHPIPAMTOKEN") // Env variable that stores API token
masterSubnetId = 231 ... |
package middleware
import (
"net/http"
"github.com/gin-gonic/gin"
)
const ApiTokenHeaderKey = "X-MessageDB-Api-Token"
func ApiTokenMiddleware() gin.HandlerFunc {
return func(ctx *gin.Context) {
token := ctx.Request.Header.Get(ApiTokenHeaderKey)
if len(token) == 0 {
ctx.AbortWithStatus(http.StatusForbidde... |
// This program listens to the host and port specified by the -listen flag and
// dumps any incoming data to standard output.
package main
import (
"flag"
"fmt"
"io"
"log"
"net"
"os"
)
var addr = flag.String("listen", "localhost:8000", "server listen address")
type dumpWriter struct {
c net.Conn
w io.Writer
... |
package pg
import (
"github.com/kyleconroy/sqlc/internal/sql/ast"
)
type ArrayCoerceExpr struct {
Xpr ast.Node
Arg ast.Node
Elemfuncid Oid
Resulttype Oid
Resulttypmod int32
Resultcollid Oid
IsExplicit bool
Coerceformat CoercionForm
Location int
}
func (n *ArrayCoerceExpr) Pos() ... |
package integration
import (
"fmt"
. "gopkg.in/check.v1"
)
func (s *RunSuite) TestDelete(c *C) {
p := s.ProjectFromText(c, "up", SimpleTemplate)
name := fmt.Sprintf("%s_%s_1", p, "hello")
cn := s.GetContainerByName(c, name)
c.Assert(cn, NotNil)
c.Assert(cn.State.Running, Equals, true)
s.FromText(c, p, "rm... |
package game_map
import (
"github.com/faiface/pixel/pixelgl"
"github.com/steelx/go-rpg-cgm/state_machine"
"reflect"
)
type FollowPathState struct {
Character *Character
Map GameMap
Entity Entity
Controller *state_machine.StateMachine
}
func FollowPathStateCreate(args ...interface{}) state_machine.... |
package nv7haven
import (
"net/url"
"strings"
"github.com/gofiber/fiber/v2"
"github.com/jdkato/prose/v2"
)
func (d *Nv7Haven) calcHella(c *fiber.Ctx) error {
input, err := url.PathUnescape(c.Params("input"))
if err != nil {
return err
}
doc, _ := prose.NewDocument(input)
done := make([]string, 0)
// I... |
package main
import (
"io/ioutil"
"os"
"testing"
)
func TestNeatPrint(t *testing.T) {
type tests struct {
testName string
input [][]string
expected string
}
intputSameLength := [][]string{
{"price", "display price of item"},
{"price", "display price of item"},
{"price", "display price of item"},... |
package PowerNLP
import (
"github.com/ksclouds/PowerNLP/Seg"
)
//默认分词方法
func Segment(sentence string) []string {
return Seg.DefaultSegment().Segment(sentence)
}
|
// ˅
package main
// ˄
type Book struct {
// ˅
// ˄
title string
// ˅
// ˄
}
func NewBook(title string) *Book {
// ˅
return &Book{title}
// ˄
}
// ˅
// ˄
|
package gojson
import "reflect"
func (enc *encoder) marshalSlice(v reflect.Value) ([]byte, error) {
var result string
var data []byte
var err error
if data, err = enc.marshalSliceElems(v); err != nil {
return nil, err
}
if data != nil {
result = result + string(data)
}
return []byte("[ " + result + " ]"),... |
package eth
import (
"fmt"
"github.com/stretchr/testify/assert"
"testing"
"web3.go/consts"
"web3.go/providers"
)
func TestGetBalance(t *testing.T) {
web3 := NewEth(providers.NewHTTPProvider(consts.HOST_HTTP_PROVIDER_LOCAL, 10))
t.Run("address err", func(t *testing.T) {
_, err := web3.GetBalance("", "")
ass... |
// 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 services
import (
"github.com/martinyonathann/bookstore_items-api/domain/items"
"github.com/martinyonathann/bookstore_items-api/utils/errors"
)
var (
ItemsService itemsServiceInterface = &itemsService{}
)
type itemsService struct {
}
type itemsServiceInterface interface {
GetItemByID(int64) (*items.Item... |
/*
I can't believe we don't have this already.. It's one of the most important data-structures in programming, yet still simple enough to implement it in a code-golf:
Challenge
Your task is to implement a stack that allows pushing and popping numbers, to test your implementation and keep I/O simple we'll use the foll... |
package main
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"google.golang.org/grpc"
"grpc-training/blog/blogpb"
"log"
"net"
"os"
"os/signal"
)
var collection *mongo.Collection
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
const URL = "mong... |
package controllers
import (
"github.com/gin-gonic/gin"
"github.com/hernancabral/Library/api/models"
"github.com/hernancabral/Library/api/utils"
"github.com/hernancabral/Library/api/utils/formaterror"
"net/http"
"strconv"
"time"
)
func (server *Server) PostBook(c *gin.Context) {
// clear previous error if an... |
package users
import (
"errors"
"net/http"
"cinemo.com/shoping-cart/internal/errorcode"
"github.com/gorilla/mux"
)
// Handlers handles users routes
func Handlers(r *mux.Router, service Service) {
r.Path("/login").Methods(http.MethodPost).HandlerFunc(LoginHandlers(service))
r.Path("/signup").Methods(http.Method... |
package stateStore
import (
dbComm "github.com/HNB-ECO/HNB-Blockchain/HNB/db/common"
"github.com/HNB-ECO/HNB-Blockchain/HNB/ledger/stateStore/common"
"github.com/HNB-ECO/HNB-Blockchain/HNB/logging"
"bytes"
)
type stateStore struct {
cache *StateCache
db dbComm.KVStore
}
func NewStateStore(db dbComm.KVStore)... |
package tools
import (
"crypto/md5"
"encoding/hex"
"io/ioutil"
)
func Md5(file string) (error, string) {
data, err := ioutil.ReadFile(file)
if err != nil {
return err, ""
}
md5Ctx := md5.New()
md5Ctx.Write(data)
cipherStr := md5Ctx.Sum(nil)
return nil, hex.EncodeToString(cipherStr)
}
|
package api
import (
"github.com/gin-gonic/gin"
r "github.com/huhaophp/eblog/controllers"
"github.com/huhaophp/eblog/models"
"github.com/huhaophp/eblog/request"
"github.com/unknwon/com"
)
// ArticleIndex 标签列表
func ArticleIndex(c *gin.Context) {
title := c.Query("title")
state := com.StrTo(c.DefaultQuery("state... |
/*
* @lc app=leetcode id=28 lang=golang
*
* [28] Implement strStr()
*/
func strStr(haystack string, needle string) int {
nl := len(needle)
hl := len(haystack)
if nl == 0 {
return 0
}
for i := 0 ; i < hl ; i++ {
if nl > hl - i {
break
}
found := true
for j := 0 ; j < nl ; j++ {
if needle[j] !... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-07-09 10:09
# @File : _236_Lowest_Common_Ancestor_of_a_Binary_Tree.go
# @Description : 找到2个节点的最近公共祖先
分治法
1.
# @Attention :
*/
package v0
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
// 从根节点开始遍历
if nil == root {
return nil
}
// 判断是否到了当... |
package structs
type Group struct {
CreatedAt int `json:"createdAt"`
GroupId string `json:"groupId"`
Users []string `json:"users"`
UserCount int `json:"userCount"`
APICallId string `json:"apiCallId"`
}
type GetAllGroupsReturn struct {
Message string `json:"message"`
Count int ... |
package distance
import (
"testing"
"github.com/stretchr/testify/require"
)
var input = []struct {
point int
dist float64
}{
{1, 0},
{12, 3},
{23, 2},
{1024, 31},
{312051, 430},
}
func TestDistance(t *testing.T) {
assert := require.New(t)
for _, in := range input {
assert.Equal(in.dist, Distance(in.po... |
package consensus
import (
"fmt"
"github.com/hashicorp/raft"
)
// keep a map of rafts for later
var rafts map[raft.ServerAddress]*raft.Raft
func init() {
rafts = make(map[raft.ServerAddress]*raft.Raft)
}
// raftSet stores all the setup material we need
type raftSet struct {
Config *raft.Config
Store ... |
package NFA
type DFARule struct {
State int32
Character int32
NextState int32
}
func (d DFARule) AppliesTo(state, character int32) bool {
return d.State == state && d.Character == character
}
func (d DFARule) Follow() int32 {
return d.NextState
}
type DFARulebook struct {
Rules []DFARule
}
func (d *DFARul... |
package ShopPositions
func MaxProfit(n int, m int, c []int) int {
return 0
}
|
package linters
import (
"go/ast"
"strings"
"golang.org/x/tools/go/analysis"
)
var TodoAnalyzer = &analysis.Analyzer{
Name: "todo",
Doc: "finds todos without author",
Run: run,
}
func run(pass *analysis.Pass) (interface{}, error) {
for _, file := range pass.Files {
ast.Inspect(file, func(n ast.Node) bool... |
package utils
import (
"crypto/md5"
"encoding/json"
"fmt"
"strconv"
"strings"
)
// 字符串转数字
func Atoi(i string) int {
v, err := strconv.Atoi(strings.TrimSpace(i))
if err != nil {
panic(err)
}
return v
}
// 数字转字符串
func Itoa(i int64) string {
return strconv.Itoa(int(i))
}
// 两数最大值
func MaxInt(a, b int) int ... |
// +build !windows,!plan9
package main
import (
"log"
"github.com/facebookgo/grace/gracehttp"
"github.com/labstack/echo/engine/standard"
)
func gracefulRun(std *standard.Server) {
log.Fatal(gracehttp.Serve(std.Server))
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.