text stringlengths 11 4.05M |
|---|
package main
/*
Pensar em semaforo com sua sinalização sendo flags
É uma alternativa ao waitGroup
*/
import (
"fmt"
)
func main() {
// dois channels
channel := make(chan int)
ok := make(chan bool) // flag
// sempre que puder channel recebe um valor
go func() {
for i := 0; i < 10; i++ {
channel <- i
}
... |
// +build mysql
package main
import (
"database/sql"
"fmt"
"os"
"time"
_ "github.com/go-sql-driver/mysql"
)
const MYSQL_DATE_FORMAT = "2006-01-02 15:04:05"
func (scsdb *SCSDB) GetDBType() string {
return "MySQL"
}
func (scsdb *SCSDB) init() error {
mysqlhost := os.Getenv("SCS_MYSQL_HOST") //SCS_MYSQL_HOST
... |
package tmp
const ModTmp = `module {{print .ModuleName}}
go {{print .GoVersion}}
require (
github.com/0LuigiCode0/logger v0.0.1 {{if isOneMQTT}}
github.com/eclipse/paho.mqtt.golang v1.3.4 // indirect {{end}} {{if isOneWS}}
github.com/gobwas/httphead v0.1.0 // indirect
github.com/gobwas/pool v0.2.1 // indirect
g... |
package resources
import (
"errors"
"net/http"
"github.com/manyminds/api2go"
"gopkg.in/mgo.v2/bson"
"themis/utils"
"themis/models"
"themis/database"
)
// UserResource for api2go routes.
type UserResource struct {
UserStorage *database.UserStorage
SpaceStorage *database.SpaceStorage
WorkItemStorage *databa... |
package main
import "fmt"
func main() {
slice := []int{99: 99}
fmt.Println(slice[0])
}
|
package keycloak
import "fmt"
func (keycloakClient *KeycloakClient) GetUserRoleMappings(realmId string, userId string) (*RoleMapping, error) {
var roleMapping *RoleMapping
err := keycloakClient.get(fmt.Sprintf("/realms/%s/users/%s/role-mappings", realmId, userId), &roleMapping, nil)
if err != nil {
return nil, e... |
package main
import (
"os"
"text/template"
)
func main() {
//START new OMIT
// Create a new, empty template
tmpl := template.New("hello")
//END new OMIT
//START parse OMIT
// Parse the template code into the new template
tmpl, err := tmpl.Parse(`Hello from {{ . }}`)
// ^ the first returned arg is a pointer... |
package Core
type Event struct {
EventId int
ComponentName string
MsgBody interface{}
}
func (event Event) GetEventId() int {
return event.EventId
}
func (event Event) GetComponentName() string {
return event.ComponentName
}
func (event Event) GetMsg() interface{} {
return event.MsgBody
}
|
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//423. Reconstruct Original Digits from English
//Given a non-empty string containing an out-of-order English representation of digits 0-9, output the ... |
// Package solution Reverse Integer of LeetCode.
// Problem:
//
// Given a 32-bit signed integer, reverse digits of an integer.
//
// Example 1:
// Input: 123
// Output: 321
//
// Example 2:
// Input: -123
// Output: -321
//
// Example 3:
// Input: 120
// Output: 21
//
// [Note]:
// Assume we are dealin... |
package rpclib
import (
"fmt"
"github.com/zcong1993/telnetor/manager"
)
// AddArgs is rpc args for add addr
type AddArgs struct {
// Addr is watching address
Addr string
// D is telnet interval
D int
}
// DelArgs is rpc args for del addr
type DelArgs struct {
// Addr is remove watching address
Addr string
}
... |
package ecc
import (
"math/big"
)
func (E *EccKeyPair) EccDH(q *Point) *big.Int {
key := new(Point)
key.Mul(E.d, q, E.C)
return key.x
}
|
package sql
import (
"time"
)
// Reduce evaluates expr using the available values in valuer.
// References that don't exist in valuer are ignored.
func Reduce(expr Expr, valuer Valuer) Expr {
expr = reduce(expr, valuer)
// Unwrap parens at top level.
if expr, ok := expr.(*ParenExpr); ok {
return expr.Expr
}
... |
package geometry
import "math"
type Shape interface {
Area() float64
}
type Rectangle struct {
Length float64
Breadth float64
}
func (r Rectangle) Area() float64 {
return r.Length * r.Breadth
}
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return 3.14 * math.Pow(c.Radius, 2.0)
}
t... |
package channels
import (
"context"
"fmt"
"time"
)
// Printer will print anything sent on the ch chan
// and will print tock every 200 milliseconds
// this will repeat forever until a context is
// Done, i.e. timed out or cancelled
func Printer(ctx context.Context, ch chan string) {
t := time.Tick(200 * time.Mill... |
/*
Task
Given a UTF-8 string (by any means) answer (by any means) an equivalent list where every element is the number of bytes used to encode the corresponding input character.
Examples
! → 1
Ciao → 1 1 1 1
tʃaʊ → 1 2 1 2
Adám → 1 1 2 1
ĉaŭ → 2 1 2 (single characters)
ĉaŭ → 1 2 1 1 2 (uses combining overlay... |
package main
import (
"code.google.com/p/go.exp/fsnotify"
"code.google.com/p/go.net/websocket"
"encoding/json"
"log"
"time"
)
type Event struct {
Path string `json:"path"`
Done chan error `json:"-"`
}
// 監視ディレクトリひとつを表す
type Entry struct {
w *fsnotify.Watcher
dir string
clients []chan... |
package server
import (
"github.com/GoACK/Service/config"
"github.com/GoACK/Service/controller"
)
// Package packs the initialized packages into a single pack so we can pass it around the other packages.
type Package struct {
Config config.Config
Controller controller.Controller
}
// Pack the initialized pac... |
package main
import (
"fmt"
"sync"
)
func Distance(s, t string,wg *sync.WaitGroup) int {
var (
n = len(s)
m = len(t)
)
switch {
case n == 0:
return m
case m == 0:
return n
}
d := buildMatrix(n, m)
defer wg.Done()
for i := 1; i <= n; i++ {
for j := 1; j <= m; j++ {
cost := 0
if s[i-1] !... |
package main
import (
"flag"
"fmt"
"github.com/Mindslave/skade/backend/internal/engine"
"github.com/Mindslave/skade/backend/internal/log/zap"
)
func main() {
var logger engine.Logger
//there is only zap at the moment, but there might be more in the future
loggerType := "zap"
switch loggerType {... |
package main
import (
"bufio"
"io"
"log"
"net"
"os"
"os/signal"
"strings"
"sync"
"syscall"
)
const (
// LogFlag 控制日志的前缀
LogFlag = log.LstdFlags | log.Lmicroseconds | log.Lshortfile
// MaxConnectionNum 表示最大连接数
MaxConnectionNum = 10000
)
var (
errLogger = log.New(os.Stderr, "ERROR ", LogFlag)
infoLogge... |
package day4_2018
import (
loader "aoc/dataloader"
"aoc/test"
"testing"
)
func TestPart1(t *testing.T) {
cases := []test.Case[[]string, int]{
{loader.Load("test_input.txt"), 240},
{loader.Load("input.txt"), 39584},
}
err := test.Execute(cases, Part1)
if err != nil {
t.Error(err)
}
}
func TestPart2(t *... |
package main
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"log"
"net/http"
"github.com/urbanairship/go-iapclient"
"gopkg.in/alecthomas/kingpin.v2"
)
var (
cid = kingpin.Flag("client-id", "OAuth Client ID").Required().String()
uri = kingpin.Flag("uri", "URI to get").Required().String()
caFil... |
/**
* @author liangbo
* @email liangbogopher87@gmail.com
* @date 2017/10/11 23:32
*/
package model
// 活动表
type Activity struct {
} |
package trees
import (
"strings"
"github.com/Nv7-Github/Nv7Haven/eod/types"
)
type SizeTree struct {
Size int
dat types.ServerData
added map[string]types.Empty
}
func (s *SizeTree) AddElem(name string, notoplevel ...bool) (bool, string) {
_, exists := s.added[name]
if exists {
return true, ""
}
if le... |
package main
// import (
// "fmt"
// rotatelogs "github.com/lestrrat/go-file-rotatelogs"
// "go.uber.org/zap"
// "go.uber.org/zap/zapcore"
// "io"
// "net/http"
// "time"
// )
// var sugarLogger *zap.SugaredLogger
// func main() {
// fmt.Println("begin main")
// InitLogger()
// defer sugarLogger.Sync()
// ... |
package dice
import "github.com/jcheng31/diceroller/roller"
type regular struct {
roller roller.Roller
max int
}
// Regular returns a normal die.
func Regular(r roller.Roller, max int) Die {
return regular{r, max}
}
// RollN returns the total result of rolling n die.
func (r regular) RollN(n int) RollResults ... |
// 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 mosquito
import (
"io"
"regexp"
"io/ioutil"
"html/template"
"path/filepath"
)
type FileSystemRenderer struct {
Root string
}
func (renderer *FileSystemRenderer) Render(w io.Writer, file string, data interface{}) error {
var tmpl *template.Template
if err := renderer.parse(file, tmpl); err != nil {... |
package middleware
import (
"context"
"net/http"
"strconv"
)
// ContextID is our type to retrieve our context
// objects
type ContextID int
// ID is the only ID we've defined
const ID ContextID = 0
// SetID updates context with the id then
// increments it
func SetID(start int64) Middleware {
return func(next h... |
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"time"
credpb "google.golang.org/genproto/googleapis/iam/credentials/v1"
credentials "cloud.google.com/go/iam/credentials/apiv1"
"cloud.google.com/go/storage"
)
var (
projectID = os.Getenv("GOOGLE_CLOUD_PROJECT")
serviceAccount = fmt.... |
package service
import (
"ConfCenter_web_Admin/initialization"
"errors"
"fmt"
"github.com/astaxie/beego/logs"
"gopkg.in/square/go-jose.v1/json"
"io/ioutil"
"net/http"
)
var (
scheme = "http://"
client = &http.Client{}
)
type OperationsResult struct {
Result []*Operations `json:"result"`
}
type Operations ... |
package foundation
import (
"testing"
"github.com/stretchr/testify/assert"
)
// TestPanic runs
func TestPanic(t *testing.T) {
assert := assert.New(t)
assert.Panics(func() {
Panic("foo", "bar", 1, true)
Panicf("%s=%d", "bar", 1)
})
ProdModeClosure(func() {
assert.NotPanics(func() {
Panic("foo", "bar"... |
package commands
import (
"golang.org/x/sys/windows"
"path/filepath"
)
func workdir() string {
if programData, err := windows.KnownFolderPath(windows.FOLDERID_ProgramData, windows.KF_FLAG_DEFAULT); err != nil {
return `C:\uhppoted`
} else {
return filepath.Join(programData, "uhppoted")
}
}
|
package response
import (
"time"
)
// TitUserBaseinfoTraining, 数据已经转化过了,可以直接在页面展示
type TitUserBaseinfoTraining struct {
// 教学背景
School string `json:"school" form:"school" `
MajorsStudied string `json:"majorsStudied" form:"majorsStudied" `
HighestEducation string `json:"highestEducation" form:"highes... |
package yousign
import (
"net/http"
"time"
)
type UserService struct {
client *Client
}
type User struct {
ID *string `json:"id,omitempty"`
Firstname *string `json:"firstname,omitempty"`
Lastname *string `json:"lastname,omitempty"`
FullName *string `json:"f... |
/*
Given a string, return a new string where the first and last chars have been exchanged.
*/
package main
import (
"fmt"
)
func front_back(s string) string {
if len(s) == 1 {
return s
}
var buf = []byte(s)
str := make([]byte, len(s))
if len(s) == 2 {
str[0] = buf[1]
str[1] = buf[0]
} else {
str[0] = b... |
package main
import (
"github.com/gorilla/mux"
// inner package dependencies
"github.com/The-Music-Network/TMN-API/middleware"
"github.com/The-Music-Network/TMN-API/components/users"
)
func initRoutes(metaDb *middleware.MetaDb, router *mux.Router) {
initUserRoutes(metaDb, router)
}
func initUserRoutes(metaDb *... |
package server
import (
"log"
"net/http"
"github.com/PECHIVKO/anagram-finder/api/router"
"github.com/PECHIVKO/anagram-finder/service"
)
func Run(port string, d *service.Dictionary) {
// Init Session
Session := &http.Server{
Addr: port,
Handler: router.NewRouter(d),
}
log.Fatal(Session.ListenAndServe()... |
package utils
import "testing"
func TestI18ns_ToFile(t *testing.T) {
//i18ns := new(I18ns)
//i18ns.AddI18n(I18n{Id: "1", Zh_CN: "你好", En_US: "hello"})
//i18ns.AddI18n(I18n{"2", "我", "me", "我"})
//i18ns.WriteToFile(".")
}
|
package command
import (
"fmt"
"log"
"regexp"
"strings"
"time"
"github.com/jixwanwang/jixbot/channel"
"github.com/jixwanwang/jixbot/nlp"
)
type newQuestion struct {
timestamp time.Time
username string
question string
}
type questions struct {
cp *CommandPool
questionRgx *regexp.Regexp
cleanRgx *r... |
// web server
package main
import (
"fmt"
"log"
"net"
"time"
)
func main() {
ln, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatal("listen error tcp :8080")
}
defer ln.Close()
log.Println("START LISTEN: ", ln.Addr())
for {
conn, err := ln.Accept()
if err != nil {
log.Println("ln.Accept ... |
package secret
import (
"crypto/rand"
"errors"
"io"
"golang.org/x/crypto/nacl/secretbox"
)
const (
KeySize = 32
NonceSize = 24
)
var (
ErrEncrypt = errors.New("secret: encryption failed")
ErrDecrypt = errors.New("secret: decryption failed")
)
// GenerateKey creates a new random secret key.
func GenerateKey... |
// This file was generated for SObject FeedRevision, API Version v43.0 at 2018-07-30 03:47:37.645128955 -0400 EDT m=+23.988635511
package sobjects
import (
"fmt"
"strings"
)
type FeedRevision struct {
BaseSObject
Action string `force:",omitempty"`
CreatedById string `force:",omitempty"`
CreatedDat... |
package americanise
import "testing"
func TestTranslate(t *testing.T) {
Translate(input, output)
}
|
// set project doc.go
/*
set document
*/
package set
|
package server
import "github.com/spf13/viper"
// Config holds the server configuration
type Config struct {
// ListenPort speicifies the port server will bind to
ListenPort int `mapstructure:"server.ListenPort"`
// listenAddress specifies address on which server should listen for new connnections
ListenAddress s... |
package aedatastore
import (
"testing"
"github.com/favclip/testerator/v2"
_ "github.com/favclip/testerator/v2/datastore"
_ "github.com/favclip/testerator/v2/memcache"
"go.mercari.io/datastore/testsuite"
_ "go.mercari.io/datastore/testsuite/dsmiddleware/dslog"
_ "go.mercari.io/datastore/testsuite/dsmiddleware/... |
package service
type PubService struct {
}
|
package jsonstream
import (
"bufio"
"encoding/json"
"errors"
"io"
)
var ErrClosed = errors.New("json: stream closed")
func isArray(br *bufio.Reader) (bool, error) {
for {
b, err := br.Peek(1)
if err != nil {
return false, err
}
switch b[0] {
// Ignore whitespace.
case ' ', '\n', '\t':
case '['... |
package agent
import (
"context"
"github.com/filecoin-project/go-bitfield"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/go-state-types/dline"
miner2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/miner"
miner3 "githu... |
/*
Given an input string S, print S followed by a non-empty separator in the following way:
Step 1: S has a 1/2 chance of being printed, and a 1/2 chance for the program to terminate.
Step 2: S has a 2/3 chance of being printed, and a 1/3 chance for the program to terminate.
Step 3: S has a 3/4 chance o... |
package easypost
import (
"encoding/json"
)
// UnmarshalJSONObject attempts to unmarshal an easypost object from JSON data.
// An error is only returned if data is non-zero length and JSON decoding fails.
// If data contains a valid JSON object with an "object" key/value that matches
// a known object type, it will ... |
package ttlib
import (
"github.com/johnnylee/util"
)
// ServerConfig: A configuration file for a server.
type ServerConfig struct {
ListenAddr string // The address to pass to Listen.
PublicAddr string // The address to use to connect to the server.
}
// LoadServerConfig: Load the server's configuration from the ... |
package wechat
import (
"strconv"
"gopkg.in/chanxuehong/wechat.v2/mch/mmpaymkttransfers/promotion"
"github.com/golang/glog"
"github.com/chanxuehong/util"
"bytes"
"encoding/xml"
"strings"
"gopkg.in/chanxuehong/wechat.v2/mch/mmpaymkttransfers"
"gopkg.in/chanxuehong/wechat.v2/mch/core"
"common-utilities/utiliti... |
package trie
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestVLenArray_get(t *testing.T) {
ta := require.New(t)
// Fixed size
{
elts := [][]byte{
{'a', 'b'},
{}, // empty
{},
{'c', 'd'},
{'e', 'f'},
{},
}
va := newVLenArray(elts)
ta.Equal(int32(6), va.N)
ta.Eq... |
package sese
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document02800105 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:sese.028.001.05 Document"`
Message *SecuritiesSettlementTransactionAllegementNotific... |
package g2util
import (
"image/color"
"github.com/mojocn/base64Captcha"
)
// Captcha ...
type Captcha struct {
cap *base64Captcha.Captcha
}
// Cap ...
func (c *Captcha) Cap() *base64Captcha.Captcha { return c.cap }
// SetCap ...
func (c *Captcha) SetCap(cap *base64Captcha.Captcha) { c.cap = cap }
// Constructo... |
package models
import (
"github.com/jinzhu/gorm"
)
// City Model
type City struct {
gorm.Model
ProvinceID int `json:"province_id" gorm:"not null" binding:"required"`
Name string `json:"name" gorm:"not null" binding:"required"`
Status bool `json:"status" gorm:"not null; default:true"`
}
|
//Implementation of Wiener's attack https://en.wikipedia.org/wiki/Wiener%27s_attack
package wiener
import (
"math/big"
"github.com/vveiln/crypto/wiener/fraction"
)
func solveQuadraticEquation(phi, n *big.Int) (*big.Int, *big.Int) {
b := new(big.Int).Sub(n, phi)
b.Add(b, big.NewInt(1))
b.Neg(b)
c := new(big.Int... |
package compoundsplitting
import (
"context"
"fmt"
"time"
)
// minCompoundWordLength prevents the splitting into very small (often not real) words
// to prevent a bloated tree
const minCompoundWordLength = 4
// maxWordLength prevents a tree from growing too big when adding very long strings
const maxWordLength =... |
package virtualgateway
import (
"context"
appmesh "github.com/aws/aws-app-mesh-controller-for-k8s/apis/appmesh/v1beta2"
"github.com/aws/aws-app-mesh-controller-for-k8s/pkg/equality"
"github.com/aws/aws-app-mesh-controller-for-k8s/pkg/k8s"
"github.com/aws/aws-sdk-go/aws"
appmeshsdk "github.com/aws/aws-sdk-go/serv... |
package controller
import (
"chirpper_backend/models"
"chirpper_backend/utils"
"context"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"time"
"cloud.google.com/go/firestore"
)
//postWithImage handle post feed request when storing an image file is needed
func (x *EndPoints) PostWithImage(client *fire... |
/**
* @Author: yanKoo
* @Date: 2019/3/25 14:57
* @Description:
*/
package main
import (
pb "api/talk_cloud"
"context"
"google.golang.org/grpc"
"log"
"sync"
"time"
)
const GROUP_PORT = "9999"
var maps sync.Map
func main() {
//host := "113.105.153.240"
host := "127.0.0.1"
conn, err := grpc.Dial(host+":9001... |
package main
import (
"os"
"os/signal"
"strings"
"syscall"
"testing"
)
func TestMagalixAgent(t *testing.T) {
var (
args []string
covurl = os.Getenv("CODECOV_URL")
)
if covurl == "" {
t.Skip("codecov url is not provided")
}
for _, arg := range os.Args {
switch {
case strings.HasPrefix(arg, "-te... |
package yaml
import (
"bytes"
"testing"
)
func TestEscapeKey(t *testing.T) {
s := "\\'\""
t.Log(s)
t.Log(EscapeKey(s))
}
func TestEscapeText(t *testing.T) {
facts := map[string]string{
":": "|2-\n :",
"a:": "|2-\n a:",
"a:b": "a:b",
":a:": "|2-\n :a:"... |
package account
import (
"github.com/bitmaelum/bitmaelum-suite/internal/message"
"github.com/bitmaelum/bitmaelum-suite/pkg/address"
"github.com/bitmaelum/bitmaelum-suite/pkg/bmcrypto"
"io"
"time"
)
// Message is a simple message structure that we return as a list
type Message struct {
ID string `js... |
package notice
import (
"github.com/devfeel/dotweb"
"master/define"
"master/api"
"strconv"
"master/utils"
)
func DelNoticeHander(ctx dotweb.Context)error{
defer ctx.End()
token:=ctx.FormValue("token")
id,_:= strconv.Atoi(ctx.FormValue("noticeID"))
if api.CheckTokenValid(token){
api.DelNoticeInfo(id)
... |
package prototype
import (
"errors"
"fmt"
)
// ShirtCloner TODO
type ShirtCloner interface {
GetClone(s int) (ItemInfoGetter, error)
}
// TODO
const (
White = 1
Black = 2
Blue = 3
)
// ShirtCache TODO
type ShirtCache struct{}
// GetClone returns cached shirts sample by cloning them
func (s *ShirtCache) GetC... |
package flow_test
import (
"fmt"
"github.com/BaritoLog/barito-flow/flow"
"github.com/go-redis/redis/v8"
"github.com/go-redis/redismock/v8"
log "github.com/sirupsen/logrus"
"github.com/stretchr/testify/require"
"os"
"sync"
"testing"
"time"
)
const (
distributedRateLimiterDefaultTopic string = "foo... |
package models
type HttpConfig struct {
Server struct {
Name string `json:"name"`
DocumentRoot string `json:"documentroot"`
EntryPoint string `json:"entrypoint"`
} `json:"server"`
}
|
package leetcode
/*Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-the-difference
著作权归领扣网络所有。商业转载请联系官方授... |
package pathfileops
import (
"errors"
"fmt"
)
// FileOps - This type is used to manage and coordinate various
// operations performed on files. Hence the name, File Operations.
//
type FileOps struct {
isInitialized bool
source FileMgr
destination FileMgr
opToExecute FileOperationCode
}
// Cop... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//674. Longest Continuous Increasing Subsequence
//Given an unsorted array of integers, find the length of longest continuous increasing subsequence (s... |
package main
import (
"sort"
"sync"
"time"
)
var (
popularHoldTime = int64(5)
popularWordMgr = &PopularWordMgr{
popularWords: map[int64](map[string]int){},
}
)
type WordUnit struct {
Word string
Count int
}
type PopularWordMgr struct {
sync.RWMutex
popularWords map[int64](map[string]int)
}
func (mgr ... |
// Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
// released under the MIT license
package ircsetup
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
"syscall"
"golang.org/x/crypto/ssh/terminal"
"github.com/fatih/color"
"github.com/goshuirc/bnc/lib"
)
var (
CbBlue = color.New(color.B... |
package main
import "fmt"
type Weight int
type Edges []EdgeStructure
type EdgeStructure struct {
v, w int
weight Weight
}
type Graph struct { // adj array graph
vertexNum int
edgeArray [][]Weight
}
func (e Edges) QuickSort(left, right int) {
pivot := right
l := left
r := right - 1
swap := func(a, b int) ... |
/*
Write the shortest code that traverses a directory tree and outputs a flat list of all files.
It should traverse the whole directory tree
The order in which it enters sub-directories doesn't matter
The directories should not be output
The output should be a plain list — the definition is flexible, but it shouldn't... |
package catm
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document00400104 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:catm.004.001.04 Document"`
Message *TerminalManagementRejectionV04 `xml:"TermnlMgmtRjctn"`
}
func (d *Documen... |
package main
import "fmt"
func main() {
loop(3)
fmt.Println(c())
}
func c() (i int) {
x := 0
defer func() { x++ }()
return 2
}
func loop(x int) {
fmt.Println("counting")
for i := 0; i < 10; i++ {
defer fmt.Println(i)
if(i == x) {
return
}
}
defer fmt.Println("done")
}
|
package handlers
import (
"net/http"
"github.com/saurabmish/Coffee-Shop/data"
)
func (p Products) Add(w http.ResponseWriter, r *http.Request) {
p.l.Println("[INFO] Endpoint for POST request")
product := r.Context().Value(KeyProduct{}).(data.Product)
p.l.Println("[DEBUG] Adding product to list")
data.AddProduct... |
package example
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/pem"
"fmt"
"golang.org/x/crypto/ocsp"
"io/ioutil"
"testing"
"time"
)
var (
pwd = "123456"
caKeyPem = `-----BEGIN ECC PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-12... |
package db
import (
"fmt"
"github.com/swjang1214/bookstore_oauth-api/src/db/mysql_db"
"github.com/swjang1214/bookstore_oauth-api/src/domain/access_token"
"github.com/swjang1214/bookstore_oauth-api/src/logger"
"github.com/swjang1214/bookstore_oauth-api/src/utils/errors"
)
const (
queryCreateAccessToken = "INSER... |
// Copyright 2019-present Open Networking Foundation.
//
// 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
import (
"fmt"
"ms/sun_old/base"
"ms/sun/shared/x"
)
func main() {
n := 0
next := func() int {
n++
return n
}
work := func() {
for {
//_, err := x.HomeFanoutByOrderId(base.DB, rand.Intn(40000))
_, err := x.HomeFanoutByOrderId(base.DB, 1000)
if n := ... |
package options
var CONFIG string
type ConfigOptions struct {
}
func (c *ConfigOptions) Init() {
}
|
// Copyright 2017 Thibault Chataigner <thibault.chataigner@gmail.com>
// 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 b... |
/*
Recreational languages win at code golf too much. This challenge is simple, when using higher level functions.
The task is as follows:
Given any valid url, which is guaranteed to result in a valid HTML document (for example https://en.wikipedia.org/wiki/Ruby_on_Rails, which has 9 images), count the number of imag... |
package shape
import (
"math"
"testing"
"github.com/calbim/ray-tracer/src/material"
"github.com/calbim/ray-tracer/src/transforms"
"github.com/calbim/ray-tracer/src/matrix"
"github.com/calbim/ray-tracer/src/ray"
"github.com/calbim/ray-tracer/src/tuple"
)
func TestSphereIntersection(t *testing.T) {
s := NewS... |
// Package loadtest provides services and mechanics for handling loadtests.
package loadtest
import (
"context"
"errors"
"math/rand"
"sync"
"time"
chromedpexecutor "github.com/dkorittki/loago/internal/pkg/worker/executor/browser"
"github.com/dkorittki/loago/pkg/worker/runner"
"github.com/rs/zerolog/log"
)
va... |
package main
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestHandler(t *testing.T) {
// Sending new request first argument is method, 2nd - route, 3rd - body
req, err := http.NewRequest("GET", "", nil)
if err != nil {
t.Fatal(err)
}
// Recorder is like mini-browser that records all ou... |
package main
import (
"encoding/json"
"log"
"net/http"
pilot "github.com/bwireman/tuple/pilot/pkg"
)
var p = pilot.NewPilot()
var versions = map[string]map[string]string{}
func handlerWrapper(path string, APIVersion string, handler func(http.ResponseWriter, *http.Request)) (string, func(http.ResponseWriter, *ht... |
package main
import (
"github.com/gin-gonic/gin"
"github.com/im-adarsh/text-resource/text-resource/service"
"github.com/im-adarsh/text-resource/text-resource/service/endpoint"
)
func main() {
r := gin.Default()
t := service.NewTranslationService()
endpoint.MakeEndPoint(r, t)
err := r.Run() // listen and serve ... |
// 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 e2e
import (
"testing"
"time"
framework "github.com/operator-framework/operator-sdk/pkg/test"
"github.com/operator-framework/operator-sdk/pkg/test/e2eutil"
)
var (
retryInterval = time.Second * 5
timeout = time.Second * 60
cleanupRetryInterval = time.Second * 1
cleanupTimeout ... |
package leetcode
import "testing"
func TestNumPairsDivisibleBy60(t *testing.T) {
if numPairsDivisibleBy60([]int{30, 20, 150, 100, 40}) != 3 {
t.Fatal()
}
}
|
// https://en.wikipedia.org/wiki/Linked_list
package main
import (
"errors"
"fmt"
)
// Node have it's value, links to previoues and next element
type Node struct {
Value interface{}
prev, next *Node
list *List
}
// List have links to first and last element
type List struct {
head, tail *Node
}
// F... |
package main
import (
f "fmt"
"strings"
)
func main() {
s := "Hello, Lucas"
r := strings.NewReader(s)
var s1, s2 string
n, _ := f.Fscanf(r, "%s %s", &s1, &s2)
f.Println("입력 개수 : ", n)
f.Println(s1)
f.Println(s2)
}
|
package controller
import (
"net/http"
"time"
"feeyashop/models"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
type productInput struct {
Name string `json:"name"`
Description string `json:"description"`
Price uint `json:"price"`
CategoryID uint `json:"category_id"`
}
// GetAllProduct godo... |
/*
Lets define a pointer sequence to be any sequence such that a(n) = a((n-1)-(a(n-1))) forall n greater than some finite number. For example if our sequence begun with
3 2 1
Our next term would be 2, because a(n-1) = 1, (n-1)-1 = 1, a(1) = 2 (this example is zero index however it does not matter what index you use ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.