text
stringlengths
11
4.05M
package main import ( "fmt" ) type TreeNode struct { Val int Left *TreeNode Right *TreeNode } // 想法: // 遍历树,将得到的结果放入数组,然后再对数组求两数之和 // 采用中序遍历,这样得到的结果是一个生序的数组,就不用再进行排序了 func findTarget(root *TreeNode, k int) bool { st := []*TreeNode{} nums := []int{} for len(st) > 0 || root != nil { len := len(st) if r...
package run import ( "testing" floc "gopkg.in/workanator/go-floc.v1" ) func TestSequenceInactive(t *testing.T) { // Construct the flow control object. flow := floc.NewFlow() defer flow.Release() flow.Complete(nil) // Construct the state object which as data contains the counter. state := floc.NewState(new(...
// Copyright 2014 Google 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 applicabl...
package impl import ( "errors" "fmt" "net" "sync" ) type Connection struct { tcpConn net.Conn conns *map[string]net.Conn inChannel chan []byte outChannel chan []byte closeChannel chan []byte mutex sync.Mutex isClosed bool } func InitCreateConnection(tcpConn net.Conn, tcpConns *...
// Package main - задание пятого урока для курса go-core. package main import ( "fmt" "go.core/lesson5/pkg/crawler" "go.core/lesson5/pkg/crawler/spider" "go.core/lesson5/pkg/index" "go.core/lesson5/pkg/storage" "go.core/lesson5/pkg/storage/bstree" "strings" ) type Engine struct { Index index.Service Storag...
package main import ( "reflect" "testing" ) //func TestMain(t *testing.T) { // //} func TestPreprocessURL(t *testing.T) { urls := []string{"google.com", "http://someweb.com"} expectedURLs := []string{"http://google.com", "http://someweb.com"} processedURLs := preprocessURL(urls) if !reflect.DeepEqual(expected...
package cache import ( "net/http" "net/http/httptest" "testing" "time" "github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi" "github.com/karlseguin/ccache/v2" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/endpoints" "github.com/...
package polar2cartesian import ( "fmt" "math" "sync" ) // polar 极坐标 type polar struct { radius float64 θ float64 } // cartesian 笛卡尔坐标 type cartesian struct { x float64 y float64 } func (c *cartesian) String() string { return fmt.Sprintf("x=%.2f, y=%.2f", c.x, c.y) } // wg 等待组, 用于等待所有goroutine执行完毕 var ...
package backend import "errors" var ( // ErrTableAlreadyExists occures when creating table exists ErrTableAlreadyExists = errors.New("the table already exists") // ErrTableNotFound occures when creating table exists ErrTableNotFound = errors.New("there is no such table") // ErrIndexNotFound occurs when a table...
package server import ( "encoding/gob" "server/libs/common/event" "server/util" ) var ( core *Server ) func NewServer(app Apper, id int32) *Server { s := &Server{} core = s s.AppId = id s.WaitGroup = &util.WaitGroupWrapper{} s.exitChannel = make(chan struct{}) s.shutdown = make(chan struct{}) s.Eventer = ...
package meetup import ( "beer/internal/domain/model" "beer/internal/tools/customerror" "context" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "testing" ) func TestCalculateBeer(t *testing.T) { var inputs = []struct { beerPerson float64 totalGuest int64 expectedBox int64 }{ ...
package sdkconnector import ( "os" "github.com/hyperledger/fabric-sdk-go/pkg/client/resmgmt" "github.com/hyperledger/fabric-sdk-go/pkg/common/errors/retry" packager "github.com/hyperledger/fabric-sdk-go/pkg/fab/ccpackager/gopackager" "github.com/hyperledger/fabric-sdk-go/pkg/fabsdk" ) //InstallCC packages and i...
package main import "fmt" // 279. 完全平方数 // 给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。 // https://leetcode-cn.com/problems/perfect-squares/ func main() { fmt.Println(numSquares(3)) } // 法一:动态规划 func numSquares(n int) int { dp := make([]int, n+1) dp[1] = 1 for i := 2; i <= n; i++ { dp[...
package main import ( "fmt" "strconv" ) /* Go语言内置包之strconv 实现了基本数据类型和其字符串表示的相互转换,主要有以下常用函数: Atoi()、Itia()、parse系列、format系列、append系列 string与int类型转换 将字符串类型的整数转换为int类型 func Atoi(s string) (i int, err error) 将int类型数据转换为对应的字符串表示 func Itoa(i int) string Parse系列函数 Parse类函数用于转换字符串为给定类型的值 func ParseBool...
/* * Copyright 2020-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicabl...
package dorisloader import ( "context" ) type bulkWorker struct { p *BulkProcessor i int bulkActions int bulkSize int service *BulkService flushC chan struct{} flushAckC chan struct{} } // newBulkWorker creates a new bulkWorker instance. func newBulkWorker(p *BulkProcessor, ...
package main import ( "bytes" "math/rand" "net" "testing" ) func TestServer(t *testing.T) { CONNECT := []byte{ // fixed header: 0x10, // CONNECT 0x1d, // remaining length (29 bytes) // variable header: 0x00, 0x06, // protocol name length 0x4d, 0x51, 0x49, 0x73, 0x64, 0x70, // protocol name "MQIsdp"...
package main import "fmt" func main() { const occupancyLimit = 12 var occupancyLimit1 uint8 var occupancyLimit2 int64 var occupancyLimit3 float32 occupancyLimit1 = occupancyLimit occupancyLimit2 = occupancyLimit occupancyLimit3 = occupancyLimit fmt.Println(occupancyLimit1, occupancyLimit2, occupancyLimit3)...
package pov import ( "errors" "time" "github.com/qlcchain/go-qlc/common" "github.com/qlcchain/go-qlc/common/types" ) type ConsensusFake struct { chainR PovConsensusChainReader } func NewConsensusFake(chainR PovConsensusChainReader) *ConsensusFake { consFake := &ConsensusFake{chainR: chainR} return consFake }...
// Copyright (c) 2020 Hirotsuna Mizuno. All rights reserved. // Use of this source code is governed by the MIT license that can be found in // the LICENSE file. package speedio_test import ( "io" "testing" "time" "github.com/tunabay/go-randdata" "github.com/tunabay/go-speedio" ) // func TestMeterReader_test1(t...
package main import "time" type Network struct { Time time.Time Addresses []Address } type Address struct { IP string MAC string Vendor string } type VendorRecord struct { MACPrefix string Vendor string }
package agent import ( "net" "shellbin/internal/logger" ) type tcpListener struct { port string aChan chan Agent } func (t tcpListener) Listen() { l, err := net.Listen("tcp", "0.0.0.0:"+t.port) if err != nil { panic(err.Error()) } defer l.Close() for { c, err := l.Accept() if err != nil { logger...
package bag01 // New 创建01背包问题 func New(itemsW []int, w int) *Bag01 { n := len(itemsW) if n == 0 || w == 0 { panic("error params") } // 初始化状态数组 status := make([]bool, w+1) return &Bag01{itemsW, w, status} } // Bag01 01背包问题 // 固定物品范围的前提下,求背包可放物品最大重量 type Bag01 struct { // 可放物品的重量 itemsW []int // 背包承重能力 wCap...
package fields import ( "encoding/json" "reflect" rc_fields "github.com/square/p2/pkg/rc/fields" "github.com/square/p2/pkg/types" "k8s.io/kubernetes/pkg/labels" ) // Types stored in the actual pod cluster document type ID string type AvailabilityZone string type ClusterName string type Annotations map[string]i...
package main import ( "bufio" "fmt" "io" "net" ) func main() { connectControl() } var ( CONTROL_PORT string = "8009" ) func connectControl() { var tcpAddr *net.TCPAddr //这里在一台机测试,所以没有连接到公网,可以修改到公网ip tcpAddr, _ = net.ResolveTCPAddr("tcp", "127.0.0.1:" + CONTROL_PORT) conn, err := net.DialTCP("tcp", nil, tc...
package annotations import ( "errors" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestGetTrafficType(t *testing.T) { tests := []struct { desc string annotations map[string]string want string err bool }{ { desc: "unknown service ...
package goSolution import "testing" func TestFindDuplicate(t *testing.T) { paths := []string {"root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)","root 4.txt(efgh)"} AssertEqual(t, [][]string {{"root/a/1.txt","root/c/3.txt"}, {"root/a/2.txt","root/c/d/4.txt","root/4.txt"}}, findDuplicate(pa...
package main import "fmt" func main() { classNum, stuNum := 2, 5 var passCount int = 0 var totalSum float64 = 0 var j = 1 for ; j <= classNum; j++ { var i = 1 sum := 0.0 for ; i <= stuNum; i++ { var grade float64 fmt.Printf("输入%d班第%d个学生的分数:\n", j, i) _, err := fmt.Scanf("%f", &grade) if err != ...
// 该文件由 make.go 自动生成,请勿手动修改! package static var assets = map[string][]byte{ "./style.css": []byte(`@charset "utf-8"; :root { --aside-width: 350px; --aside-footer-height: 140px; --aside-header-height: 80px; } /*============== reset =================*/ body { margin: 0 } a { text-decoration: non...
/* * Tencent is pleased to support the open source community by making Blueking Container Service available. * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except * in compliance with the License. You may obta...
/***************************************************************** * Copyright©,2020-2022, email: 279197148@qq.com * Version: 1.0.0 * @Author: yangtxiang * @Date: 2020-08-03 11:28 * Description: *****************************************************************/ package netstream import ( "errors" "github.com/go-xe2...
package provider import ( "context" "fmt" "github.com/ottogroup/penelope/pkg/config" "github.com/ottogroup/penelope/pkg/http/impersonate" ) type defaultImpersonatedTokenConfigProvider struct { } func NewDefaultImpersonatedTokenConfigProvider() impersonate.TargetPrincipalForProjectProvider { retur...
package hall_call_handler //******** // Routines for computing a suitability score for each elevator and handling of designated hall call orders. // Moved here because of loops when it was in order_handler. //******** import ( "math" "time" elevio "../elev_driver" slog "../sessionlog" statemachine "../stateMach...
package main import ( "fmt" "" // put in link from master "" // put in link from master ) type OS_Swift struct { Login string Password string TenantID string EndPointURL string Tenant string SwiftHandler swift.Connection } func (s *OS_Swift) Auth() string { s.SwiftHandler = swift.Conn...
package app import ( "io/ioutil" "path/filepath" "testing" "github.com/10gen/realm-cli/internal/cloud/realm" "github.com/10gen/realm-cli/internal/local" "github.com/10gen/realm-cli/internal/utils/test/assert" "github.com/10gen/realm-cli/internal/utils/test/mock" "github.com/Netflix/go-expect" ) func TestApp...
// Copyright 2015 by caixw, All rights reserved. // Use of this source code is governed by a MIT // license that can be found in the LICENSE file. package main import ( "time" "github.com/issue9/term/colors" ) type logLevel int // 是否不显示被标记为IGNORE的日志内容。 var showIgnoreLog = false const ( succ logLevel = iota in...
// Source : https://oj.leetcode.com/problems/longest-common-prefix/ // Author : Austin Vern Songer // Date : 2016-04-13 /********************************************************************************** * * Write a function to find the longest common prefix string amongst an array of strings. * **...
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0. package export import ( "bytes" "testing" "github.com/stretchr/testify/require" ) func TestEscape(t *testing.T) { var bf bytes.Buffer str := []byte(`MWQeWw""'\rNmtGxzGp`) expectStrBackslash := `MWQeWw\"\"\'\\rNmtGxzGp` expectStrWithoutBackslash := `M...
package main import ( "fmt" "strconv" ) func main() { fmt.Println(strconv.ParseBool("1")) //true fmt.Println(strconv.ParseBool("t")) fmt.Println(strconv.ParseBool("T")) fmt.Println(strconv.ParseBool("true")) fmt.Println(strconv.ParseBool("True")) fmt.Println(strconv.FormatBool(0 < 1)) fmt.Println(strconv.Fo...
package main import ( "fmt" "strings" ) // https://leetcode-cn.com/problems/text-justification/ //------------------------------------------------------------------------------ func fullJustify(words []string, maxWidth int) []string { N := len(words) const FMT = "%%%ds" var res []string add := func(start, end,...
package structures // Package defines an AS3 package, which doesn't really exist in JS. The package is not used at all // to print out JS, but it may be needed to avoid name collisions, and therefore it is implemented, // but don't expect any output from it soon. // Package does validate that every class must be wrapp...
package mgr import ( "fmt" "testing" "github.com/go-xorm/xorm" "github.com/jchprj/GeoOrderTest/cfg" "github.com/go-sql-driver/mysql" ) func TestCreateEngine(t *testing.T) { cfg.InitConfig("../docker/config.yml") err := initMySQL() if err != nil { t.Errorf("init err %v", err) } engine, err := GetEngine()...
package api import ( "encoding/json" utils "github.com/kevinbarbary/go-lms/utils" "log" "net/http" ) type TokenInfo struct { Expires string Now string SecondsRemaining int64 URL string SiteID string LoginID string } func CheckToken(token, useragent, sit...
package main import ( "fmt" "net" ) func main() { p := make([]byte, 44100*0.02*2) // fmt.Print("the p is ") // fmt.Println(len(p)) // time.Sleep(time.Second * 2) addr := net.UDPAddr{ Port: 2000, IP: net.ParseIP("192.168.25.18"), } ser, err := net.ListenUDP("udp", &addr) fmt.Printf("WUT?") for { ...
package main import "fmt" func main() { x := 100 switch { case x < 5: fmt.Println("X é menor que 5") case x == 5: fmt.Println("X é igual 5") case x > 5 && x <= 10: fmt.Println("X é maior que 5") default: fmt.Println("X é maior que 10") } y := "b" switch y { case "a": fmt.Println("Y é a letra A"...
package dataloaders // go:generate go run github.com/vektah/dataloaden UserLoader string *github.com/GlitchyGlitch/typinger/models.User // go:generate go run github.com/vektah/dataloaden ArticlesLoader string []*github.com/GlitchyGlitch/typinger/models.Article type Loaders struct { UserByIDs *UserLoader Art...
package encoding import ( "fmt" gkeys "github.com/number571/go-cryptopro/gost_r_34_10_2012" "github.com/number571/tendermint/crypto" "github.com/number571/tendermint/crypto/gost256" "github.com/number571/tendermint/crypto/gost512" "github.com/number571/tendermint/libs/json" pc "github.com/number571/tendermint/...
/* * Copyright 2018-present Open Networking Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law ...
package templatecode const ( templateController = `package controllers // target type target struct { BaseController } // Index() 页面 func (this *target) Index() { this.SimpleView() } // Add() 添加 func (this *target) Add() { } // Get() 查询单条记录 func (this *target) Get() { } // All() 查询多条记录 func (this *target) All(...
package main import ( "fmt" ) func main() { var t int fmt.Scan(&t) for ;t>0;t-- { var s int fmt.Scan(&s) v := make([]int, s) for i:=0; i<s; i++ { fmt.Scan(&v[i]) } p1 := 0 for ;v[p1]==0 && p1<s; p1++ {} p2 := s-1 for ; v[p2]==0 && p2>=0; p2-- {} ans := 0 for i:=p1; i...
package router import ( "github.com/ArakiTakaki/golangWebLesson/controllers/api" "github.com/gin-gonic/gin" ) func apiSet(r *gin.RouterGroup) { // /home/index.html に飛ぶ様に設定されている。(飛ばす場所) r.GET("/items", api.NavItems) r.GET("/meta", api.PageData) }
package main import ( "fmt" ) func main() { test := "hello" test += "hello2" test += "hello3" fmt.Println(test) fmt.Println("Hello, playground") }
package store import ( mystore "bookstore/store" factory "bookstore/store/factory" "sync" ) // 在初始化中注册,只要有导入internal/store包,就自动完成了注册 func init() { factory.Register("mem", &MemStore{ books: make(map[string]*mystore.Book), }) } type MemStore struct { sync.RWMutex books map[string]*mystore.Book } func (ms *Me...
package helper import ( "math/rand" "time" ) type Charset string const ( DefaultCharset = Charset("abcdefghijklmnopqrstuvwxyz1234567890") NumricCharset = Charset("1234567890") ) func init() { rand.Seed(time.Now().Unix()) } func (cs Charset) RandomStr(size int) string { var ( charset = string(cs) outp ...
package app import ( "github.com/spf13/cobra" rt "github.com/k82cn/myoci/pkg/runtime" ) var runFlags rt.RunFlags // RunCommand get the run command instance. func RunCommand() *cobra.Command { runCmd := &cobra.Command{ Use: "run", Short: "Run an image as container", Long: "Run an image as container...
// Package fail - state.go Determines state of servers from responses package main import "net/http" import "time" // http client var client = &http.Client{Timeout: 10 * time.Second} // states var States = map[int]string{ 0: "RED", 1: "GREEN", 2: "BLUE", } // Poll a server to get flood state func getState(server...
package model import ( "errors" "fmt" "time" "walletApi/src/common" "github.com/astaxie/beego/orm" _ "github.com/go-sql-driver/mysql" ) //应用版本 type AppVersion struct { Id int64 `orm:"auto" from:"id" description:"主键ID"` AppName string `orm:"size(80)" valid:"Required" form:"appName" des...
/* Copyright 2017 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, ...
// 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 ( "flag" "fmt" "github.com/slack-go/slack" ) func main() { var ( apiToken string debug bool ) flag.StringVar(&apiToken, "token", "YOUR_TOKEN_HERE", "Your Slack API Token") flag.BoolVar(&debug, "debug", false, "Show JSON output") flag.Parse() api := slack.New(apiToken, slack.Opti...
package autoquad /* Generated using mavgen - https://github.com/ArduPilot/pymavlink/ Copyright 2020 queue-b <https://github.com/queue-b> Permission is hereby granted, free of charge, to any person obtaining a copy of the generated software (the "Generated Software"), to deal in the Generated Software without restric...
package problem0239 import "testing" func TestSolve(t *testing.T) { t.Log(maxSlidingWindow([]int{1, 2, 3, -4, 5}, 2)) }
package wcloudmessage import ( "github.com/satori/go.uuid" ) type CloudMessageData struct { TargetScreen string Show_in_foreground bool Notification Notification } type Notification struct { Id uuid.UUID OrderId string OrderCommentId string Time string IsNotified ...
package main import ( "github.com/go-redis/redis" "fmt" "strconv" "github.com/samuel/go-zookeeper/zk" "time" "strings" ) var client *redis.Client var zkHandler *zk.Conn func init() { client = redis.NewClient(&redis.Options{ Addr: "10.96.90.6:6379", Password: "", // no password set DB: 0, // ...
package main import ( "crypto/md5" "flag" "fmt" "io" "io/ioutil" "log" "os" "path" "path/filepath" "strings" ) //目标目录的父目录 var Parents_dir string //根据目标目录的路径,在目标目录的父目录下创建重复文件目录 var Same_file_dir string //指定要去重的目录 var source_path string //遍历目标目录的所有文件,存到slice中 var file_list []string //经过计算对比md5值,将重复文件目录放到s...
package main import "encoding/json" import "fmt" import "bytes" type Gender int const ( GenderNotSet = iota GenderMale GenderFemale GenderOther ) var toString = map[Gender]string{ GenderNotSet: "Not Set", GenderMale: "Male", GenderFemale: "Female", GenderOther: "Other", } var toID = map[string]Gender{...
package main import ( "testing" "github.com/jackytck/projecteuler/tools" ) func TestP50(t *testing.T) { cases := []tools.TestCase{ {In: 100, Out: 41}, {In: 1000, Out: 953}, {In: 1000000, Out: 997651}, } tools.TestIntInt(t, cases, consecutivePrimeSum, "P50") }
// (C) Copyright 2012, Jeramey Crawford <jeramey@antihe.ro>. All // rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package sha256_crypt import "testing" var sha256Crypt = New() func TestGenerate(t *testing.T) { data := []struct { salt []byte ...
package server import ( "context" "io" "net" "sync" "github.com/eclipse/paho.mqtt.golang/packets" "github.com/htdvisser/squatt/session" "go.uber.org/zap" ) // Buffer sizes var ( ClientSendBufferSize = 16 ) // Client connection type Client struct { server *Server log *zap.Logger remoteAddr stri...
package bench import ( "reflect" "testing" ) // http://www.darkcoding.net/software/go-the-price-of-interface/ // Just getting the reflect.Value of a string. // 45ns. // Or, 60ns with GC enabled. Yes, quite a difference. func Benchmark_ReflectGetValueOfString(b *testing.B) { var slot string for i := 0; i < b.N; ...
// 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. // +build !windows,!linux,!darwin,!openbsd,!freebsd package router import ( "github.com/tailscale/wireguard-go/device" "github.com/tailscale/wir...
package main import ( "fmt" "log" "os" "github.com/resin-os/resin-provisioner/provisioner" ) func init() { // show date/time in log output. log.SetFlags(log.LstdFlags) } func usage() { fmt.Fprintf(os.Stderr, "usage: query: %s [config path]\n", os.Args[0]) fmt.Fprintf(os.Stderr, "usage: provision: %s [co...
/* * Copyright (c) 2020. Ant Group. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 */ package config import ( "encoding/json" "testing" "github.com/stretchr/testify/require" ) func TestLoadConfig(t *testing.T) { buf := []byte(`{ "device": { "backend": { "type": "registry", "c...
package main import ( "crypto/md5" "crypto/tls" "crypto/x509" "fmt" "github.com/Azunyan1111/http-recoder/keys" "github.com/elazarl/goproxy" "log" "net/http" "net/http/httputil" "os" "regexp" "strconv" "strings" ) func main() { proxy := goproxy.NewProxyHttpServer() proxy.Verbose = true goproxyCa, _ :=...
package agent import () type Load interface { Load(file string) error } type Crawl interface { Crawl(loader *Loader) error } type Save interface { ReArrange(channels Channels) error Save() error }
package fcache import ( "sync" "github.com/nuczzz/lru" "sync/atomic" ) // memCache memory cache. type memCache struct { // m map of memory cache. m map[interface{}]*lru.Node // needCryptKey crypt key or not. needCryptKey bool // lru lru control lru *lru.LRU // lock lock of memory cache data. lock sync....
package main import( "fmt" ) type Bet int const( NoBET Bet = iota TICHU GRAND_TICHU ) type Suit int const( Spade Suit = iota Heart Diamond Club Special ) type Card struct { Suit Suit Rank int // 2-10, plus J,Q,K,A (11,12,13,14) } const( Sparrow = Card{Special, 1} Dragon = Card{Special, 2} Pheonix = Ca...
package rc522 const ( //MF522 command PCD_IDLE = 0x00 PCD_AUTHENT = 0x0E PCD_RECEIVE = 0x08 PCD_TRANSMIT = 0x04 PCD_TRANSCEIVE = 0x0C PCD_RESETPHASE = 0x0F PCD_CALCCRC = 0x03 //Mifare_One PICC_REQIDL = 0x26 PICC_REQALL = 0x52 PICC_ANTICOLL1 = 0x93 PICC_ANTICOLL2 = 0x95 PICC_ANTICO...
package util import ( "io" "os" "github.com/pkg/errors" ) // ForEachFile iterates over every file in the specified directory path, // invoking fn for each identified file. // // If path is not a directory, ForEachFile will return an error. // // If fn returns an error, iteration will stop and ForEachFile will ret...
package gengateway import ( "io" "log" "net/http" "time" "github.com/gogo/protobuf/proto" "golang.org/x/net/context" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/grpclog" "github.com/vanishs/gwsrpc/utils" "github.com/vanishs/gwsrpc/ws" "github.com/vanishs/gwsr...
package example func main() { var str string = "hello" integer := int(str) // complile error: cannot convert str (type string) to type int }
package modules import ( "fmt" "testing" "time" "github.com/stretchr/testify/assert" ) func TestGetMapUpdatedItems(t *testing.T) { tm := NewTemplateKeyValueMaker( &CrudEvent{ UpdatedData: `{"test":"t1","test_id":1}`, }, &NotificationType{ TitleTemplate: "", MessageTemplate: "", }) assert.Eq...
package dstate import ( "errors" "github.com/NamedKitten/discordgo" "sync" "time" ) var ( ErrMemberNotFound = errors.New("Member not found") ErrChannelNotFound = errors.New("Channel not found") ) type GuildState struct { sync.RWMutex // ID is never mutated, so can be accessed without locking ID int64 `jso...
package blockchain import ( "bytes" "encoding/gob" "fmt" "log" "time" "github.com/neil-berg/blockchain/database" ) // Block shape type Block struct { Data []byte Hash []byte PrevHash []byte Nonce int Timestamp time.Time } // Blockchain shape type Blockchain struct { // The blockchain's ti...
package unio import ( "github.com/labstack/echo" "reflect" "strings" ) /** Middleware Run all JSON body fields, and format the need */ func (m *Middleware) JsonFormatFields(formatter RequestFormatRule) echo.MiddlewareFunc { return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) (er...
package plient import ( "net/http" "net/url" ) type Plient struct { client *http.Client headers []Header } type Header struct { key string value string } func create(proxy string, headers []Header) *Plient { proxyUrl, err := url.Parse(proxy); if err != nil { panic("Proxy error") } client := &http.Cl...
package parser import ( "errors" "strings" ) const ErrorMsg = "invalid mysql url" func ParseMysqlUrl(url string) (string, error) { protocolAndRest := strings.Split(url, "://") if len(protocolAndRest) != 2 { return "", errors.New(ErrorMsg) } _ = protocolAndRest[0] hostAndRest := strings.Split(protocolAndRes...
package send import ( "encoding/json" "io/ioutil" "net/http" "net/url" "strings" "errors" ) type SSAcao string type SStatus string const( SendSms SSAcao = "sendsms" BulkSms SSAcao = "bulksms" StatusError SStatus = "error" StatusSuccess SStatus = "success" PARAM_ACAO string = "acao" ...
package utils import ( "os" "strconv" ) // GetEnv - для удобного чтения переменных окружения func GetEnv(key string, defaultVal interface{}) interface{} { if value, exists := os.LookupEnv(key); exists { var result = defaultVal switch defaultVal.(type) { case int: if res, err := strconv.Atoi(value); err ...
package testing import ( "testing" "github.com/brigadecore/brigade/sdk/v3" "github.com/stretchr/testify/require" ) func TestMockSystemClient(t *testing.T) { require.Implements(t, (*sdk.SystemClient)(nil), &MockSystemClient{}) }
package main type Def struct { Dict string `json:"dict"` Desc string `json:"desc"` } type Res struct { Term string `json:"term"` Defs []*Def `json:"definition,omitempty"` Sugs []string `json:"suggestions,omitempty"` }
/* Copyright (c) 2017 GigaSpaces Technologies Ltd. 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 ...
package racecond import ( "fmt" "sync" ) //Program with race condition var x = 0 func increment(wg *sync.WaitGroup) { x = x + 1 wg.Done() } //RunIncrements runs "increment()" func "numIncrements" times func RunIncrements(numIncrements int) { var wg sync.WaitGroup for i := 0; i < numIncrements; i++ { wg.Add...
// Package callbacks provides callback implementations for Discord API events. package callbacks import ( "context" "fmt" "time" "github.com/bwmarrin/discordgo" "github.com/opentracing/opentracing-go" "github.com/prometheus/client_golang/prometheus" "github.com/ewohltman/ephemeral-roles/internal/pkg/logging" ...
// Fact returns the factorial of n. func Fact(n int) int { r := 1 for ; n > 1; n-- { r *= n } return r }
package main import . "github.com/little-go/practices/visitor" func main() { info := Info{} var v Visitor = &info //v = LogVisitor{v} //v = NameVisitor{v} //v = OtherThingsVisitor{v} loadFile := func(info *Info, err error) error { info.Name = "Hao Chen" info.Namespace = "MegaEase" info.OtherThings = "We a...
package main import ( "net" "log" "fmt" "bufio" ) // 入口函数 func main() { conn,err:=net.Dial("tcp","127.0.0.1:3130") if err!=nil { log.Println(err) } fmt.Fprintf(conn,"GET / HTTP/1.0\r\n") status,err:=bufio.NewReader(conn).ReadString('\n') fmt.Println(status) }
// Copyright (c) 2015 Klaus Post, released under MIT License. See LICENSE file. package shutdown import ( "bytes" "fmt" "math/rand" "net/http" "os" "runtime" "runtime/pprof" "strconv" "strings" "sync" "testing" "time" ) func reset() { SetTimeout(1 * time.Second) sqM.Lock() defer sqM.Unlock() srM.Lock...
// Mandelbrot creates PNG of Mandelbrot package mandelbrot import ( "image" "image/color" "image/png" "io" "math/cmplx" ) func Mandelbrot(w io.Writer, xmin, xmax, ymin, ymax float64, width, height int) { img := image.NewRGBA(image.Rect(0, 0, width, height)) for py := 0; py < height; py++ { y := float64(py)/f...
package tts import ( "fmt" "testing" ) var text = ` 我現在 schedule 上總 total 有10個 case 在 run, 等等還要跟我的 team 再 confirm 一下 format, 可能要再 review 一下新版的 checklist, 看 data 現在處理的 process 到哪邊,都 check 完、confirm了都 OK 的話,就只要給他們去 maintain 就好了,Anyway, 明天跟 RD 部門的 leader meeting還是 focus 在 interface 和 menu 上面, 反正他們都有 for 新平台的 know how...