text
stringlengths
11
4.05M
package main import "fmt" func main() { ch:=make(chan int) quit:=make(chan bool) go fibn(ch,quit,20) for{ select { case num:=<-ch: fmt.Print(num," ") case <-quit: return } } } func fibn(ch chan<- int,quit chan <- bool,n int){ x,y:=1,1 for i:=1;i<20;i++{ ch<-x x,y=y,x+y } quit<-true }
package main import "github.com/ugoturner/podgo/cmd" func main() { cmd.Build() }
package models import ( "fmt" "time" "github.com/jinzhu/gorm" ) // ===== BEGIN of all query sets // ===== BEGIN of query set TrelloQuerySet // TrelloQuerySet is an queryset type for Trello type TrelloQuerySet struct { db *gorm.DB } // NewTrelloQuerySet constructs new TrelloQuerySet func NewTrelloQuerySet(db *...
package main import ( // Standard library packages "log" "net/http" "os" // Third party packages "github.com/julienschmidt/httprouter" "gopkg.in/mgo.v2" ) func main() { f, _ := os.OpenFile("/tmp/heart.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) defer f.Close() log.SetOutput(f) log.Printf("Start") //...
package server import ( "bufio" "config" "io" "log" "net" "sync" "time" ) type ConcurrentMap struct { lock sync.RWMutex data map[interface{}]interface{} } func (m *ConcurrentMap) Put(key, value interface{}) { m.lock.Lock() defer m.lock.Unlock() if m.data == nil { m.data = make(map[interface{}]interface...
// ˅ package main import ( "fmt" "time" ) // ˄ // Display values with a bar chart. type BarChartObserver struct { // ˅ // ˄ // ˅ // ˄ } func NewBarChartObserver() *BarChartObserver { // ˅ return &BarChartObserver{} // ˄ } func (self *BarChartObserver) Update(number *Number) { // ˅ fmt.Print("Bar char...
package serializetree import "testing" func TestNoData(t *testing.T) { tree := NewTree() actual := tree.Marshal() expected := "{\"head\": null}" if actual != expected { t.Errorf("Bad marchalling, expected %s, actual was %s", expected, actual) } } func TestBasicSerialization(t *testing.T) { tree := NewTree() ...
package cassandra import ( "log" "github.com/gocql/gocql" "user-event-store/app/management" ) var Session *gocql.Session func init() { var err error configuration := management.Configuration.Config("cassandra") host := configuration.String("host") keyspace := configuration.String("keyspace") cluster := goc...
package rest import ( "errors" "fmt" "github.com/jinmukeji/jiujiantang-services/pkg/rest" jinmuidpb "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/user/v1" generalpb "github.com/jinmukeji/proto/v3/gen/micro/idl/ptypes/v2" "github.com/kataras/iris/v12" ) const ( // SimpleChinese 简体中文 SimpleChinese ...
/* * Copyright (c) 2021. Alibaba Cloud. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 */ package exporter import ( "time" "github.com/dragonflyoss/image-service/contrib/nydus-snapshotter/pkg/metric/ttl" "github.com/dragonflyoss/image-service/contrib/nydus-snapshotter/pkg/nydussdk/model" "githu...
package pkg import ( "encoding/json" "github.com/fabric-lab/hyperledger-fabric-manager/server/pkg/entity" "github.com/fabric-lab/hyperledger-fabric-manager/server/pkg/store" "github.com/fabric-lab/hyperledger-fabric-manager/server/pkg/util" "github.com/gin-gonic/gin" "strings" ) func GetEntitys(c *gin.Context) ...
package nougat import "net/url" // Base sets the rawURL. // If you intend to extend the url with Path, baseUrl should be specified // with a trailing slash. func (r *Nougat) Base(rawURL string) *Nougat { r.rawURL = rawURL return r } // Path extends the rawURL with the given path by resolving the reference // to an...
package beater import ( "fmt" "os/exec" "strconv" "strings" "time" "github.com/elastic/beats/libbeat/beat" "github.com/elastic/beats/libbeat/common" "github.com/elastic/beats/libbeat/logp" "github.com/elastic/beats/libbeat/publisher" "github.com/kussj/cassandrabeat/config" ) type Cassandrabeat struct { d...
/* * Package targets * Target GEN/SMD (Sega Genesis / Megadrive) * * Part of XPMC. * Contains data/functions specific to the GEN output target * * /Mic, 2012-2015 */ package targets import ( "os" "time" "../specs" "../utils" "../effects" "../timing" ) /* Sega G...
// Copyright 2017 Google 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 in...
/* Copyright 2022 The KubeVela Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, softw...
package main import ( "fmt" "math/bits" ) func main() { a := 2 b := 7 total := 0 for i := a; i <= b; i++ { total += bits.OnesCount16(i) } fmt.Println(total) }
package main import ( "fmt" "strconv" "strings" ) func main() { time := "12:23PM" end := strings.Index(time, ":") typ := time[end+3 : len(time)] fmt.Println(typ) change := string(time[0:end]) fmt.Println(change) num, _ := strconv.Atoi(change) changeType := false if num == 1 { num = 12 } else if num...
package main import "runtime" var ninserts int64 var nupserts int64 var ndeletes int64 var xdeletes int64 var numentries int64 var totalwrites int64 var totalreads int64 var delmod = int64(0) var updmod = int64(1) var conflicts = int64(0) var rollbacks = int64(0) var numcpus = runtime.GOMAXPROCS(-1)
package mobile import ( "github.com/golang/protobuf/proto" "github.com/textileio/go-textile/core" "github.com/textileio/go-textile/pb" ) // Feed calls core Feed func (m *Mobile) Feed(req []byte) ([]byte, error) { if !m.node.Started() { return nil, core.ErrStopped } mreq := new(pb.FeedRequest) if err := prot...
package main import ( "fmt" ) func main() { fmt.Println(wordBreak("carcars", []string{ "car", "ca", "rs", })) fmt.Println(wordBreak("cars", []string{ "car", "ca", "rs", })) } func wordBreak(s string, wordDict []string) bool { mm := make(map[string]bool) // 为了快速判断字符床是否存在 for _, w := range wordDict { mm[...
package core import ( "crypto/sha256" "encoding/hex" "strconv" "time" ) type Block struct { Index int64 Timestamp int64 PrevBlockHash string Data string Hash string } //区块hash生成 func calculateHash(b Block) string { blockData := strconv.Itoa(int(b.Index)) + strconv.Itoa(int(b.T...
package main import ( "fmt" "runtime" "sync" "testing" "time" ) func TestGetGomaxprocs(t *testing.T) { group := sync.WaitGroup{} for i := 0; i < 100; i++ { group.Add(1) go func() { time.Sleep(3 * time.Second) group.Done() }() } totalCpu := runtime.NumCPU() fmt.Println("Total CPU ", totalCpu) ...
package main func main() { /* fmt.Println("1 + 1 =", 1+1) var name string = "golang" // değişken adı küçük harfle başlarsa dışarıdan erişilemez olur fmt.Println(name) var Version string = "1.2" // değişken adı büyük harfle başlarsa public olur fmt.Println(Version) */ /* var message ...
/***************************************************************** * Copyright©,2020-2022, email: 279197148@qq.com * Version: 1.0.0 * @Author: yangtxiang * @Date: 2020-07-30 16:58 * Description: *****************************************************************/ package xthrift import ( "github.com/apache/thrift/lib/...
package news_api import ( "config" "encoding/json" "models" "net/http" ) func FindAll(response http.ResponseWriter, request *http.Request) { db, err := config.GetDB() if err != nil { respondWithError(response, http.StatusBadRequest, err.Error()) } else { newsModel := models.NewsModel{ Db: db, } news...
package hash import ( "crypto/sha256" "encoding/hex" "fmt" "hash/crc32" "io" "os" "path/filepath" "runtime" "strconv" "strings" "github.com/docker/docker/pkg/fileutils" "github.com/docker/docker/pkg/longpath" "github.com/pkg/errors" ) // Password hashes the password with sha256 and returns the string fu...
/* Copyright 2020 The SuperEdge 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, s...
// Copyright 2021 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 main import ( "fmt" "github.com/kwo/bigmux" "gopkg.in/yaml.v2" "io/ioutil" "log" "os" "path" ) func main() { if len(os.Args) != 2 { fmt.Printf("Usage: %s <config-file>\n", path.Base(os.Args[0])) os.Exit(1) } configFilename := os.Args[1] data, errFile := ioutil.ReadFile(configFilename) if err...
/* Package kinematics calculates forward and inverse kinematics for robotic arm systems. Forward kinematics takes joint angles and returns an XyzWxyz coordinate of the end effector. Inverse kinematics takes an XyzWxyz coordinate and returns joint angles that move the end effector to that coordinate. ForwardKinematics...
package main import ( "fmt" "math/rand" ) //switch语句中fallthrough穿透,没有break语句跳出,默认都是跳出 func main() { a := 6 //有判断条件 switch a { case 0: fmt.Println("值为0") fallthrough case 1: fmt.Println("值为1") fallthrough case 2: fmt.Println("值为2") case 3, 4, 5, 6, 7, 8: fmt.Println("值在3, 4, 5, 6, 7, 8之间") defa...
package main import ( "context" "errors" "fmt" "io" "log" "os" "github.com/akito0107/xsqlparser" "github.com/akito0107/xsqlparser/dialect" "github.com/urfave/cli" "github.com/xo/dburl" "github.com/akito0107/xmigrate" ) func main() { app := cli.NewApp() app.Name = "pginverse" app.Usage = "postgres db m...
package main import ( "bufio" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "os" "regexp" "strings" ) type iPInfo struct { Data []string } func main() { if len(os.Args) != 2 { fmt.Println("Need a file name") return } inputFile, inputError := os.Open(os.Args[1]) //变量指向os.Open打开的文件时生成的文件句柄 if inp...
package main import ( "bytes" "fmt" "io" "io/ioutil" "log" "net/http" "os" "os/exec" "strings" "sync" ) func handler(w http.ResponseWriter, r *http.Request) { log.Print("Home page request.") body, err := ioutil.ReadFile("static/index.html") if err != nil { http.Error(w, err.Error(), http.StatusInternal...
package main import ( bootstrap "code-cadets-2021/lecture_2/05_offerfeed/cmd/bootstrap" "code-cadets-2021/lecture_2/05_offerfeed/internal/tasks" ) func main() { signalHandler := bootstrap.NewSignalHandler() feed := bootstrap.NewAxilisOfferFeed() queue := bootstrap.NewOrderedQueue() processingService := bootstr...
package Models import ( "fmt" _ "github.com/go-sql-driver/mysql" "resource-api/Config" ) //GetAllClients Fetch all client data func GetAllClients(client *[]Client) (err error) { if err = Config.DB.Find(client).Error; err != nil { return err } return nil } //CreateClient ... Insert New data func CreateClient(...
package types import ( "encoding/json" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestMessageInfoHandlesMultipleCoins(t *testing.T) { info := MessageInfo{ Sender: "foobar", Funds: []Coin{ {Denom: "peth", Amount: "12345"}, {Denom: "uatom", Amount: "78987...
package main import ( "context" "encoding/json" "fmt" "log" "os" "os/signal" "sync" "syscall" "github.com/bobrovka/calendar/internal" "github.com/bobrovka/calendar/internal/consumer" "github.com/bobrovka/calendar/internal/models" "github.com/heetch/confita" "github.com/heetch/confita/backend/file" flag ...
package main import ( f "fmt" ) const( PUTIH = iota HITAM BIRU MERAH KUNING ) type Warna byte type Kotak struct{ lebar, tinggi, panjang float64 warna Warna } type DaftarKotak []Kotak func (k Kotak) volume() float64{ return k.lebar * k.panjang * k.tinggi } func (k *Kotak) SetWarna(w Warna) { k.warna = w...
package main import ( "fmt" "net/http" "os" "strings" ) func main() { input := os.Args[1:] if len(input) == 0 { fmt.Fprintf(os.Stderr, "No args found\n") os.Exit(1) } url := input[0] if !strings.HasPrefix(url, "http://") { url = "http://" + url } resp, err := http.Get(url) if err != nil { fmt.Fpri...
package main import ( "fmt" ) func main() { fmt.Println("Selection sort: start") Array := []int { 4, 9, 1, 3, 1, 5, 7, 0, 11, 2, 5, 12, 10 }; fmt.Println(Array) for i := 1; i < len(Array); i++ { j := i for j > 0 && Array[j-1] > Array[j] { Array[j-1], Array[j] = Array[j], Array[j-1] j-- } } fmt...
package controller import ( "context" "errors" "cloud.google.com/go/firestore" "google.golang.org/api/iterator" ) type findRepo interface { } type DBRepoStruct struct { client *firestore.Client } //NewFindRepo return new memory for findrepostruct struct func NewDBRepo(client *firestore.Client) *DBRepoStruct {...
package main import ( "fmt" "sync" ) const ( DEPTH = 4 ENDINGDEPTH = DEPTH - 1 ) type Fetcher interface { // Fetch returns the body of URL and // a slice of URLs found on that page. Fetch(url string) (body string, urls []string, err error) } // Crawl uses fetcher to recursively crawl // pages starting ...
package main import ( "Mmx/Modules" "Mmx/Router" ) func main() { Modules.Config.Init() Modules.Global.Init() Router.InitRouter() }
package main import ( "log" "os" "strings" "github.com/bmaupin/go-epub" ) func genetatePdfFile(bookProjectDir, bookVersion, coverImagePath string, forPrint bool) string { var e *epub.Epub var outFilename string var indexArticleTitle string var bookWebsite string var engVersion bool target := "pdf" css :=...
package data import( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" "time" ) const DATABASE_NAME="danmu" /**如果数据不存在 则创建表*/ func createDB(database_name string){ db,err :=sql.Open(driver_name,database_url) if err!=nil { fmt.Printf(err.Error()) } result,err :=db.Exec("create database "+database_name) ...
package report import ( "encoding/json" "io" "net/http" "os" "strconv" "github.com/gorilla/mux" "github.com/reynaldipane/toko-ijah/appcontext" helper "github.com/reynaldipane/toko-ijah/helpers" orders "github.com/reynaldipane/toko-ijah/order" productstock "github.com/reynaldipane/toko-ijah/product_stock" ) ...
package msaevents import ( "fmt" "reflect" "strconv" "strings" ) type CustomFieldMapLabelValue struct { Label string Value string } type CustomField struct { Field CustomFieldConfig `json:"field"` Data *CustomFieldData `json:"data"` } func (c *CustomField) StringValue() string { if c.Data != nil { retu...
package e2e import ( "bytes" "context" "encoding/json" "errors" "fmt" "path/filepath" "strconv" "strings" "sync" "time" "github.com/blang/semver/v4" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gstruct" "github.com/stretchr/testify/assert" "github.com/stretchr/tes...
// 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 internal import ( "fmt" "os" flag "github.com/spf13/pflag" ) type options struct { BlobNameOrPrefix string ContainerName string AccountName string AccountKey string SetBlobMD5 bool FileSource string ShowVersion bool } //Options TODO var Options = &options{} const st...
package sleepytcp import "sync" type waitingCaller struct { ready chan struct{} mu sync.Mutex // protects conn, err, close(ready) conn *clientConn err error } // waiting reports whether w is still waiting for an answer (connection or error). func (w *waitingCaller) waiting() bool { select { case <-w.read...
package venti import ( "crypto/sha1" "errors" "fmt" "io" ) // TODO: when should scores be pointers vs values? const ScoreSize = sha1.Size type Score [ScoreSize]byte func ZeroScore() Score { return Score{ 0xda, 0x39, 0xa3, 0xee, 0x5e, 0x6b, 0x4b, 0x0d, 0x32, 0x55, 0xbf, 0xef, 0x95, 0x60, 0x18, 0x90, 0xaf, ...
package setr import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document05700102 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:setr.057.001.02 Document"` Message *OrderConfirmationStatusReportV02 `xml:"OrdrConfStsRpt"` } func (d *Docu...
package lark import ( "testing" ) func TestCrypto(t *testing.T) { text := "hello world" cd := NewCrypto("test key") plant, err := cd.DecryptString("P37w+VZImNgPEO1RBhJ6RtKl7n6zymIbEG1pReEzghk=") if err != nil { t.Fatal(err) } t.Logf("plan: %q", plant) if plant != text { t.Errorf("mismatch result: %q ==...
// +build ignore package main import ( "fmt" "os" "os/signal" "github.com/naveego/live-api" "github.com/Sirupsen/logrus" ) const ( SERVER_ADDR = "ws://127.0.0.1:8888" ) func main() { logrus.SetLevel(logrus.DebugLevel) cli, err := live.NewWebSocketClient(SERVER_ADDR, "23432", "TEST") if err != nil { p...
package main import ( "bufio" "fmt" "io" "os" "strconv" "strings" ) type xy_tuple struct { x int32 y int32 dir direction } type direction int const ( UPDOWN direction = 0 LEFTRIGHT direction = 1 INVALID direction = 2 ) // Complete the minimumMov...
package coding type Splitter func(rune) int var ( _7BitSplitter Splitter = func(rune) int { return 7 } _1ByteSplitter Splitter = func(rune) int { return 8 } _MultibyteSplitter Splitter = func(r rune) int { if r < 0x7F { return 8 } return 16 } _UTF16Splitter Splitter = func(r rune) int { if (r...
// Copyright 2019 The bigfile Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package http import "github.com/gin-gonic/gin" func init() { isTesting = true gin.SetMode(gin.ReleaseMode) }
package objs import ( "time" ) const ( StartupEvent = 1 // 시동 ShockEvent = 2 // 충격 SpeedingEvent = 3 // 과속 ProximityEvent = 4 // 근접 ) type IpasLog struct { Ipas Date time.Time `json:"date"` EventType int `json:"event_type"` SessionId string `json:"session_id"` Targets string `json...
package fake import ( "math/rand" "github.com/goropikari/psqlittle/core" ) // ColName generates fake ColName func ColName() core.ColumnName { return core.ColumnName{ TableName: RandString(), Name: RandString(), } } // Value generates fake Value func Value() core.Value { return RandString() } const le...
package cmd import ( "fmt" "os" "strings" "github.com/lingrino/vaku/vaku" "github.com/pkg/errors" "github.com/spf13/cobra" ) var folderMapCmd = &cobra.Command{ Use: "map [path]", Short: "Return a text map of the folder, with subfolders indented by depth", Long: `Takes in a path and returns a text map of p...
// Copyright 2021 Clivern. All rights reserved. // Use of this source code is governed by the MIT // license that can be found in the LICENSE file. package definition import ( "fmt" ) const ( // HttpbinService const HttpbinService = "httpbin" // HttpbinPort const HttpbinPort = "80" // HttpbinDockerImage cons...
package renter import ( "testing" "time" ) // TestEstimateTimeUntilComplete is a unit test that probes // 'estimateTimeUntilComplete' func TestEstimateTimeUntilComplete(t *testing.T) { t.Parallel() // took 100ms for the chunk to become available, using default Skynet EC // params timeUntilAvail := time.Duratio...
package util const ( MirrorActivityTypeInit = "init" MirrorActivityTypeReconfigure = "reconfigure" MirrorActivityTypeLocked = "locked" MirrorActivityTypeUnlocked = "unlocked" MirrorActivityTypeCronSync = "scheduled-sync" MirrorActivityTypeSync = "sync" ) const ( MirrorActivityStatusCom...
package gottle import ( "reflect" "testing" "time" "github.com/adelowo/onecache/filesystem" ) func TestIp(t *testing.T) { ipProvider := NewRealIP() throttler := NewOneCacheThrottler(IP(ipProvider)) if !reflect.DeepEqual(ipProvider, throttler.ipProvider) { t.Fatalf(` IP providers differ\n .. Expecte...
package http import ( "fmt" _twitter "github.com/dghubble/go-twitter/twitter" "github.com/dora1998/snail-bot/twitter" "github.com/gin-gonic/gin" "net/http" ) type PostIFTTTWebHookRequest struct { Text string `json:"text"` UserName string `json:"user_name"` LinkToTweet string `json:"link_to_tweet"` ...
package utils import "testing" import "reflect" type divideIntoBatchesTestData struct { slice []uint8 batchSize int expected [][]uint8 } func TestDivideIntoBatches(t *testing.T) { testData := [...]divideIntoBatchesTestData{ {[]uint8{1, 1, 2, 2, 3, 3, 4}, 2, [][]uint8{{1, 1}, {2, 2}, {3, 3}, {4}}}, {[]u...
package ch01 import ( "sort" "testing" ) func TestEx15(t *testing.T) { for _, c := range []struct { in []int x int want []int }{ {in: []int{0, 1, 2}, x: 3, want: []int{1,2}}, {in: []int{2, 1, 0}, x: 3, want: []int{1,2}}, {in: []int{2, 0, 1}, x: 3, want: []int{1,2}}, {in: []int{0, 1, 3, 3, 4, 5, 6...
package main // escreva um programa que crie um loop utilizando a sintax for{} // Utilizeo para demonstrar os anos que voce nasceu até hoje import "fmt" func main() { anoNascimento := 1980 anoFinal := 2020 for { if anoNascimento > anoFinal { break } fmt.Println(anoNascimento) anoNascimento++ } }
package p2exec import ( "strings" "testing" ) func TestBuildWithArgs(t *testing.T) { args := P2ExecArgs{ Command: []string{"script"}, } expected := "script" actual := strings.Join(args.CommandLine(), " ") if actual != expected { t.Errorf("Expected args.BuildWithArgs() to return '%s', was '%s'", expected, ...
package main import ( "context" "fmt" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/feature/s3/manager" "github.com/aws/aws-sdk-go-v2/service/ec2" "github.com/aws/aws-sdk-go-v2/service/s3" "log" "os" "strings" "time" ) var client *ec2.Client var s3cl...
package testutils import "testing" func ASSERT_STREQ(t *testing.T, actual string, expected string) { if expected != actual { t.Fail() t.Fatalf("expected=%s, got=%s", expected, actual) } } func ASSERT_EQ(t *testing.T, actual int, expected int) { if expected != actual { t.Fatalf("expected=%d, got=%d", expecte...
package main import ( "github.com/iotaledger/hive.go/node" "github.com/iotaledger/wasp/packages/parameters" _ "github.com/iotaledger/wasp/packages/vm/sandbox" "github.com/iotaledger/wasp/plugins/banner" "github.com/iotaledger/wasp/plugins/chains" "github.com/iotaledger/wasp/plugins/cli" "github.com/iotaledger/w...
package main import "fmt" func main() { x := "Shikamaru Nara" fmt.Println(x) { fmt.Println(x) y := "Laziness is the mother of all bad habits, but ultimately she is a mother and we should respect her" fmt.Println(y) } // fmt.Println(y) // outside the scope of y } // Shikamaru Nara // Shikamaru Nara // La...
package main import ( "fmt" "unicode" "bytes" "strings" ) func LetterChanges(str string) string { var buffer bytes.Buffer for i := 0; i < len(str); i++ { var letter string if unicode.IsLetter(rune(str[i])) { if (string(str[i])) == "z" { letter = "a" } else if string(str[i]) == "...
package assembler import ( "log" "golang.org/x/sys/cpu" ) var useAVX2, useAVX, useSSE4 bool func init() { useSSE4 = cpu.X86.HasSSE41 useAVX = cpu.X86.HasAVX useAVX2 = cpu.X86.HasAVX2 Init(true) log.Printf("SSE4: %v", useSSE4) log.Printf("AVX: %v", useAVX) log.Printf("AVX2: %v", useAVX2) } var logging bo...
package testutil import ( "reflect" "sort" ) var ints1k [1000]int var ints1ksorted [1000]int func init() { for i := 0; i < 1000; i++ { ints1k[i] = i ^ 0x2cc ints1ksorted[i] = ints1k[i] } sort.Ints(ints1ksorted[:]) } func InputInts() []int { return []int{74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, ...
package httpmanager import ( "encoding/json" "net/http" ) type infoInputBody struct { } type infoOutputBody struct { Used int32 `json:"used"` Total int32 `json:"total"` UnitRequest int32 `json:"unitRequest"` UnitPrice int32 `json:"unitPrice"` } // InfoHandler returns the basic info of the cloud...
package lib import ( "fmt" "github.com/go-piv/piv-go/piv" "golang.org/x/crypto/ssh/terminal" "strings" ) func AskPin() (string, error) { fmt.Print("Enter PIN: ") pin, err := terminal.ReadPassword(0) if err != nil { return "", err } return strings.TrimSpace(string(pin)), nil } func GetYubikey()...
/* This art-app is purely used to generate the HTML file */ package main // Expects blockartlib.go to be in the ../blockartlib/ dir, relative to // this art-app.go file import ( "crypto/x509" "encoding/hex" "encoding/json" "fmt" "html/template" "io/ioutil" "log" "net/http" "os" "strings" "./blockartlib"...
package main import ( "fmt" "image" "image/color" "image/draw" "image/jpeg" "os" "path/filepath" "neilpa.me/phace" ) // OutlineFaces creates a new image, drawing a boarder around the faces. // Dumps the resulting image in `out/` with the same basename as the // original. Best way to check how things are actu...
package cloud func GetRegion() { return }
package controller import ( database "../connect" "../models" "github.com/gin-gonic/gin" ) func Read(c *gin.Context) { db := database.Connect() models.ShowValues(db, c) defer db.Close() // Hoãn lại việc close database connect cho đến khi hàm Read() thực hiệc xong } func Insert(c *gin.Context) { record := mode...
package piscine func IsPrintable(str string) bool { //checking whether string is containing smth, if not - false if str == "" { return false } array := []rune(str) for _, char := range array { //checking for printable values // 32 - SPACE, 126 - TILDA if char >= ' ' && char <= '~' { continue } else {...
package main import ( "fmt" "os" "sort" "github.com/gin-gonic/gin" "github.com/yuneejang/webserver/config" "github.com/yuneejang/webserver/utils" "gopkg.in/urfave/cli.v1" ) func main() { app := cli.NewApp() app.Copyright = "Copyright 2020-2020 The go-symverse Authors" app.Version = "0.0.0" app.Name = "We...
package configfile import ( "encoding/json" "encoding/xml" "fmt" "os" "strings" "github.com/stewelarend/config" "gopkg.in/yaml.v2" ) func Add(filename string) error { f, err := os.Open(filename) if err != nil { return fmt.Errorf("cannot open file(%s): %v", filename, err) } defer f.Close() if strings.H...
package schedule import ( "fmt" "gopkg.in/tomb.v2" "gopkg.in/mgo.v2" "strconv" "strings" "sync" "time" "TskSch/msgQ" ) type Schedule struct { L string Id int Name string W *sync.WaitGroup Session *mgo.Session Host string Port string T tomb.Tomb } type Result struct { Task_id string //command ID...
package tmp const DatabaseTmp = `package database{{$module := .ModuleName}} import ( "fmt" {{if isOnePostgres}} "database/sql" _ "github.com/lib/pq"{{end}} {{printf "\"%v/helper\"" $module}} {{range $i,$k := .DBS}} {{printf "\"%v/store/%v_store\"" $module $i }}{{end}} {{if isOneMongo}} "go.mongodb.org/mongo...
package pathtree import ( "log" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func init() { log.SetFlags(log.LstdFlags | log.Lshortfile) } func TestNewPathTree(t *testing.T) { p := New() require.NotNil(t, p) assert.Equal(t, "/", p.Root()) p = New("/usr/local/bin") ...
package fuse import ( "log" ) var _ = log.Println func (me *DefaultRawFuseFileSystem) Init(h *InHeader, input *InitIn) (*InitOut, Status) { return new(InitOut), OK } func (me *DefaultRawFuseFileSystem) Destroy(h *InHeader, input *InitIn) { } func (me *DefaultRawFuseFileSystem) Lookup(h *InHeader, name string) (...
// Licensed to SolID under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. SolID licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use this file except in compli...
package login import ( "github.com/gin-gonic/gin" "github.com/charlesfan/go-api/service/rsi" "github.com/charlesfan/go-api/utils/log" ) func CheckEmail() gin.HandlerFunc { return func(c *gin.Context) { //Implement b := rsi.EmailLoginBody{} if err := c.Bind(&b); err != nil { log.Error(err) log.Error(...
package main import ( "net/http" "web" "log" "time" "spider/controller" "mycache" "task" "util" "strconv" "spider/entity" "fmt" ) /** @Todo 检查北上广是否重复创建缓存 */ func main() { //创建任务队列 taksCache := mycache.GetCache("task") //开启服务 go func() { for url := range task.Task { _, err := mycache.Get(taksCache...
/* 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 silverfish import ( "crypto/sha512" "encoding/hex" "math/rand" "strings" ) const dictionary string = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" // SHA512Str export func SHA512Str(src, hashSalt *string) *string { salted := strings.Join([]string{*src, *hashSalt}, "") h := sha512.New...
func strStr(haystack string, needle string) int { if needle == "" { return 0 } needleLength := len(needle) haystackLength := len(haystack) if haystackLength < needleLength { return -1 } searchFlag := 0 for i := 0; i < haystackLength-needleLength+1; i++ { for j := 0; j < needleLength; j++ { if i+j >...
package subscription import ( "github.com/dennor/go-paddle/events/types" "github.com/dennor/phpserialize" ) const UpdatedAlertName = "subscription_updated" // Updated refer to https://paddle.com/docs/subscriptions-event-reference/#subscription_updated type Updated struct { AlertID int ...
package metrics import ( "flag" "fmt" "io/ioutil" "log" "os" "plugins" "regexp" "strings" "time" ) // TCP Network stats // // gobs of this code lifted from: https://github.com/grahamking/latency/ // // DESCRIPTION // This plugin attempts to determine network latency. // interface is up and we cannot ping. /...