text stringlengths 11 4.05M |
|---|
package mymath
func Sqrt(x float64) float64 {
z := 0.0
for i :=0; i<1000; i++ {
z -=(z*z -x) / (2*x)
}
return z
}
|
package main
import (
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
//"fmt"
//"encoding/json"
_ "encoding/json"
"fmt"
//"encoding/json"
//"os/user"
"encoding/json"
)
func init() {
orm.RegisterDataBase("default", "mysql", "root:root@tcp(127.0.0.1:3306)/go_g?charset=utf8")
orm.RegisterMod... |
package main
import (
"fmt"
)
// https://leetcode-cn.com/problems/4sum-ii/
// 454. 四数相加 II | 4Sum II
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Solution
//
// 复杂度分析:
// * 时间: O(N^2)
// * 空间:... |
package kubemq_queue
import (
"context"
"net"
"strconv"
queuesStream "github.com/kubemq-io/kubemq-go/queues_stream"
"github.com/sirupsen/logrus"
"github.com/batchcorp/plumber-schemas/build/go/protos/args"
"github.com/batchcorp/plumber-schemas/build/go/protos/opts"
"github.com/batchcorp/plumber/types"
)
con... |
package lang
import "fmt"
// Month just a literature form
type Month int
func outputMonth(m Month) {
fmt.Println(m)
}
|
package perfect
import (
"errors"
)
type Classification int
var ErrOnlyPositive = errors.New("Only positive number are allowed")
const (
ClassificationPerfect Classification = iota
ClassificationAbundant
ClassificationDeficient
)
func Classify(n int64) (Classification, error) {
sumOfDivisors, err := divisorSu... |
package main
import (
"context"
"fmt"
"log"
"sync"
"concurrency"
"golang.org/x/sync/errgroup"
)
func main() {
requests := concurrency.GenerateRequests(concurrency.Count)
DoAsync(context.TODO(), requests)
}
func DoAsync(ctx context.Context, requests [][]byte) {
totalWorkers := concurrency.TotalWorkers
/... |
package arguments
type CommandOpts struct {
recursivelyOpt bool
nameBeginWithADotOpt bool
longFormatOpt bool
sortOpt bool
reverseArrayOpt bool
}
var Options *CommandOpts
func (opts *CommandOpts) RecursivelyOpt() bool {
return opts.recursivelyOpt
}
func (opts *CommandOpts) NameBe... |
package handlers
import (
"net/http"
"github.com/pilagod/gorm-cursor-paginator/v2/paginator"
"github.com/root-gg/plik/server/common"
"github.com/root-gg/plik/server/context"
)
// GetUsers return users
func GetUsers(ctx *context.Context, resp http.ResponseWriter, req *http.Request) {
// Double check authorizat... |
package jarviscore
import (
"io/ioutil"
"testing"
)
func TestCtrlScriptFile(t *testing.T) {
ctrl := &CtrlScriptFile{}
dat, err := ioutil.ReadFile("./test/test.sh")
if err != nil {
t.Fatalf("TestCtrlScriptFile load script file %v", err)
}
ci, err := BuildCtrlInfoForScriptFile("test.sh", dat, "", "")
if err... |
package graph
import (
"github.com/zond/godip/common"
"reflect"
"testing"
)
func assertPath(t *testing.T, g *Graph, src, dst common.Province, found []common.Province) {
if f := g.Path(src, dst, nil, false); !reflect.DeepEqual(f, found) {
t.Errorf("%v should have a path between %v and %v like %v but found %v", g... |
/*
* EVE Swagger Interface
*
* An OpenAPI for EVE Online
*
* OpenAPI spec version: 0.4.1.dev1
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package swagger
// mail schema
type PostCharactersCharacterIdMailMail struct {
// approved_cost integer
ApprovedCost int64 `json:"approved_... |
// Copyright 2019 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 lib
import (
"github.com/mayflower/docker-ls/lib/connector"
)
func createConnector(cfg *Config) connector.Connector {
if cfg.basicAuth {
return connector.NewBasicAuthConnector(cfg)
}
return connector.NewTokenAuthConnector(cfg)
}
|
// Copyright 2019 TiKV Project 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 agr... |
package main
import "fmt"
const d string = "Some Variable"
func main(){
const a = "ANAND"
const s = 10
fmt.Println(a)
fmt.Println(s)
fmt.Println(d)
}
|
package controller
import (
"net/http"
"github.com/corentindeboisset/golang-api/app/service"
"github.com/corentindeboisset/golang-api/app/repository"
)
// UserController handles routes related to users
type UserController struct {
ServiceContainer *service.Container
RepositoryContainer *repository.Container
}
/... |
// Copyright 2021 Google LLC
//
// 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 ... |
package initialisation
/*
構造体や配列の初期化に関するメモ
*/
type Struct1 struct {
x string
y []string
}
func GetStruct1() *Struct1 {
s1 := new(Struct1)
s1.x = "A"
s1.y = append(s1.y, "B")
s1.y = append(s1.y, "C")
return s1
}
|
package backtracking
import (
"strconv"
"strings"
)
func getPermutation2(n int, k int) string {
factorial := make(map[int]int, n+1)
sum := 1
factorial[0] = 1
for i := 1; i <= n; i++ {
sum *= i
factorial[i] = sum
}
numbers := []int{}
for i := 1; i <= n; i++ {
numbers = append(numbers, i)
}
// base 0... |
package main
import (
"context"
"log"
"github.com/circonus-labs/gosnowth"
)
// ExampleGetNodeState demonstrates how to get the snowth node's state from
// a particular node.
func ExampleGetNodeState() {
// Create a new client.
cfg := gosnowth.NewConfig(SnowthServers...)
client, err := gosnowth.NewClient(conte... |
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
//apiUrl = "https://coinmarketcap-nexuist.rhcloud.com/api/"
//ethApi = apiUrl + "eth"
//btcApi = apiUrl + "btc"
func main() {
r, _ := http.Get("https://coinmarketcap-nexuist.rhcloud.com/api/eth")
defer r.Body.Close()
body, _ := ioutil.ReadAl... |
package dushengchen
/*
question:
https://leetcode.com/problems/longest-palindromic-substring/
Submission:
https://leetcode.com/submissions/detail/289234911/
*/
func longestPalindrome(s string) string {
var max string
for i:=0; i < len(s); i++ {
start, end := i, i
for ;(end+1 < len(s))... |
package middlewares
import (
"net/http"
"github.com/JeanCntrs/airbnb-catalog-server/db"
)
// CheckDB : Check the status of database and if everything is fine, continue the process, otherwise, stop the execution
func CheckDB(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Reque... |
/*
Go Language Raspberry Pi Interface
(c) Copyright David Thorpe 2016-2018
All Rights Reserved
Documentation http://djthorpe.github.io/gopi/
For Licensing and Usage information, please see LICENSE.md
*/
package sensordb
import (
"context"
"fmt"
// Frameworks
"github.com/djthorpe/gopi"
"github.com/djthorpe/... |
package awsvaultcredsprovider
import (
"github.com/jcmturner/restclient"
"github.com/jcmturner/vaultclient"
"github.com/jcmturner/vaultmock"
"github.com/stretchr/testify/assert"
"testing"
"time"
)
const (
Test_SecretAccessKey = "9drTJvcXLB89EXAMPLELB8923FB892xMFI"
Test_SessionToken = "AQoXdzELDDY//////////... |
// Copyright 2017 Mirantis
//
// 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 wri... |
// +build aws_lambda
package cmd
import (
"github.com/aws/aws-lambda-go/lambda"
"github.com/awslabs/aws-lambda-go-api-proxy/httpadapter"
"github.com/movieManagement/gen/restapi/operations"
ini "github.com/movieManagement/init"
log "github.com/movieManagement/logging"
)
// Start is the lambda main entry point
fu... |
package core
import (
"reflect"
"sort"
"testing"
)
func TestSplit(t *testing.T) {
type args struct {
participants []string
}
tests := []struct {
name string
args args
wantAmountOfGroups int
}{
{"6 participants", args{participants: []string{"Alex", "Igor", "Olga", "Max", "V... |
package industrydb
import (
_ "github.com/go-sql-driver/mysql"
"stockdb"
"entity/xlsentity"
"util"
)
type MinorIndustryDatabase struct {
stockdb.DBBase
}
func (s *MinorIndustryDatabase) InsertIndustry(industry xlsentity.Industry) int {
db := s.Open()
stmt, err := db.Prepare("insert c... |
// Package cloudsysfs provides a function for detecting the current host's cloud provider, based on the contents of the /sys filesystem.
package cloudsysfs
import "github.com/erichs/cloudsysfs/providers"
var cloudProviders = [...]func(chan<- string){
providers.AWS,
providers.Azure,
providers.DigitalOcean,
provide... |
package types
import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
// BankKeeper defines the expected bank keeper
type BankKeeper interface {
AddCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) (sdk.Coins, error)
SendCoins(ctx sdk.Context, from sdk.AccAddress, to sdk.AccAddress, amt sdk.Coins) error
}
|
package prof
type SmallLarge struct {
Small string `json:"small"`
Large string `json:"large"`
}
type profile struct {
Username string `json:"username"`
FullName string `json:"full_name"`
Bio string `json:"bio"`
FollowedBy int64 `json:"followed_by"`
Follows int64 `json:"follo... |
// Copyright 2021 Frederik Zipp. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This example was ported from:
// https://codepen.io/hakimel/pen/KanIi
// Original copyright:
//
// Copyright (c) 2021 by Hakim El Hattab (https://codepen.io/h... |
package sensu
import (
"encoding/json"
"errors"
"fmt"
"github.com/bitly/go-simplejson"
"io/ioutil"
"log"
"path/filepath"
)
type ClientConfig struct {
Name string `json:"name"`
Address string `json:"address"`
Version string `json:"version"`
Subscriptions []string `json:"subscripti... |
package main
import "github.com/davecgh/go-spew/spew"
type ListNode struct {
Val int
Next *ListNode
}
func addToFront(val int, head *ListNode) *ListNode {
temp := &ListNode{Val:val}
temp.Next = head
return temp
}
func lenList(l *ListNode) int {
var n int
for i:=l; i != nil; i = i.Next {
... |
package assets
import (
"embed"
)
//go:embed static
var Static embed.FS
|
package catp
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document01400101 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:catp.014.001.01 Document"`
Message *ATMDepositCompletionAdviceV01 `xml:"ATMDpstCmpltnAdvc"`
}
func (d *Documen... |
package 待分类
import "fmt"
type notifier interface {
notify()
}
type human struct {
name string
email string
}
func (h *human) notify() {
fmt.Printf("Sending human email to %s<%s>\n", h.name, h.email)
}
func main() {
h := human{"Tom", "110@qq.com"}
//sendNotification(h)
/*
# command-line-arguments
src... |
package main
import (
"fmt"
"math/rand"
"ms/sun_old/base"
"ms/sun/shared/helper"
"ms/sun/shared/x"
"time"
)
var i4 = 0
func main() {
base.DefultConnectToMysql()
for i := 0; i < 6; i++ {
go f4()
}
time.Sleep(time.Hour)
}
func f4() {
for {
arr := make([]x.HomeFanout, 0, 50)
for i := 0; i < 100; i++... |
package module
import (
"backend/src/global"
"gorm.io/gorm"
"time"
)
// 用户
type User struct {
BaseTable
// 用户名称
UserName string `json:"userName" form:"userName"`
// 密码
Password string `json:"password" form:"password"`
// 盐
Salt string `json:"salt" form:"salt"`
// 用户昵称
NickName string `json:"nickName" form... |
package main
import (
"fmt"
"net/http"
"github.com/mgarmuno/mediaWebServer/server/api/file"
"github.com/mgarmuno/mediaWebServer/server/api/omdb"
"github.com/mgarmuno/mediaWebServer/server/data"
)
func main() {
initialChecks()
fs := http.FileServer(http.Dir("client"))
http.Handle("/", fs)
http.Handle("/api/... |
package agent
import (
"errors"
"fmt"
"sync"
"time"
"golang.org/x/net/context"
"github.com/Sirupsen/logrus"
"github.com/bryanl/dolb/kvs"
)
var (
// checkTTL is the time to live for cluster member keys
checkTTL = 10 * time.Second
// ErrClusterNotJoined is returned when this agent has not joined a cluster.... |
package config
// Config is the configuration struct
type Config struct {
LogLevel string `default:"debug"`
CoSign CoSignConfig
Address string `default:"0.0.0.0:8080"`
}
// CoSignConfig contains the credentials for info exposed through the webapi
type CoSignConfig struct {
Name string `required:"true"`
Pas... |
package controllers
import (
"github.com/astaxie/beego"
"reporter/models"
"didapinche.com/db_util"
"gotool/generator"
"github.com/astaxie/beego/config"
"reporter/vo"
"com.didapinche.go.commons/log"
"fmt"
)
type MainController struct {
beego.Controller
}
func (c *MainController) Post() {
iniconf, err := con... |
package main
import (
"fmt"
"sort"
"strings"
"github.com/bwmarrin/discordgo"
)
func getRole(s *discordgo.Session, u *discordgo.User, m *discordgo.Message, roleName string) bool {
// see what the user permission level is
roles, err := s.GuildRoles(m.GuildID)
if err != nil {
fmt.Printf("Error getting roles: %... |
// Copyright (c) 2020 Blockwatch Data Inc.
// Author: alex@blockwatch.cc
package models
import (
"math"
"sync"
"tezos_index/chain"
)
var incomePool = &sync.Pool{
New: func() interface{} { return new(Income) },
}
// Income is a per-cycle income sheet for baker accounts.
type Income struct {
RowId ... |
/**
* day 05 2020
* https://adventofcode.com/2020/day/5
*
* compile: go build main.go
* run: ./main < input
* compile & run: go run main.go < input
**/
package main
import (
"bufio"
"fmt"
"os"
"sort"
)
// get upper 7 bits - the 'F' and 'B' part
func upper7Bits(b int) int {
return (b >> 3) & 0x7F
}
/... |
package main
import (
"github.com/gin-gonic/gin"
"github.com/gin-gonic/contrib/static"
"fmt"
// "database/sql"
_ "github.com/lib/pq"
)
const (
host = "localhost"
port = 5432
user = "user"
password= "mysecretpassword"
dbname = "test"
)
func main() {
/*
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s passw... |
package mqtt
import (
"context"
"io/ioutil"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/batchcorp/collector-schemas/build/go/protos/events"
"github.com/batchcorp/plumber-schemas/buil... |
package tls
import (
"bytes"
"encoding/pem"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/openshift/installer/pkg/asset"
)
// CertBundle contains a multiple certificates in a bundle.
type CertBundle struct {
BundleRaw []byte
FileList []*asset.File
}
// Cert returns the certificate bundle... |
package domain
import "errors"
var (
ErrVideoNotFound = errors.New("video not found")
ErrFailedDeleteLike = errors.New("failed delete like")
ErrFailedAddLike = errors.New("failed add like")
ErrInternal = errors.New("internal error")
ErrAlreadyLike =... |
package xpost
import (
"errors"
)
var gExchanger *Exchanger
func init() {
if gExchanger == nil {
gExchanger = &Exchanger{
xp: nil,
wires: make(map[string]*wire)}
}
}
// GetExchanger returns a global default exchanger instance
func GetExchanger() *Exchanger {
if gExchanger == nil {
gExchanger = &Exc... |
package ipproxy
import (
"sync"
)
// closeable is a helper type for asynchronous processes that follow an orderly
// close sequence.
type closeable struct {
finalizer func() error
closeCh chan struct{}
readyToFinalizeCh chan struct{}
closedCh chan struct{}
closeNowOnce sync.Once
... |
package config
import (
"path/filepath"
"sync"
"github.com/BurntSushi/toml"
)
type mallConf struct {
Title string `toml:"title"`
Server struct {
Port string `toml:"port"`
} `toml:"server"`
Token struct {
Secret string `toml:"secret"`
} `toml:"token"`
Datebases struct {
Alpha struct {
Host ... |
package leetcode
/*You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.
The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship b... |
package main
//#include <unistd.h>
import "C"
import (
linuxproc "github.com/c9s/goprocinfo/linux"
"github.com/prometheus/client_golang/prometheus"
"strconv"
"time"
)
type Core struct {
ID int
IdleTime uint64
}
type StatReader func(string) (*linuxproc.Stat, error)
var (
sysCpuGaugeVec = prometheus.New... |
package main
import "testing"
func TestSum(test *testing.T) {
result := sum(5, 5)
shouldBe := 10
if result != shouldBe {
test.Errorf("Função sum deveria retornar 10, mas retornou %v", result);
}
} |
/*
* @lc app=leetcode.cn id=416 lang=golang
*
* [416] 分割等和子集
*/
// @lc code=start
package main
import "fmt"
import "sort"
func canPartition(nums []int) bool {
sum := 0
for _, v := range nums {
sum += v
}
if sum % 2 != 0 {
return false
}
target := sum / 2
sort.Ints(nums)
sum2 := 0
for _, v := rang... |
// Copyright 2021 Akamai Technologies, 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... |
package reporter
import (
"fmt"
"os"
)
// Reporter interface is responsible for reporting responses in the event of an
// errors. We make it an interface so its easier to inject a mock for unit
// testing.
type Reporter interface {
ReportIfError(error, string, ...interface{})
}
// FmtReporter is a production imp... |
package main
import (
"testing"
"time"
)
func TestBanTimes(t *testing.T) {
timeinfuture := time.Date(time.Now().Year()+1, time.September, 10, 23, 0, 0, 0, time.UTC)
timeinpast := time.Date(time.Now().Year()-1, time.September, 10, 23, 0, 0, 0, time.UTC)
uid := Userid(1)
ip := "10.1.2.3"
bans.users... |
package domain
import "github.com/google/uuid"
type uuidPlayerIdGenerator struct {
}
func NewUUIDPlayerIdGenerator() PlayerIdGenerator {
return uuidPlayerIdGenerator{}
}
func (g uuidPlayerIdGenerator) Generate() PlayerId {
return uuid.New()
}
|
/*
Copyright (C) 2018 Black Duck Software, Inc.
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version... |
package twine
import (
"bytes"
"testing"
)
var tests = []struct {
key []byte
plain []byte
cipher []byte
}{
// http://jpn.nec.com/rd/crl/code/research/image/twine_SAC_full_v4.pdf
{
[]byte{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99},
[]byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef},... |
// Copyright © 2010-12 Qtrac Ltd.
//
// This program or package and any associated files are licensed under the
// Apache License, Version 2.0 (the "License"); you may not use these files
// except in compliance with the License. You can get a copy of the License
// at: http://www.apache.org/licenses/LICENSE-2.0.
//
... |
func isPalindrome(x int) bool {
if x < 0 {
return false
}
if x == 0 || x == x % 10{
return true
}
if x/10 == 0 {
return false
}
x_ary := []int{}
rightDigit := 0
for x > 0 {
rightDigit = x % 10
x = x / 10
x_ary = append(x_ary, rightD... |
package handler
import (
"testing"
"github.com/gin-gonic/gin"
)
func TestNewHandler(t *testing.T) {
h := func(c *gin.Context) (resp Response, err *ErrResponse) {
return nil, nil
}
NewHandler(h)
h = func(c *gin.Context) (Response, *ErrResponse) {
return nil, &ErrResponse{}
}
NewHandler(h)
}
|
package utils
import (
"fmt"
"unsafe"
)
//打印浮点数的特定表现格式
func Float64Bits(f float64, d int) {
b := *(*uint64)(unsafe.Pointer(&f))
switch d {
case 16:
fmt.Printf("浮点数%.1f的16进制表示是%016x\n", f, b)
case 2:
fmt.Printf("浮点数%.1f的2进制表示是%02b\n", f, b)
default:
fmt.Println("error decimal: ", d)
}
}
|
package location
import (
"context"
"fmt"
"log"
"os"
"strings"
"time"
"github/thisissoon/Go-Cloud-Functions-Examples/functions/events/location/updateLocation/postcodes"
"github/thisissoon/Go-Cloud-Functions-Examples/functions/events/location/updateLocation/storage"
"cloud.google.com/go/firestore"
firebase ... |
/*
MIT License
Copyright (c) 2020 Operator Foundation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, pub... |
package client
import (
"context"
"fmt"
"io"
"github.com/qnib/metahub/pkg/registry"
"github.com/docker/distribution"
"github.com/docker/distribution/reference"
registryClient "github.com/docker/distribution/registry/client"
"github.com/opencontainers/go-digest"
manifestListSchema "github.com/docker/distrib... |
package requests
// This is a common base for most requests
type BaseRequest struct {
Action string `json:"action" mapstructure:"action"`
Wallet string `json:"wallet" mapstructure:"wallet"`
BpowKey *string `json:"bpow_key,omitempty" mapstructure:"bpow_key,omitempty"`
}
|
package schema
// AssetType define an asset type
type AssetType string
// RelationKeyType define a relation type
type RelationKeyType string
// RelationType define a relation type
type RelationType struct {
FromType AssetType `json:"from_type"`
Type RelationKeyType `json:"relation_type"`
ToType AssetT... |
package rsa
/*
Reference: https://medium.com/better-programming/build-an-rsa-asymmetric-cryptography-generator-in-go-d202b18bcfd0
Do take sometime to read the blog post from the above link, the below package code combines PEM and writeFile functions into one function.
*/
import (
"crypto/rand"
"crypto/rsa"
"cryp... |
package testutil
import (
"crypto/md5"
"database/sql"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"cinemo.com/shoping-cart/framework/db"
"cinemo.com/shoping-cart/pkg/projectpath"
"cinemo.com/shoping-cart/pkg/trace"
"github.com/golang-migrate/migrate/v4"
// include migrate file driver
"github.com/golang-migr... |
package config
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestGetRedis(t *testing.T) {
defer func() {
if r := recover(); r != nil {
t.Fatal("Panic error:", r)
}
}()
_ = GetRedis()
assert.True(t, true)
}
|
package main
import (
"fmt"
)
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
type ListNode struct {
Val int
Next *ListNode
}
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil && l2 == nil {
return nil
}
n3 := new(List... |
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package packet
import (
"errors"
"math"
)
const tcpHeaderLength = 20
// maxPacketLength is the largest length that all headers support.
// IPv4... |
package collectors
import (
"time"
"github.com/cloudfoundry-community/go-cfclient"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/log"
)
type RoutesCollector struct {
namespace string
environment string
deployment ... |
package game
import (
"errors"
"awesome-dragon.science/go/goGoGameBot/internal/command"
"awesome-dragon.science/go/goGoGameBot/internal/config/tomlconf"
"awesome-dragon.science/go/goGoGameBot/pkg/format"
)
func (g *Game) createCommandCallback(fmt format.Format) command.Callback {
return func(data *command.Data)... |
package sorting
// InsertionSort sorting algorithm implementation
// Time complexity: O(n^2)
// Space complexity: O(1)
func InsertionSort(arr []int) {
for j := 1; j < len(arr); j++ {
key := arr[j]
i := j - 1
for i >= 0 && arr[i] > key {
arr[i+1] = arr[i]
i--
}
arr[i+1] = key
}
}
|
package dict
import (
"bytes"
"compress/zlib"
"encoding/binary"
"io/ioutil"
"sync"
)
const (
MAXIMUM_LEADBYTES = 12
SIZE_OF_WCHAR = 2
UnicodeNull = 0
)
const (
MB_TBL_SIZE = 256 /* size of MB tables */
GLYPH_TBL_SIZE = MB_TBL_SIZE /* size of GLYPH tables */
DBCS_TBL_SIZE = 256 ... |
package main
import (
"fmt"
"encoding/json"
)
func main() {
type User struct {
FirstName string
LastName string
Books [] string
}
userVar1 := &User{
FirstName: "John",
LastName: "Smith",
Books: []string{ "The Art of Programming", "Golang for Dummies" }}
userVar2, _ := json.Marshal(use... |
package utils
import (
"errors"
"strconv"
"github.com/gin-gonic/gin"
)
func GetInt64InQuery(c *gin.Context, name string) (int64, error) {
str, ok := c.GetQuery(name)
if !ok {
return 0, errors.New("miss parameter " + name + " InQuery")
}
return strconv.ParseInt(str, 10, 64)
}
|
package encryptor
import (
"time"
)
type fakeEncryptor struct {
singleFrameEncryptionTimeInMs time.Duration
}
func NewEncryptor(singleFrameEncryptionTimeInMs time.Duration) *fakeEncryptor {
return &fakeEncryptor{
singleFrameEncryptionTimeInMs: singleFrameEncryptionTimeInMs,
}
}
func (f *fakeEncryptor) Encrypt... |
package cotacao
import (
"fmt"
"github.com/fabioxgn/go-bot"
"github.com/fabioxgn/go-bot/web"
)
var (
url = "http://developers.agenciaideias.com.br/cotacoes/json"
)
type retorno struct {
Bovespa struct {
Cotacao string `json:"cotacao"`
Variacao string `json:"variacao"`
} `json:"bovespa"`
Dolar struct {
... |
// Package deferred has machinery for providing JavaScript with
// deferred values. These arise because we want to have library
// functions for JavaScript to request things that will only later be
// supplied -- either because it will take some time to get, and it's
// better if JavaScript doesn't have to block (e.g.,... |
package backup
import (
"context"
"go.mongodb.org/mongo-driver/bson/primitive"
"golang.org/x/oauth2"
)
func tokenSource(ctx context.Context, id primitive.ObjectID, s *Service,
ts oauth2.TokenSource) *dbTokenSource {
return &dbTokenSource{
ctx: ctx,
id: id,
src: ts,
service: s,
}
}
type d... |
package domain
import "time"
type SessionStorageService interface {
// Close closes the storage connection
Close() error
// CreateSession creates a new session. It errors if a valid session already exists.
CreateSession(accountID string, sessionKey string, expirationDuration time.Duration) error
// FetchPossib... |
//---devendo exercicios 3, 4 e 5
|
package im
import (
"github.com/astaxie/beego"
)
func init() {
// Mapping user routing
// deprecated
// beego.Router("/api/v1/im/user/:uid/register", &Controller{}, "post:RegisterUsers")
// beego.Router("/api/v1/im/user/:uid", &Controller{}, "get:GetSessionByUID")
beego.Router("/api/v1/im/user/:uid/sendmessage"... |
package dcmdata
import (
"log"
"github.com/grayzone/godcm/ofstd"
)
type DcmItem struct {
DcmObject
elementList *DcmList
lastElementComplete bool
fStartPosition int
}
func NewDcmItem(tag DcmTag, len uint32) *DcmItem {
return &DcmItem{*NewDcmObject(tag, len), nil, true, 0}
}
/** Virtual object co... |
package actions
import (
"os"
)
type ActionFunc func()
func Quit(){
os.Exit(0)
}
func Ignore(){
}
|
package dummy
import (
"io/ioutil"
"math/rand"
"time"
"github.com/sherifabdlnaby/prism/pkg/component"
"github.com/sherifabdlnaby/prism/pkg/config"
"github.com/sherifabdlnaby/prism/pkg/payload"
"github.com/sherifabdlnaby/prism/pkg/response"
"go.uber.org/zap"
)
//Dummy Dummy ProcessReadWrite that does absolute... |
/*
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 goauth
import (
"io"
"net/http"
"net/http/httptest"
)
type testCase struct {
method string
url string
body io.Reader
handler http.HandlerFunc
request func(r *http.Request)
expect func(r *httptest.ResponseRecorder)
}
func testCases(tcs []testCase) {
for _, tc := range tcs {
w := httptest.... |
/*
In The Netherlands we have PostNL, the postal company. They use KixCodes, it's a fast way to deliver letters and packages that can be scanned during the process.
Kix Code
https://www.postnl.nl/Images/KIX-code-van-PostNL_tcm10-8633.gif
The code is a combination of: Postal code, House/box/call number and House app... |
package memorydll
//#include<stdlib.h>
// extern void * MemoryLoadLibrary(const void *);
// extern void * MemoryGetProcAddress(void *, char *);
// extern void MemoryFreeLibrary(void *);
import "C"
import (
"unsafe"
"errors"
"syscall"
"fmt"
)
type Handle uintptr
// A DLL implements access to a singl... |
package key
import (
"github.com/giantswarm/apiextensions/pkg/apis/provider/v1alpha1"
"github.com/giantswarm/aws-operator/service/controller/clusterapi/v29/templates/cloudconfig"
)
// NOTE that code below is deprecated and needs refactoring.
func CloudConfigSmallTemplates() []string {
return []string{
cloudcon... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.