text
stringlengths
11
4.05M
package minify import ( "github.com/stretchr/testify/assert" "io/ioutil" "reunion/configuration" "testing" ) func TestMinifyContentCss(test *testing.T) { minified := Minify(".test { color: red; }", urlCss) assert.Equal(test, ".test{color:red}", minified) } func TestMinifyCssFromFile(test *testing.T) { config...
package timeout import ( "time" "github.com/gin-gonic/gin" ) var bufPool *BufferPool const ( defaultTimeout = 5 * time.Second ) // New wraps a handler and aborts the process of the handler if the timeout is reached func New(opts ...Option) gin.HandlerFunc { t := &Timeout{ timeout: defaultTimeout, handler:...
package kaleido import ( "fmt" resty "gopkg.in/resty.v1" ) const ( memBasePath = "/consortia/%s/memberships" ) type Membership struct { OrgName string `json:"org_name"` Id string `json:"_id,omitempty"` } func NewMembership(orgName string) Membership { return Membership{orgName, ""} } func (c *KaleidoCl...
package envvar import ( "os" "testing" ) func TestMustWithExistingValue(t *testing.T) { err := os.Setenv("TEST", "Hello World!") if err != nil { t.Fail() } if Must("TEST") != "Hello World!" { t.Fail() } } func TestMustPanicWithNonExistingValue(t *testing.T) { _ = os.Unsetenv("TEST") defer func() { if...
package goobj import ( "bytes" "reflect" "testing" ) func TestTable_calcMaxWidths(t *testing.T) { table := newTable([]string{"a", "ab", "abc"}) table.addRow([]string{"ab", "ab", "ab"}) expected := []int{2, 2, 3} actual := table.calcMaxWidths() if !reflect.DeepEqual(expected, actual) { t.Errorf("max widths ...
package search func search(nums []int, target int) int { maxIdx := len(nums) - 1 for l, h := 0, maxIdx; l <= h; { if l >= 0 && l <= maxIdx && nums[l] == target { return l } if h <= maxIdx && h >= 0 && nums[h] == target { return h } m := l + ((h - l) >> 1) mid := nums[m] if mid == target { ret...
package main import ( "log" "github.com/seanpfeifer/hostrelay/reliable" "github.com/seanpfeifer/hostrelay/unreliable" ) const ( defaultTCPHost = ":8080" defaultUDPHost = ":8585" ) func main() { log.Println("Starting server...") go func() { err := unreliable.ListenAndServeUDP("udp", defaultUDPHost) Fatal...
package main import "fmt" type Books struct { title string author string subject string bookId int } func main() { var a = Books{"111", "222", "444", 333} fmt.Println("这个是一种定义方式", a) var b = Books{ title: "string", author: "string", subject: "string", bookId: 123, } fmt.Println("这个是一种定义方式", ...
package pgtune import ( "github.com/timescale/timescaledb-tune/internal/parse" ) // Keys in the conf file that are tuned related to the WAL const ( WALBuffersKey = "wal_buffers" MinWALKey = "min_wal_size" MaxWALKey = "max_wal_size" CheckpointTimeoutKey = "checkpoint_timeout" WALComp...
package main import ( "fmt" "io/ioutil" "os" ) func main() { file1 := "F:/go/src/golangStudy/file_opt/you.txt" file2 := "F:/go/src/golangStudy/file_opt/my.txt" data, err := ioutil.ReadFile(file1) if err != nil { fmt.Println(err) } err = ioutil.WriteFile(file2, data, 0666) if err != nil { fmt.Println(er...
package operatorstatus import ( "fmt" "os" "strconv" "github.com/operator-framework/api/pkg/operators/v1alpha1" "github.com/operator-framework/operator-lifecycle-manager/pkg/lib/csv" "github.com/operator-framework/operator-lifecycle-manager/pkg/lib/ownerutil" "github.com/sirupsen/logrus" "k8s.io/apimachinery/...
// +build amd64 arm64 ppc64 ppc64le package poll type uintp = uint64
// Template Declare Start // // ${struct_field_name} // @Description:${todo} // // Template Declare End // Methods Declare // // GetComponentRequest // @Description: // // start_struct_field_code GetComponentRequest int64 // end_struct_field_code // // GetComponentRequest // @Description: // // start_struct...
package testdata import ( "github.com/frk/gosql" ) type SelectExistsWithFilterQuery struct { Exists bool `rel:"test_user:u"` gosql.Filter }
package analysis import ( "fmt" "strconv" "strings" "text/template" "github.com/frk/tagutil" ) // analysis error type anError struct { Code errorCode PkgPath string TargetName string BlockName string RelField string RelType RelType FieldType string FieldTypeKind stri...
package nats_streaming import ( "context" "io/ioutil" "github.com/batchcorp/plumber-schemas/build/go/protos/records" pb2 "github.com/nats-io/stan.go/pb" "github.com/nats-io/stan.go" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/sirupsen/logrus" "github.com/batchcorp/plumber-schemas/bu...
package util import ( "log" ) var DefaultTimeMask = "2006-01-02T15:04:05-0700" func Check(err error) { if err != nil { log.Panic(err) } } func CheckIf(condition bool, ifTrue interface{}, ifFalse interface{}) interface{} { if condition { switch ifTrue.(type) { case func() interface{}: return ifTrue.(fun...
package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "github.com/graphql-go/graphql" ) type user struct { ID string `json:"id"` Name string `json:"name"` } var data map[string]user /* Create User object type with fields "id" and "name" by using GraphQLObjectTypeConfig: - Name: name...
// Licensed to Elasticsearch B.V. under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Elasticsearch B.V. licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use ...
package gosign import ( "crypto/sha256" "encoding/base64" "io/ioutil" "net/http" "net/http/httptest" "strings" "testing" ) func TestThatTheHandlerExecutesTheHandlerThatItWraps(t *testing.T) { // Arrange. testBody, err := ioutil.ReadFile("testdata/data.json") if err != nil { t.Fatal("Failed to read test d...
package services import ( "context" "github.com/golang/protobuf/ptypes/empty" "github.com/satori/go.uuid" "github.com/tppgit/we_service/core" "github.com/tppgit/we_service/entity/cloudmessage" "github.com/tppgit/we_service/entity/transformer" "github.com/tppgit/we_service/entity/user" "github.com/tppgit/we_ser...
package store import ( "database/sql" "io/ioutil" _ "github.com/lib/pq" "github.com/rs/zerolog/log" ) type Store struct { ConnStr string db *sql.DB } func (s *Store) Connect() { db, err := sql.Open("postgres", s.ConnStr) if err != nil { log.Error().Err(err).Msg("could not connect to postgres") } s...
package handlers import ( "testing" "net/http" "github.com/gin-gonic/gin" "strings" "github.com/urbn/ordernumbergenerator/app/fixtures" "github.com/urbn/ordernumbergenerator/app" "github.com/urbn/ordernumbergenerator/app/config" ) func Test_GetHealth(t *testing.T) { app.Configuration,_ = config.LoadConfig() ...
package login import ( "GP/db" "GP/model" "database/sql" "log" ) func LoginAccCheck(username string) (ok bool, err error) { var haveusername string querySql := "select username from gp.user where username = ?" err = db.DB.QueryRow(querySql, username).Scan(&haveusername) if err != nil { if err == sql.ErrNoRo...
package mysqldb import ( "context" "time" ) // JinmuLAccessToken 是一体机账户登录会话信息数据 type JinmuLAccessToken struct { Account string `gorm:"account"` // 账户 Token string `gorm:"primary_key"` // token 是登录凭证 MachineUUID string `gorm:"column:machine_uuid"` // machine_uuid ExpiredAt ...
package examples import "embed" //go:embed *.clvm var F embed.FS
package ngomc import ( "reflect" "unsafe" ) const ( kindMask = (1 << 5) - 1 kindOffset = 184 / 8 elemOffset = 384 / 8 filedOffset = elemOffset + 1 ) //go:linkname memmove reflect.memmove func memmove(to, from unsafe.Pointer, n uintptr) func Encode(i interface{}) []byte { results := make([][2]uintptr, 0,...
package alertmanager import ( "encoding/json" "net/http" "strconv" "strings" "github.com/go-kit/kit/log" "github.com/go-kit/kit/log/level" "github.com/prometheus/alertmanager/notify/webhook" "github.com/prometheus/client_golang/prometheus" ) type TelegramWebhook struct { ChatID int64 Message webhook.Messa...
package main import ( "encoding/json" "errors" "io/ioutil" ) // Config stores settings of application type Config struct { Port string `json:"port"` // Port on which runs this app } // InitConfig creates new Config struct filled with values from config file func (app *App) InitConfig(configFilePath string) error...
package main import ( "fmt" "./concatenate" ) func main() { a, b := concatenate.Swap("hello", "world") fmt.Println(a, b) c, d := concatenate.Concatenate("good", "girl") fmt.Println(c, d) fmt.Println(concatenate.Calladd(6, 7)) }
package main import ( "html/template" "net/http" ) const ( AlertLvlError = "danger" ) type Alert struct { Level string Message string } type Data struct { Alert *Alert Yield interface{} } var indexView *template.Template func index(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type",...
package storage type ( Storage interface { PutSnapshot(id string, typ string, data []byte) error PutCache(id string, data []byte) error PutBlob(id string, data []byte) error GetSnapshots(typ string) ([][]byte, error) GetCacheContent(id string) ([]byte, error) GetBlobPath(id string) (string, error) Del...
package main import ( "github.com/pathbird/pbauthor/cmd" ) func main() { cmd.Execute() }
package model func TestUser() *User { return &User{ Email: "user@example.com", Password: "P@ssw0rd", } }
package main import ( "ego/src/commons" "ego/src/item" "ego/src/item/cat" "ego/src/item/param" "ego/src/user" "fmt" "github.com/gorilla/mux" "html/template" "net/http" ) // main.go func welcome(w http.ResponseWriter, r *http.Request) { // 解析指定文件生成模板对象 tmpl, err := template.ParseFiles("view/login.html") i...
package CapCV // Type https://docs.opencv.org/4.5.2/d1/d1b/group__core__hal__interface.html#ga32b18d904ee2b1731a9416a8eef67d06 type Type uint8 const ( CV_8U Type = iota CV_8S CV_16U CV_16S CV_32S CV_32F CV_64F CV_16F ) const ( CV_8UC1 Type = iota * 8 CV_8UC2 CV_8UC3 CV_8UC4 ) const ( CV_8SC1 Type = (io...
/* Copyright 2021 CodeNotary, Inc. 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 applicable law or agreed to i...
package version import ( "fmt" "strconv" "strings" ) const dot = `.` type SemVer struct { Major int Minor int Patch int } //Parse func Parse(s string) (v *SemVer) { v = new(SemVer) s = escape(s) vs := strings.Split(s, dot) if len(vs) > 0 { v.Major, _ = strconv.Atoi(vs[0]) } if len(vs) > 1 { v.Minor...
package main import "fmt" func main() { i, j := 42, 2701 p := &i // i 的内存地址指向 p fmt.Println(*p) *p = 21 // 通过指针 p 设置 i 的值 fmt.Println(i) p = &j // j 的内存地址指向 p *p = *p / 37 // 通过指针 p 读取 j 的值, 然后重新设置 j 值 fmt.Println(j) } /* 指针 GO 具有指针。指针保存 变量的内存地址 ...
// 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 database import ( "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" _ "github.com/jinzhu/gorm/dialects/postgres" _ "github.com/jinzhu/gorm/dialects/sqlite" "github.com/mukesh0513/RxSecure/internal/config" "github.com/mukesh0513/RxSecure/internal/database/sqlData/gormSupported" ) ...
package object import ( "time" ) type Article struct { ID int `gorm:"primary_key" form:"articleid"` CreatedAt time.Time UpdatedAt time.Time DeletedAt *time.Time `sql:"index"` AuthorId int `form:"userid"` QuestionId int `form:"questionid"` ArticleTitle strin...
package db import ( "os" "github.com/cyberbono3/monit_bot/shared/db/schema" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) var ( host = os.Getenv("HOST") database = os.Getenv("DB") username = os.Getenv("USER") password = os.Getenv("PASS") userCollection = os....
package idea import "testing" func TestIdea(t *testing.T) { t.Run("Test Encrypt", func(t *testing.T) { var plainText = []byte("abcdefgh") var key = []byte("abcdefghijklmnop") var expected = []byte("num sei") cypheredText := EncryptBlock(plainText, key) if string(expected) != string(cypheredText) { t....
package core type ( RegisterWorkerRequest struct { Port int `json:"port"` } RegisterWorkerResponse struct { Status string WorkerId uint } )
package main import ( "log" "os" "text/template" ) var tpl *template.Template type sage struct { Name string Motto string } type car struct { Manufacturer string Model string Doors int } type items struct { Wisdom []sage Transport []car } func init() { tpl = template.Must(template.Par...
package gatekeeper import ( "fmt" "os" ) func NewUUID() (string, error) { f, err := os.Open("/dev/urandom") defer f.Close() if err != nil { return "", err } b := make([]byte, 16) f.Read(b) return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:]), nil } func GetUUID() string { var u...
package effects import "github.com/faiface/beep" // Pan balances the wrapped Streamer between the left and the right channel. The Pan field value of // -1 means that both original channels go through the left channel. The value of +1 means the same // for the right channel. The value of 0 changes nothing. type Pan st...
package quota import ( "errors" "fmt" "math" "strings" ) // Quota stores the used and limit for a resouce's quota. type Quota struct { Service string Name string Region string InUse int64 Limit int64 Unlimited bool } // Constraint defines a check against availablity // for a resource quota. type Cons...
package models_test import ( "path" "time" "github.com/cloudfoundry-incubator/notifications/config" "github.com/cloudfoundry-incubator/notifications/models" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("ClientsRepo", func() { var repo models.ClientsRepo va...
/* * Copyright (C) 2017-Present Pivotal Software, Inc. All rights reserved. * * This program and the accompanying materials are made available under * the terms of the 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 ...
/* * @lc app=leetcode.cn id=349 lang=golang * * [349] 两个数组的交集 */ package solution import "sort" // @lc code=start func intersection(nums1 []int, nums2 []int) (ans []int) { sort.Ints(nums1) sort.Ints(nums2) i, j := 0, 0 for i < len(nums1) && j < len(nums2) { if i > 0 && nums1[i] == nums1[i-1] { i++ co...
package centos import ( "bytes" "fmt" "os/exec" "strings" "github.com/caos/orbos/internal/operator/common" "github.com/caos/orbos/internal/operator/nodeagent" "github.com/caos/orbos/mntr" ) func Ensurer(monitor mntr.Monitor, open []string) nodeagent.FirewallEnsurer { return nodeagent.FirewallEnsurerFunc(func...
package gortex import ( "fmt" "math" "math/rand" "github.com/vseledkin/gortex/assembler" ) type Matrix struct { Rows int //number of rows Columns int // number of columns W []float32 DW []float32 `json:"-"` } func (m *Matrix) SameAs() (mm *Matrix) { mm = Mat(m.Rows, m.Columns) return } func...
package main import ( "fmt" "os" "github.com/giantswarm/conair/btrfs" "github.com/giantswarm/conair/networkd" "github.com/giantswarm/conair/nspawn" ) var cmdBootstrap = &Command{ Name: "bootstrap", Description: "Bootstrap conair base image", Summary: "Creates an arch rootfs with pacstrap. If there...
package main import ( . "github.com/alimoeeny/gomega" "testing" ) func Test_Synapse_stepforwrd(t *testing.T) { RegisterTestingT(t) n1 := NewNeuron(Role_input) n2 := NewNeuron(Role_regular) s := NewSynapse(n1, n2, 0.5, baseKernel()) Ω(s.Time).Should(Equal(int64(0))) Ω(s.KernelIndex).Should(Equal(0)) s.StepF...
// 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...
package cmd import ( "github.com/spf13/cobra" "github.com/bpineau/cloud-floating-ip/pkg/operation" "github.com/bpineau/cloud-floating-ip/pkg/run" ) var destroyCmd = &cobra.Command{ Use: "destroy", Short: "Delete the routes managed by cloud-floating-ip", Long: `Delete the routes managed by cloud-floating-ip`...
package lib import "fmt" // Y is the 3rd key component of pub key func Y(g, x, p Integer) Integer { if x <= 1 || x >= (p-1) { fmt.Println("Cannot continue, x : ", x, " has to be > 1 and < p-1 : ", p-1) return 0 } gIsRoot := false roots, n := getRoots(p) if n == 0 { fmt.Println("Warning no roots found for...
package register import ( "fmt" "os" ) // StringRegister ... type StringRegister struct { Value string } // Type ... func (i *StringRegister) Type() DataType { return StringType } // GetString ... func (r *Register) GetString() string { switch arg := r.o.(type) { case *StringRegister: return arg.Value defau...
package reverseinteger import ( "fmt" "math" "strconv" ) // Reverse func func Reverse(numero int) int { strNumero := strconv.Itoa(numero) var sliceDigitos []int var resultado int var reverseStr string var negativo bool if numero < 0 { numero = numero * -1 strNumero = strconv.Itoa(numero) negativo = tru...
package main import ( "fmt" "os" "github.com/ovh/venom" "github.com/ovh/venom/cmd/venom/root" ) func main() { if err := root.New().Execute(); err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) venom.OSExit(2) } }
package frida_go type ProcessQueryOptions struct { SelectPids []uint Scope FridaScope }
package schedule import "database/sql" const ( Monday = "Monday" Tuesday = "Tuesday" Wednesday = "Wednesday" Thursday = "Thursday" Friday = "Friday" Saturday = "Saturday" Sunday = "Sunday" ) var ( mondayActivities []Activity tuesdayActivities []Activity wednesdayActivities []Activity thu...
package slack import ( "fmt" "net/http" "net/url" "path" "strings" "github.com/songx23/letschat/pkg/httpclient" ) type Client struct { httpClient *http.Client baseURL url.URL oauthToken string } func NewClient(httpClient *http.Client, baseURL url.URL, token string) *Client { return &Client{ httpClien...
package main import ( "flag" "fmt" "github.com/go-errors/errors" "github.com/karrick/godirwalk" "os" "path/filepath" "strings" "time" "github.com/k0kubun/go-ansi" terminal "github.com/wayneashleyberry/terminal-dimensions" ) func contains(s []string, e string) bool { for _, a := range s { if a == e { r...
package main import ( "bufio" "bytes" "fmt" "io" "io/ioutil" "log" "net/http" "os" "regexp" ) // Reference defines a location and expression to get a snippet from. type Reference struct { Name string Url string Parts PartMap } type ReferenceMap map[string]*Reference // Part defines the use of a Refere...
package aliyun import ( "github.com/aliyun/aliyun-oss-go-sdk/oss" ) // GetCodeURI returns codeURI of a given function func (m *Manager) GetCodeURI(funcName string) (string, error) { codeOut, err := m.userCodeBucket.SignURL(funcName, oss.HTTPGet, 99999999) if err != nil { return "", err } return codeOut, nil } ...
// Copyright 2018 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
package core_test import ( "fmt" "github.com/xo/common" "github.com/xo/core" "sync" "testing" "time" ) func funcTest() { fmt.Println("func test succ") } func TestSingleQueueSingleTaskCache(t *testing.T) { taskQueue := core.NewTaskQueue(1, 1) for i := 0; i < 1; i++ { taskQueue <- core.New...
/* Introduction Say you have a population of people. This population is made up of 100 Alices and 25 Bobs. So, 80% of the population are Alices and 20% are Bobs. We want to change the proportional makeup of the population to be 62% Alices and 38% Bobs. Rules You can only add to the population. You cannot take any awa...
package messageTypes import "../elevio" const ( HallOrderManager = 0 Network = 1 ) type RequestCost struct { Order OrderStamped RequestFrom int } type FSMChannels struct { DelegateHallOrder chan elevio.ButtonEvent RequestCost chan RequestCost ReplyToNetWork chan Orde...
package mat import ( "math" ) type Tuple4 [4]float64 func (t Tuple4) ResetVector() Tuple4 { t[0] = 0.0 t[1] = 0.0 t[2] = 0.0 t[3] = 1.0 return t } func (t Tuple4) ResetPoint() Tuple4 { t[0] = 0.0 t[1] = 0.0 t[2] = 0.0 t[3] = 0.0 return t } func T4F32(x, y, z float32, w float64) Tuple4 { return Tuple4{flo...
/* Copyright 2018 IBM Corp. 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 distr...
package proxy import ( "bytes" "net/http" "net/url" ) // ProcessRequest modifies the request in accordnance // with Proxy settings func (p *Proxy) ProcessRequest(r *http.Request) error { proxyURLRaw := p.BaseURL + r.URL.String() proxyURL, err := url.Parse(proxyURLRaw) if err != nil { return err } r.URL = p...
package objectstorage import ( "context" "github.com/minio/minio-go/v7" "time" ) type minioBucketManager struct { client *minio.Client } func NewMinioBucketManager(client *minio.Client) *minioBucketManager { return &minioBucketManager{ client: client, } } func (m *minioBucketManager) ResolveBucket(ctx conte...
package cmd import ( "github.com/spf13/cobra" "go.skia.org/infra/go/sklog" ) var cfgFile string // rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ Use: "bot_config", Short: "Determines the configuration of a bot.", Long: `Each sub-command implements a get...
package testcase type Options[T string] struct { requiredKey T `option:"mandatory" validate:"required"` key T `option:"mandatory"` optKey T }
package storage import ( "bytes" "encoding/json" ) // MachineType describes a set of machines/hosts sharing same hardware specs type MachineType struct { ID int64 `json:"id"` DisplayName string `json:"name"` Features []string `json:"features,omitempty"` Login string `json:"login"` Pass...
package main import ( "fmt" "gee/gee" "html/template" "net/http" "time" ) func formatAsDate(t time.Time) string { year, month, day := t.Date() return fmt.Sprintf("%d-%02d-%02d", year, month, day) } func main() { r := gee.Default() r.Use(gee.Logger()) // global middleware r.SetFuncMap(template.FuncMap{ "f...
package errors import ( "github.com/appootb/substratum/errors" ) func Init() { if errors.Implementor() == nil { errors.RegisterImplementor(&Debug{}) } } type Debug struct{} func (m Debug) Translate(_ int32) string { return "" }
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/6/11 10:04 上午 # @File : lt_求二叉树最大路径_test.go.go # @Description : # @Attention : */ package v2 import ( "fmt" "testing" ) func Test_aaa(t *testing.T) { sum := maxPathSum(&TreeNode{ Val: -3, }) fmt.Println(sum) } func Test_bb(t *testing.T) { fmt.Printl...
package main /* A simple TCP echo server on the current host with the given port Replies with the same data with host information License: Apache License-2.0 */ import ( "fmt" "flag" "net" "os" ) /* Handling and printing error */ func handleError(err error) { // handle error if err != nil { fmt.Pri...
package storage import ( "testing" "github.com/stretchr/testify/assert" ) func TestNewStore(t *testing.T) { var store Store st, err := TypeString("unknownStorage") assert.Error(t, err) store = NewStore(st) for _, storeType := range []string{"S3", "Spaces", "Diskv", "Redis"} { st, err := TypeString(storeType...
package infrastructure import ( "context" "errors" "math/rand" "reflect" "testing" "time" "github.com/google/uuid" "github.com/jybbang/go-core-architecture/core" "github.com/jybbang/go-core-architecture/infrastructure/mongo" "go.mongodb.org/mongo-driver/bson" ) func Test_mongoQueryRepositoryService_Connect...
// Package action declares Action interface. package action import ( "github.com/artemrys/go-all-repos/internal/config" "github.com/artemrys/go-all-repos/internal/repo" "github.com/google/go-github/github" ) // Action declares interface for all actions. type Action interface { Do() } // NewActionFunc declares a ...
// Copyright Fuzamei Corp. 2018 All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "bytes" "encoding/hex" "encoding/json" "errors" "fmt" "io/ioutil" "math/rand" "net/http" "os" "strconv" "time" "github.com/33c...
package types import ( "testing" "github.com/irisnet/irishub/app/v1/auth" "github.com/irisnet/irishub/app/v1/bank" "github.com/irisnet/irishub/codec" sdk "github.com/irisnet/irishub/types" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermin...
package service import ( "demo1_gogin_api/db" "demo1_gogin_api/log" . "demo1_gogin_api/models" "github.com/gin-gonic/gin" "net/http" "time" ) func GetTags(c *gin.Context) { var tags []TbTag if err := db.SqlDB.Find(&tags).Error; err != nil { c.AbortWithStatus(404) log.UserLog.Error("Query tags from db erro...
package main func affineEncrypt(string msg) string { cipher := "" var i int for i := 0; i < len(msg); i++ { if msg[i] != '' { cipher := cipher + char((((a*(msg[i]-'A'))+b)%26) + 'A') } else { cipher := cipher + msg[i] } } return cipher } func affineDecrpyt(string cipher) string { ...
package day10 import ( "math" "strings" "github.com/kdeberk/advent-of-code/2019/internal/utils" ) type asteroid struct { x float64 y float64 } func (self asteroid) distance(other asteroid) float64 { return math.Abs(self.x-other.x) + math.Abs(self.y-other.y) } type slope struct { quadrant byte angle floa...
package wal import ( "encoding/binary" "hash/crc32" "time" "github.com/anchorfree/kafka-ambassador/pkg/wal/pb" "github.com/gogo/protobuf/proto" "github.com/golang/protobuf/ptypes" ) var crcTable = crc32.MakeTable(crc32.Castagnoli) func CrcSum(data []byte) uint32 { crc := crc32.New(crcTable) _, _ = crc.Write...
package ast_parser import ( "strings" . "github.com/dave/jennifer/jen" ) type Param struct { Type string Name string } type ReturnValue struct { Type string } type Method struct { Name string Params []Param Receiver string ReturnValues []ReturnValue } func (m *Method) getStructName() st...
// Copyright 2017 "as". All rights reserved. Torgo is governed // the same BSD license as the go programming language. package main import ( "bufio" "fmt" "os" "github.com/as/bo" ) func Gintl(b []byte) int64 { return int64(bo.Gintl(b)) } // conformsAny checks if n represents the size of the Item func conforms...
package main import ( "fmt" "sync" "sync/atomic" "unsafe" ) type IntMap interface { Get(k int) (v int, found bool) Set(k int, v int) } // Single lock around the map type Locked struct { e map[int]int m sync.RWMutex } func NewLocked() *Locked { return &Locked{make(map[int]int), sync.RWMutex{}} } func (c *L...
package graph import ( "context" "fmt" "math/rand" "github.com/AlejandroAldana99/graphql/controller" "github.com/AlejandroAldana99/graphql/graph/generated" "github.com/AlejandroAldana99/graphql/graph/model" ) func (r *mutationResolver) CreateBook(ctx context.Context, input model.NewBook) (*model.Book, error) {...
package detector import ( "github.com/samuel/go-zookeeper/zk" ) // ZkConnector Interface to facade zk.Conn type // since github.com/samuel/go-zookeeper/zk does not provide an interface // for the zk.Conn object, this allows for mocking and easier testing. type zkConnector interface { Close() Children(string) ([]st...
package main import "fmt" func main() { fmt.Println("switch statement") switch { case (2 == 2): fmt.Println("\tThis should print: 001") case false: fmt.Println("\tThis should not print: 001") } fmt.Println("switch with fallthrough") // if the true case has "fallthrough", the case immediately after that t...
package day15 import "fmt" type Node struct { data int next *Node } func (n Node) NewNode(data int) *Node { return &Node{data: data, next: nil} } func (n *Node) Insert(data int) { for n.next != nil { n = n.next } n.next = n.NewNode(data) } func (n *Node) Display() (out string) { for n.next != nil { out ...
package main import "time" func doJob(quit chan int) { // тодорхой ажил гүйцэтгэхийг оруулав time.Sleep(time.Millisecond * 200) quit <- 1 } func main() { routineQuit := make(chan int) for i:=0; i<50; i++ { go doJob(routineQuit) } // бүх функцээс дууссан дохио хүлээх for i...