text stringlengths 11 4.05M |
|---|
package cmd
import (
"encoding/json"
"fmt"
"code.cloudfoundry.org/cfdev/config"
)
type Catalog struct {
UI UI
Config config.Config
}
func (c *Catalog) Run(args []string) error {
bytes, err := json.MarshalIndent(c.Config.Dependencies, "", " ")
if err != nil {
return fmt.Errorf("unable to marshal catalo... |
package gorms
import (
"gorm.io/driver/postgres"
)
func NewPostgresAdapter(settings GormSettings) *adapter {
return &adapter{
dialector: postgres.New(postgres.Config{
DSN: settings.ConnectionString,
PreferSimpleProtocol: true, // disables implicit prepared statement usage
}),
settings: ... |
// main.go
package main
import (
"github.com/go-gl/gl"
glfw "github.com/go-gl/glfw3"
)
var rtri, rquad float32 = 0, 0 // 用于三角形的角度
func draw() { // 从这里开始进行所有的绘制
gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) // 清除屏幕和深度缓存
gl.LoadIdentity() // 重置当前的模型观察矩阵
gl.... |
// Copyright © 2020 Attestant Limited.
// 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 leetcode
func lengthOfLongestSubstring(s string) int {
cmap := make(map[rune]int, 0)
max := 0
start := 0
for i, c := range []rune(s) {
if idx, ok := cmap[c]; ok {
start = MathMax(start, idx)
}
max = MathMax(max, i-start+1)
cmap[c] = i + 1
}
return max
}
|
package resolvers
import (
"context"
"github.com/syncromatics/kafmesh/internal/graph/generated"
"github.com/syncromatics/kafmesh/internal/graph/model"
"github.com/pkg/errors"
)
//go:generate mockgen -source=./processorJoin.go -destination=./processorJoin_mock_test.go -package=resolvers_test
// ProcessorJoinLoa... |
package utils
import (
"../config"
"github.com/go-redis/redis"
"time"
)
var (
// RedisClient is the connection handle
// for the database
RedisClient *redis.Client
)
func OpenDbConnexion() {
RedisClient = redis.NewClient(&redis.Options{
Addr: config.Config.RedisHost,
Password: "",
DB: ... |
package common
import (
"crypto/sha256"
"golang.org/x/crypto/sha3"
)
// SHA256 calculates SHA256-256 hashing of input b
// and returns the result in bytes array.
func SHA256(b []byte) []byte {
hash := sha256.Sum256(b)
return hash[:]
}
// HashB calculates SHA3-256 hashing of input b
// and returns the result in b... |
/*
Copyright 2020 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 consumer
import (
"log"
"github.com/streadway/amqp"
"github.com/vdntruong/rabbitmq/util"
)
func Topic(ch *amqp.Channel, stop chan bool) {
err := ch.ExchangeDeclare(
"logs", // name
"fanout", // type
true, // durable
false, // auto-deleted
false, // internal
false, // no-wait
... |
package discord // "github.com/itszuvalex/mcdiscord/pkg/discord"
import (
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/bwmarrin/discordgo"
"github.com/itszuvalex/mcdiscord/pkg/api"
)
const (
Emoji_Check string = "✅"
Emoji_X string = "❌"
ConfigKey = "discord"
BufferSize ... |
package main
import (
"context"
"fmt"
"net/http"
"github.com/google/go-github/github"
)
func fetchLicenseList() ([]*github.License, error) {
// Create default client
client := github.NewClient(nil)
// Fetch list of LICENSE from Github API
list, res, err := client.Licenses.List(context.Background())
if err ... |
package controller
import (
"strings"
"github.com/pubg/kube-image-deployer/util"
"k8s.io/klog"
)
type Image struct {
key string
containerName string
url string
tag string
}
func (c *Controller) syncKey(key string) error {
obj, exists, err := c.indexer.GetByKey(key)
if err != ... |
// CSI2520 - Devoir 1 - GO
// Joshua O'Reilly
// 8359885
package main
import (
"errors"
"fmt"
"strings"
)
// DistToToronto - approximate distance from Ottawa to Toronto
const DistToToronto float32 = 351 // Km
// DistToMontreal - approximate distance from Ottawa to Montreal
const DistToMontreal = 200 ... |
package main
import (
"log"
"menteslibres.net/gosexy/redis"
"strings"
"time"
)
var host = "127.0.0.1"
var port = uint(6379)
func spawnPublisher() error {
var err error
var publisher *redis.Client
publisher = redis.New()
err = publisher.Connect(host, port)
if err != nil {
log.Fatalf("Publisher failed to... |
package main
import (
"fmt"
)
type Integrante struct {
Nombre string
}
type Banda struct {
Nombre string
Integrantes []Integrante
}
func main() {
banda1 := Banda{
Nombre: "U2",
Integrantes: []Integrante{
Integrante{
Nombre: "Bono",
},
Integrante{
Nombre: "The Edge",
},
Integra... |
package 二维子串问题
// dp[i][t] 表示: 以A[i-1]、B[t-1]结尾的连续公共数组长度(从右到左可以拓展多长)
// 状态转移方程:
// A[i-1] == B[t-1]: dp[i][t] = dp[i-1][t-1] + 1
// A[i-1] != B[t-1]: dp[i][t] = 0
func findLength(A []int, B []int) int {
dp := [1005][1005]int{}
ans := 0
for i := 1; i <= len(A); i++ {
for t := 1; t <= len(B); t++ {
if A[i-1... |
package jobs
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/url"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
deployer "github.com/h... |
package fibonacci
import "testing"
func TestNum(t *testing.T) {
tests := []struct {
name string
arg int
want int
}{
{"1", -1, 0},
{"2", 0, 0},
{"3", 1, 0},
{"4", 2, 1},
{"5", 3, 1},
{"6", 4, 2},
{"7", 32, 1346269},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := ... |
package slices
import (
"github.com/life4/genesis/constraints"
)
// Any returns true if f returns true for any element in arr
func Any[S ~[]T, T any](items S, f func(el T) bool) bool {
for _, el := range items {
if f(el) {
return true
}
}
return false
}
// All returns true if f returns true for all elemen... |
package core
import (
"fmt"
"strconv"
"strings"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/any"
libp2pc "github.com/libp2p/go-libp2p-core/crypto"
peer "github.com/libp2p/go-libp2p-core/peer"
mh "github.com/multiformats/go-multihash"
"github.com/... |
/*
Created by: Maulik Shah (mshah@redhat.com)
Date Created: 10/08/2018
File to define the s3 connectors and functions
*/
package main
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/endpoints"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aw... |
package model
type LinkReceiveResult struct {
Packet IpPacket
ReceivedFrom VirtualIp
}
|
package main
import (
"fmt"
"structures/computer"
)
//Employee structure
type Employee struct {
firstName, secondName string
age, salary int
}
//Person structure
type Person struct {
string
int
Address
}
//Address structure
type Address struct {
city, address string
}
func main() {
//creating na... |
package main
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"os"
)
// 自己编写一个函数,接收两个文件路径 srcFileName dstFileName
func CopyFile(dstFileName string, srcFileName string) (written int64, err error) {
srcFile, err := os.Open(srcFileName)
if err != nil {
fmt.Printf("open file err=%v\n", err)
}
defer srcFile.Close()
r... |
package cmd
import (
"github.com/bitmaelum/bitmaelum-suite/cmd/bm-client/handlers"
"github.com/sirupsen/logrus"
"os"
"github.com/spf13/cobra"
)
var readCmd = &cobra.Command{
Use: "read",
Aliases: []string{"read-message", "r"},
Short: "Read messages for your account",
Long: `Read message from your account
`... |
package db
import (
"github.com/boltdb/bolt"
"log"
"time"
"encoding/json"
)
type List struct{
Id string
Name string
Body string
Created time.Time
}
func (list *List) Save() error{
Ddb.Update(func(tx *bolt.Tx) error {
log.Println("--- Save List")
b := tx.Bucket([]byte("List"))
encoded, err ... |
package Bucket
type Bucket struct {
value int
}
func NewBucket() Bucket {
return Bucket{value: -2}
}
func (b *Bucket) GetValue() int {
return b.value
}
func (b *Bucket) SetValue(value int) {
b.value = value
}
func (b *Bucket) Remove() {
b.value = -1
}
func (b *Bucket) Empty() bool {
return b.value == -1 || ... |
package main
import "fmt"
func main() {
months := []string{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
quarter1 := months[0:3]
quarter2 := months[3:6]
quarter3 := months[6:9]
quarter4 := months[9:12]
fmt.Println(quarter1, len(quarter1... |
package model
import (
"appengine"
"appengine/datastore"
"time"
"net/http"
"errors"
"strconv"
)
type Transaction struct {
CategoryKey *datastore.Key
Location string
Description string
Date time.Time
Amount float32
// Not included in datastore
Key *datastore.Key `datastore:"-"`
Category *Category `datas... |
package calendar
import (
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/andywow/golang-lessons/lesson-calendar/pkg/eventapi"
)
func TestCheckEventData(t *testing.T) {
event := &eventapi.Event{}
err := CheckEventData(event)
require.Error(t, err)
eventTime := time.Now()
event = &eventap... |
package types
type Runtime = string
// List of supported runtimes
const (
Nodejs12 Runtime = "nodejs12"
Nodejs10 Runtime = "nodejs10"
Python38 Runtime = "python38"
)
|
package controller
import (
"github.com/gin-gonic/gin"
"net/http"
)
func GetLogin(c *gin.Context) {
c.HTML(http.StatusOK,"login.html",nil)
}
func GetPassword(c *gin.Context) {
c.HTML(http.StatusOK,"password.html",nil)
} |
package main
import (
"fmt"
"github.com/muhammadzhuhry/belajar-golang-dasar/helper"
)
func main() {
helper.SayHello("Zuhri")
//helper.sayGoodbye("Zuhri") // error
fmt.Println(helper.Application)
//fmt.Println(helper.version) // error
}
// ACCESS MODIFIER
// Di bahasa pemrograman lain, biasanya ada kata kunci y... |
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"log"
"math"
"math/rand"
"net/http"
"sort"
"strconv"
"syscall"
"time"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(h *http.Request) bool {
return true
},
}... |
package reiro
import "strings"
const allowedVariableNameSymbols = "$_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const allowedSpaceSymbols = " \t\n\r"
const allowedNumbers = "0123456789"
const allowedSymbols = "!@#$%^&*()_+.,;:'\\/\""
const allowedBrackets = "[]{}<>()"
// ParserVariableName parser
func Par... |
package kv
import (
"encoding/json"
"fmt"
"github.com/yddeng/raft"
"net/http"
"sync"
)
var (
rf *raft.Raft
kvStorage *KV
rfMtx sync.Mutex
)
type KV struct {
Data map[string]string
sync.Mutex
}
func (this *KV) Set(k, v string) {
this.Lock()
defer this.Unlock()
this.Data[k] = v
}
func (this *... |
package apiclient
import (
"context"
"google.golang.org/grpc"
workflowpkg "github.com/argoproj/argo/pkg/apiclient/workflow"
"github.com/argoproj/argo/pkg/apis/workflow/v1alpha1"
grpcutil "github.com/argoproj/argo/util/grpc"
)
type errorTranslatingWorkflowServiceClient struct {
delegate workflowpkg.WorkflowSer... |
// Copyright (c) 2017 Darren Whitlen <darren@kiwiirc.com>
// released under the MIT license
package bncDataStoreBuntdb
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"log"
"strings"
"time"
"github.com/goshuirc/bnc/lib"
"github.com/tidwall/buntdb"
)
type DataStore struct {
ircbnc.DataStoreInterf... |
package pam
import (
"github.com/odwrtw/papi"
"github.com/odwrtw/polochon/lib"
)
func showPolochonToPapi(show *polochon.Show) (*papi.Show, error) {
if show.ImdbID == "" {
return nil, ErrMissingImdbID
}
return &papi.Show{ImdbID: show.ImdbID}, nil
}
func showPapiToPolochon(papiShow *papi.Show, polochonShow *po... |
package main
import "strings"
type Round struct {
opponent string
you string
expected string
rock map[string]int
paper map[string]int
scissors map[string]int
part2 map[string]map[string]int
}
func NewRound(input string) *Round {
plays := strings.Split(input, " ")
return &Round{
opponent: pl... |
package cli_test
import (
"fmt"
"testing"
"time"
"github.com/InjectiveLabs/injective-oracle-scaffold/injective-chain/app"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/crypto/hd"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
servertypes "github.com/cosmos/cosmos-sdk/server/types"
"gith... |
package conclusion
func isPerfectSquare(num int) bool {
// positive integer num
if num <= 1 {
return true
}
low, high := 1, num
for low <= high {
mid := low + (high-low)>>1
mul := mid * mid
if mul == num {
return true
} else if mul > num || mul <= 0 { // mul <= 0 means overflow
high = mid - 1
}... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-08-18 13:29
# @File : of_剑指_Offer_11_旋转数组的最小数字.go
# @Description :
# @Attention :
*/
package offer
func minArray(numbers []int) int {
start := 0
end := len(numbers) - 1
for start < end {
mid := start + (end-start)>>1
if numbers[mid] < numbers[end] {... |
package customer
import (
"database/sql"
"fmt"
"log"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/korrawit/finalexam/repository"
)
type CustomerContext struct {
Repo interface {
CreateNewCustomer(c *repository.Customer) error
GetCustomers() ([]repository.Customer, error)
GetCustomerById(... |
package config
import (
"github.com/kelseyhightower/envconfig"
)
type dbParams struct {
Host string `envconfig:"DB_HOST" default:"127.0.0.1"`
Port string `envconfig:"DB_PORT" default:"5432"`
User string `envconfig:"DB_USER" default:"netlabi"`
DbName string `envconfig:"DB_NAME" default:"netlabi"`
P... |
package main
import (
"fmt"
)
// https://leetcode-cn.com/problems/subarray-sum-equals-k/
//------------------------------------------------------------------------------
// solution 1
func subarraySum(nums []int, k int) int {
n := len(nums)
if n < 1 {
return 0
}
// sum -> index array
m := make(map[int][]in... |
package util
import (
"fmt"
"net/http"
"github.com/GoPracPro/src/local/platform/rest"
"github.com/GoPracPro/src/local/platform/rest/util"
)
//ExecuteGET for input URL and attach reponse to input responseModel which should be
//reference of the response model which needs to be type case as api reponse specificati... |
// 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 router
import (
"github.com/tailscale/wireguard-go/device"
"github.com/tailscale/wireguard-go/tun"
"tailscale.com/types/logger"
)
type ... |
package pod
import (
"context"
"github.com/projecteru2/cli/cmd/utils"
corepb "github.com/projecteru2/core/rpc/gen"
"github.com/juju/errors"
"github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
)
type removePodOptions struct {
client corepb.CoreRPCClient
name string
}
func (o *removePodOptions) run(ctx... |
package main
import (
"strconv"
"fmt"
)
func main() {
x:= 2.4
y := 2
fmt.Println(x / float64(y))
nota := 6.9
notaFinal := int(nota)
fmt.Println(notaFinal)
fmt.Println("Teste", string(97)) // Não converte int em string e sim o correspondente da tabela unicode
fmt.Println("Teste", strconv.Itoa(97))
num... |
package main
import (
"fmt"
"net/http"
"./data"
)
// GET /threads/new
// 发帖页
func newThread(writer http.ResponseWriter, request *http.Request) {
_, err := session(writer, request)
if err != nil {
http.Redirect(writer, request, "/login", 302)
} else {
generateHTML(writer, nil, "layout", "private.navbar", "n... |
package binchunk
import "github.com/hilarryxu/golua/types"
func Undump(data []byte) *types.Prototype {
reader := &reader{data}
reader.checkHeader()
return nil
}
|
package formula
import (
"fmt"
"regexp"
"strconv"
)
// Roll represents the component parts of a dice formula that can be used to actually perform a rolling of dice.
type Roll struct {
Count int
Sides int
Modifier int
Extensions map[string][]string
}
/**
* Formula
* A dice formula is a string that breaks dow... |
// mysql
// go get -u github.com/go-sql-driver/mysql
package main
// "encoding/json"
import (
"database/sql"
"fmt"
"strconv"
_ "github.com/Go-SQL-Driver/MySQL"
)
//Db数据库连接池
var DB *sql.DB
func main() {
//连接至数据库
// sql.Open()中的数据库连接串格式为:"用户名:密码@tcp(IP:端口)/数据库?charset=utf8"。
db, _ := sql.Open("mysql", "roo... |
package controller
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"github.com/gorilla/mux"
"github.com/gorilla/schema"
"github.com/oceanpkg/ocean-backend/internal/auth"
"github.com/oceanpkg/ocean-backend/internal/database"
"github.com/oceanpkg/ocean-backend/internal/util"... |
package model
type Int64Set struct {
elements map[int64]bool
}
func NewInt64Set() *Int64Set {
return &Int64Set{
elements: make(map[int64]bool),
}
}
func (s *Int64Set) Put(i int64) {
s.elements[i] = true
}
func (s *Int64Set) Delete(i int64) {
delete(s.elements, i)
}
func (s *Int64Set) Values() []int64 {
var... |
package info
import (
"io"
"fmt"
"os"
"net/url"
"github.com/trevershick/analytics2-cli/a2m/config"
"github.com/trevershick/analytics2-cli/a2m/rest"
"github.com/pivotal-golang/bytefmt"
)
type showCollectionArgs struct {
config *config.Configuration
workspaceId int
loader rest.Loader
writer io.Writer
}
func... |
package main
import(
"fmt"
"strings"
)
// ## 1.题目描述
/*
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
链接:https://leetcode-cn.com/problems/reverse-integer
*/
// ## 2.实现方式一... |
package dbaccess
import (
"log"
"sync"
"time"
)
const restaurantWithIDSql = `
SELECT r.name, r.name_fa, r.address, r.address_fa
FROM restaurants r
WHERE r.id = $1
`
type (
// Restaurant stores all the data
Restaurant struct {
Name string
Name_fa string
Address string
Address_fa string
... |
// Code references : https://github.com/netsec-ethz/scion-homeworks/blob/master/latency/timestamp_client.go and reference https://github.com/perrig/scionlab/blob/master/sensorapp/sensorfetcher/sensorfetcher.go
package main
import (
"flag"
"fmt" //importing fmt package for printing
"log"
"math... |
/*-
* Copyright (c) 2017, F5 Networks, 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... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-08-16 13:40
# @File : insert_sort.go
# @Description : 插入排序
# @Attention :
*/
package sort
func InsertSort(data []int) {
for i := 1; i < len(data); i++ {
val := data[i]
j := i - 1
for ; j >= 0 && data[j] > val; j-- {
data[j+1] = data[j]
}
data[... |
package commands
import (
"log"
"github.com/dolab/logger"
)
var (
stderr *logger.Logger
envTemplate = `#!/usr/bin/env bash
export APPROOT=$(pwd)
# adjust GOPATH
case ":$GOPATH:" in
*":$APPROOT:"*) :;;
*) GOPATH=$APPROOT:$GOPATH;;
esac
export GOPATH
# adjust PATH
readopts="ra"
if [ -n "$ZSH_VERSION" ... |
// Package clock provides interface to manage nRF51 clocks source/generation.
package clock
import (
"mmio"
"unsafe"
"nrf5/hal/internal/mmap"
"nrf5/hal/te"
)
// Periph represents clock management peripheral.
type Periph struct {
te.Regs
_ [2]mmio.U32
hfclkrun mmio.U32
hfclkstat mmio.U32
_... |
package web
import (
"encoding/json"
"fmt"
"net/http"
zs "github.com/zerostick/zerostick/daemon"
)
// Wifilist scans the network for available SSIDs and returns a list in JSON
func Wifilist(w http.ResponseWriter, r *http.Request) {
wifiList, err := zs.ScanNetworks()
if err != nil {
fmt.Println(err, "Error sc... |
package cmd
import "github.com/spf13/cobra"
func newZonesCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "zones",
Aliases: []string{"z", "zone"},
Short: "Overview for Zones within an account",
Long: "Zones:\nA Zone is a domain name along with its subdomains and other identities",
Run: func(cmd ... |
package writer
// Writer for writing to outputs
type Writer interface {
Write() error
}
|
package dbtools
// podstawowa obsluga ORM bazy danych
//TWORZNEI MODELU i podstawowe inserty
import (
"log"
//"time"
"mstr"
// "mstr"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
//_ "github.com/jinzhu/gorm/dialects/mysql"
)
var DB *gorm.DB
func init() {
var err error
//DB, err = ... |
package database
import (
"context"
"errors"
"github.com/anshap1719/authentication/models"
"github.com/gofrs/uuid"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"time"
)
var ErrInstagramAccountNotFound = errors.New("No InstagramAccount found in the database")
var ErrInstagramConnection... |
package honeycombio
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
)
func TestDatasets(t *testing.T) {
ctx := context.Background()
c := newTestClient(t)
datasetName := testDataset(t)
currentDataset := &Dataset{
Name: datasetName,
Slug: urlEncodeDataset(datasetName),
}
t.Run("List",... |
package main
import (
"bufio"
"fmt"
"os"
)
func part1(bins []string) int {
var gamma int
var epsilon int
bits := len(bins[0])
binlen := len(bins)
ones := 0
for i := 0; i < bits; i++ {
ones = 0
for j := 0; j < binlen; j++ {
b := bins[j][i]
if b == '1' {
ones++
}
}
if ones > (binlen / 2... |
package zfs
// #include <stdlib.h>
// #include <string.h>
// #include <libzfs.h>
// #include "common.h"
// #include "zpool.h"
// #include "zfs.h"
import "C"
import (
"strings"
"syscall"
)
func (self *Dataset) CreateBookmark(name string) (*Dataset, error) {
sourcePath, _ := self.Path()
var bookmarkPath string
if... |
package graph
import "fmt"
func PrintMatrix(m [][]int) {
fmt.Println("矩阵如下:")
for _, v := range m {
fmt.Println(v)
}
}
|
package abstract_factory
type SportMotorbike struct {
}
func (s *SportMotorbike) GetType() int {
return 1
}
func (s *SportMotorbike) GetWeels() int {
return 2
}
func (s *SportMotorbike) GetSeats() int {
return 1
}
|
package Accountapi
import (
"BearApp/business/auth"
datastruct "BearApp/common/data_struct"
errorcode "BearApp/common/error_code"
constant "BearApp/constant"
"BearApp/handler/common"
"BearApp/model"
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"githu... |
package main
import (
"github.com/gin-gonic/gin"
)
var router *gin.Engine
func main() {
router = gin.Default()
router.LoadHTMLGlob("templates/*")
router.GET("/", ShowIndexPage)
router.GET("/article/view/:id", ShowArticlePage)
router.Run()
}
// func ShowIndexPage(c *gin.Context) {
// articles := getAllAr... |
//Comprehensive symbol table testing
package main;
func pain (b bool, ba []bool, a int, i float64, j1, j2 rune) int {
type int1 int;
type (
int2 int1
int3 int2
)
var f = 5;
var g int;
var h = true;
var h1, h2 = true, false;
var (
... |
package function
import (
"errors"
"fmt"
"github.com/10gen/realm-cli/internal/cli"
"github.com/10gen/realm-cli/internal/cli/user"
"github.com/10gen/realm-cli/internal/cloud/realm"
"github.com/10gen/realm-cli/internal/terminal"
"github.com/AlecAivazis/survey/v2"
)
type runInputs struct {
cli.ProjectInputs
N... |
package rivescript
import "errors"
// The types of errors returned by RiveScript.
var (
ErrDeepRecursion = errors.New("deep recursion detected")
ErrRepliesNotSorted = errors.New("replies not sorted")
ErrNoDefaultTopic = errors.New("no default topic 'random' was found")
ErrNoTriggerMatched = errors.New("no tr... |
package sese
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document00100102 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:sese.001.001.02 Document"`
Message *TransferOutInstructionV02 `xml:"TrfOutInstrV02"`
}
func (d *Document00100102) ... |
package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"os/exec"
"os/signal"
"strings"
"syscall"
)
var currentCmd *exec.Cmd
func main() {
initialize()
signalCh := make(chan os.Signal)
signal.Notify(signalCh, syscall.SIGINT)
stdin := bufio.NewReader(os.Stdin)
handleSignals := func() {
for {
sig :=... |
package main
import (
"github.com/preetampvp/gocal/calculator"
"github.com/rivo/tview"
)
func main() {
app := tview.NewApplication()
calculator := calculator.NewCalculator(app)
if err := app.SetRoot(calculator, true).Run(); err != nil {
panic(err)
}
}
|
package openshift
import (
"context"
"fmt"
"os"
"time"
"github.com/go-logr/logr"
configv1 "github.com/openshift/api/config/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtim... |
package main
import "fmt"
//interface
//カスタムエラー
/*
type error interface {
Error() string
}
*/
type MyError struct {
Message string
ErrCode int
}
func (e *MyError) Error() string {
return e.Message
}
func RaiseError() error {
return &MyError{Message: "カスタムエラーが発生しました", ErrCode: 500}
}
func main() {
err := R... |
package main
import (
"fmt"
"strconv"
"strings"
)
func getClosest(pos []int, board [][]string) []int {
for i := 0; i < len(board); i++ {
for j := 0; j < len(board[i]); j++ {
if board[i][j] == "d" {
dirty := []int{i, j}
return dirty
}
}
}
return pos
}
func getMove(pos []int, board [][]string) ... |
package watch
import (
"fmt"
"os"
"path/filepath"
"github.com/fsnotify/fsnotify"
)
func Watch(mainPath string) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
fmt.Println("Error, ", err)
}
defer watcher.Close()
//open the directory file
dir, err := os.Open(mainPath)
if err != nil {
fmt.Printf... |
package leetcode
import "testing"
func TestDistanceBetweenBusStops(t *testing.T) {
if distanceBetweenBusStops([]int{1, 2, 3, 4}, 0, 1) != 1 {
t.Fatal()
}
if distanceBetweenBusStops([]int{1, 2, 3, 4}, 0, 2) != 3 {
t.Fatal()
}
}
|
package main
import (
"fmt"
"math"
)
// 50. Pow(x, n)
// 实现 pow(x, n) ,即计算 x 的 n 次幂函数。
// 说明:
// -100.0 < x < 100.0
// n 是 32 位有符号整数,其数值范围是 [−2^31, 2^31 − 1] 。
// https://leetcode-cn.com/problems/powx-n/
func main() {
fmt.Println(myPow(2.0, 10))
fmt.Println(myPow2(2.0, 10))
// fmt.Println(myPow2(2.0, -2))
// fm... |
package main
import "fmt"
func main() {
type name [3]string
// type must be same to compare two arrays
a := name{"abc", "xyz"}
b := name{}
if a == b {
fmt.Println("Equal")
} else {
fmt.Println("not")
}
fmt.Printf("%#v", a)
}
|
package ibmcloud
// MachinePool stores the configuration for a machine pool installed on IBM Cloud.
type MachinePool struct {
// InstanceType is the VSI machine profile.
InstanceType string `json:"type,omitempty"`
// Zones is the list of availability zones used for machines in the pool.
// +optional
Zones []stri... |
package main
import (
"fmt"
"strings"
"github.com/charliegriefer/blackjack/cards"
p "github.com/charliegriefer/blackjack/player"
)
func main() {
var player p.Player
player.Name = "Player"
var dealer p.Player
dealer.Name = "Dealer"
// create a deck of cards, and shuffle it.
deck := cards.CreateDeck()
fmt.... |
package search
import (
"fmt"
"html"
"math"
"reflect"
"strconv"
)
type fallback interface {
Exec() (*searchResult, []error)
}
type searchHandler struct {
client searchClient
hasPagination bool
hasMetadata bool
path string
query map[string]string
search *string
filters ... |
// Bleeder provides a mechanism for seamlessly exhausting the buffered content of
// a bufio.Reader, then delegating further read requests to a separate reader.
//
// The original use case for this implementation was an efficient means of
// creating an 'expanding' bufio.Reader. Just continuing to create new bufio.Rea... |
package penyedia
import (
"encoding/json"
"github.com/yaziedda/iser/app/common"
"github.com/yaziedda/iser/app/database"
// "iser/app/penawaran"
"log"
)
func PenyediaLogin(email string, password string) string {
dbmap := db.InitDb(PenyediaModel{}, "penyedia")
defer dbmap.Db.Close()
mapWhere := map[string]inte... |
package main
import "fmt"
import "crypto/sha1"
import "io"
func main() {
fmt.Println("vim-go")
h := sha1.New()
io.WriteString(h, "hello")
fmt.Printf("% X\n", h.Sum(nil))
}
|
package ers
import (
"regexp"
"sort"
"strings"
"github.com/mix3/tlds-go"
)
type option struct {
exact bool
strict bool
gmail bool
utf8 bool
localhost bool
ipv4 bool
ipv6 bool
tlds []string
}
type Option func(*option)
func Exact(v bool) Option {
return func(u *option) {
... |
package rename
import (
"github.com/spf13/cobra"
"github.com/nordcloud/mfacli/config"
"github.com/nordcloud/mfacli/pkg/vault"
)
func Create(cfg *config.Config) *cobra.Command {
return &cobra.Command{
Use: "rename OLD_CLIENT_ID NEW_CLIENT_ID",
Short: "Rename the client",
Args: cobra.ExactArgs(2),
RunE:... |
package main
// Import Go and NATS packages
import (
"log"
"runtime"
//"strconv"
"github.com/nats-io/go-nats"
//"encoding/json"
)
type Sensors struct {
Name string
Timestamp string
Value string
}
type List struct {
Sensor1 *Sensors
Sensor2 *Sensors
Sensor3 *Sensors
}
func main() {
// Create server c... |
package xml
import (
"strings"
"testing"
)
const parserXml = "<root k='v'><child ck='cv' /><child>chars</child></root>"
var parserXmlTypes = []int{startType, startType, startType, charsType, endType, endType}
var parserXmlStrings = []string{"root", "k", "v", "child", "ck", "cv", "child", "child", "chars", "child",... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.