text stringlengths 11 4.05M |
|---|
// +build js
package math4g
import (
"math"
"github.com/gopherjs/gopherjs/js"
)
var (
nan = Scala(js.Global.Get("NaN").Float())
)
func NaN() Scala {
return nan
}
func IsNaN(x Scala) bool {
/* slow implementation: 1
return js.Global.Get("isNaN").Invoke(x).Bool()
*/
return math.IsNaN(float64(x))
}
func Cbrt(x Scala) Scala {
y := Scala(math.Pow(float64(Abs(x)), 1.0/3.0))
if x < 0 {
return -y
} else {
return y
}
} |
package main
func main() {
var a, b struct {
x []int
}
_ = (a == b)
}
|
// // SPDX-License-Identifier: MIT OR Unlicense
package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
str "github.com/boyter/go-string"
"github.com/gdamore/tcell"
"github.com/rivo/tview"
"os"
"runtime"
"strconv"
"strings"
"sync"
"time"
)
type displayResult struct {
Title *tview.TextView
Body *tview.TextView
BodyHeight int
SpacerOne *tview.TextView
SpacerTwo *tview.TextView
Location string
}
type codeResult struct {
Title string
Content string
Score float64
Location string
}
type tuiApplicationController struct {
Query string
Offset int
Results []*FileJob
DocumentCount int64
Mutex sync.Mutex
DrawMutex sync.Mutex
SearchMutex sync.Mutex
// View requirements
SpinString string
SpinLocation int
SpinRun int
}
func (cont *tuiApplicationController) SetQuery(q string) {
cont.Mutex.Lock()
cont.Query = q
cont.Mutex.Unlock()
}
func (cont *tuiApplicationController) IncrementOffset() {
cont.Offset++
}
func (cont *tuiApplicationController) DecrementOffset() {
if cont.Offset > 0 {
cont.Offset--
}
}
func (cont *tuiApplicationController) ResetOffset() {
cont.Offset = 0
}
func (cont *tuiApplicationController) GetOffset() int {
return cont.Offset
}
// After any change is made that requires something drawn on the screen this is the method that does it
// NB this can never be called directly because it triggers a draw at the end.
func (cont *tuiApplicationController) drawView() {
cont.DrawMutex.Lock()
defer cont.DrawMutex.Unlock()
// reset the elements by clearing out every one so we have a clean slate to start with
for _, t := range tuiDisplayResults {
t.Title.SetText("")
t.Body.SetText("")
t.SpacerOne.SetText("")
t.SpacerTwo.SetText("")
resultsFlex.ResizeItem(t.Body, 0, 0)
}
resultsCopy := make([]*FileJob, len(cont.Results))
copy(resultsCopy, cont.Results)
// rank all results
// then go and get the relevant portion for display
rankResults(int(cont.DocumentCount), resultsCopy)
documentTermFrequency := calculateDocumentTermFrequency(resultsCopy)
// after ranking only get the details for as many as we actually need to
// cut down on processing
if len(resultsCopy) > len(tuiDisplayResults) {
resultsCopy = resultsCopy[:len(tuiDisplayResults)]
}
// We use this to swap out the highlights after we escape to ensure that we don't escape
// out own colours
md5Digest := md5.New()
fmtBegin := hex.EncodeToString(md5Digest.Sum([]byte(fmt.Sprintf("begin_%d", makeTimestampNano()))))
fmtEnd := hex.EncodeToString(md5Digest.Sum([]byte(fmt.Sprintf("end_%d", makeTimestampNano()))))
// go and get the codeResults the user wants to see using selected as the offset to display from
var codeResults []codeResult
for i, res := range resultsCopy {
if i >= cont.Offset {
// TODO run in parallel for performance boost...
snippets := extractRelevantV3(res, documentTermFrequency, int(SnippetLength))
if len(snippets) == 0 { // false positive most likely
continue
}
snippet := snippets[0]
// now that we have the relevant portion we need to get just the bits related to highlight it correctly
// which this method does. It takes in the snippet, we extract and all of the locations and then return
l := getLocated(res, snippet)
coloredContent := str.HighlightString(snippet.Content, l, fmtBegin, fmtEnd)
coloredContent = tview.Escape(coloredContent)
coloredContent = strings.Replace(coloredContent, fmtBegin, "[red]", -1)
coloredContent = strings.Replace(coloredContent, fmtEnd, "[white]", -1)
codeResults = append(codeResults, codeResult{
Title: res.Location,
Content: coloredContent,
Score: res.Score,
Location: res.Location,
})
}
}
// render out what the user wants to see based on the results that have been chosen
for i, t := range codeResults {
tuiDisplayResults[i].Title.SetText(fmt.Sprintf("[fuchsia]%s (%f)[-:-:-]", t.Title, t.Score))
tuiDisplayResults[i].Body.SetText(t.Content)
tuiDisplayResults[i].Location = t.Location
//we need to update the item so that it displays everything we have put in
resultsFlex.ResizeItem(tuiDisplayResults[i].Body, len(strings.Split(t.Content, "\n")), 0)
}
// because the search runs async through debounce we need to now draw
tviewApplication.QueueUpdateDraw(func() {})
}
func (cont *tuiApplicationController) DoSearch() {
cont.Mutex.Lock()
query := cont.Query
cont.Mutex.Unlock()
cont.SearchMutex.Lock()
defer cont.SearchMutex.Unlock()
// have a spinner which indicates if things are running as we expect
running := true
var wg sync.WaitGroup
wg.Add(1)
go func() {
for {
statusView.SetText(fmt.Sprintf("%s searching for '%s'", string(cont.SpinString[cont.SpinLocation]), query))
tviewApplication.QueueUpdateDraw(func() {})
cont.RotateSpin()
time.Sleep(20 * time.Millisecond)
if !running {
wg.Done()
return
}
}
}()
var results []*FileJob
var status string
if strings.TrimSpace(query) != "" {
files := FindFiles(query)
toProcessQueue := make(chan *FileJob, runtime.NumCPU()) // Files to be read into memory for processing
summaryQueue := make(chan *FileJob, runtime.NumCPU()) // Files that match and need to be displayed
q, fuzzy := PreParseQuery(strings.Fields(query))
fileReaderWorker := NewFileReaderWorker(files, toProcessQueue)
fileReaderWorker.FuzzyMatch = fuzzy
fileSearcher := NewSearcherWorker(toProcessQueue, summaryQueue)
fileSearcher.SearchString = q
resultSummarizer := NewResultSummarizer(summaryQueue)
resultSummarizer.FileReaderWorker = fileReaderWorker
resultSummarizer.SnippetCount = SnippetCount
go fileReaderWorker.Start()
go fileSearcher.Start()
// First step is to collect results so we can rank them
fileMatches := []string{}
for f := range summaryQueue {
results = append(results, f)
fileMatches = append(fileMatches, f.Location)
}
searchToFileMatchesCache[query] = fileMatches
plural := "s"
if len(results) == 1 {
plural = ""
}
status = fmt.Sprintf("%d result%s for '%s' from %d files", len(results), plural, query, fileReaderWorker.GetFileCount())
cont.DocumentCount = fileReaderWorker.GetFileCount()
}
running = false
wg.Wait()
statusView.SetText(status)
cont.Results = results
cont.drawView()
}
func (cont *tuiApplicationController) RotateSpin() {
cont.SpinRun++
if cont.SpinRun == 4 {
cont.SpinLocation++
if cont.SpinLocation >= len(cont.SpinString) {
cont.SpinLocation = 0
}
cont.SpinRun = 0
}
}
// Sets up the UI components we need to actually display
var overallFlex *tview.Flex
var inputField *tview.InputField
var queryFlex *tview.Flex
var resultsFlex *tview.Flex
var statusView *tview.TextView
var tuiDisplayResults []displayResult
var tviewApplication *tview.Application
var snippetInputField *tview.InputField
// setup debounce to improve ui feel
var debounced = NewDebouncer(200 * time.Millisecond)
func NewTuiSearch() {
// start indexing by walking from the current directory and updating
// this needs to run in the background with searches spawning from that
tviewApplication = tview.NewApplication()
applicationController := tuiApplicationController{
Mutex: sync.Mutex{},
SpinString: `\|/-`,
}
// Create the elements we use to display the code results here
for i := 1; i < 50; i++ {
var textViewTitle *tview.TextView
var textViewBody *tview.TextView
textViewTitle = tview.NewTextView().
SetDynamicColors(true).
SetRegions(true).
ScrollToBeginning()
textViewBody = tview.NewTextView().
SetDynamicColors(true).
SetRegions(true).
ScrollToBeginning()
tuiDisplayResults = append(tuiDisplayResults, displayResult{
Title: textViewTitle,
Body: textViewBody,
BodyHeight: -1,
SpacerOne: tview.NewTextView(),
SpacerTwo: tview.NewTextView(),
})
}
// input field which deals with the user input for the main search which ultimately triggers a search
inputField = tview.NewInputField().
SetFieldBackgroundColor(tcell.Color16).
SetLabel("> ").
SetLabelColor(tcell.ColorWhite).
SetFieldWidth(0).
SetDoneFunc(func(key tcell.Key) {
// this deals with the keys that trigger "done" functions such as up/down/enter
switch key {
case tcell.KeyEnter:
tviewApplication.Stop()
// we want to work like fzf for piping into other things hence print out the selected version
if len(applicationController.Results) != 0 {
fmt.Println(tuiDisplayResults[0].Location)
}
os.Exit(0)
case tcell.KeyTab:
tviewApplication.SetFocus(snippetInputField)
case tcell.KeyBacktab:
tviewApplication.SetFocus(snippetInputField)
case tcell.KeyUp:
applicationController.DecrementOffset()
debounced(applicationController.drawView)
case tcell.KeyDown:
applicationController.IncrementOffset()
debounced(applicationController.drawView)
case tcell.KeyESC:
tviewApplication.Stop()
os.Exit(0)
}
}).
SetChangedFunc(func(text string) {
// after the text has changed set the query and trigger a search
text = strings.TrimSpace(text)
applicationController.ResetOffset() // reset so we are at the first element again
applicationController.SetQuery(text)
debounced(applicationController.DoSearch)
})
// Decide how large a snippet we should be displaying
snippetInputField = tview.NewInputField().
SetFieldBackgroundColor(tcell.ColorDefault).
SetAcceptanceFunc(tview.InputFieldInteger).
SetText(strconv.Itoa(int(SnippetLength))).
SetFieldWidth(4).
SetChangedFunc(func(text string) {
if strings.TrimSpace(text) == "" {
SnippetLength = 300 // default
} else {
t, _ := strconv.Atoi(text)
if t == 0 {
SnippetLength = 300
} else {
SnippetLength = int64(t)
}
}
}).
SetDoneFunc(func(key tcell.Key) {
switch key {
case tcell.KeyTab:
tviewApplication.SetFocus(inputField)
case tcell.KeyBacktab:
tviewApplication.SetFocus(inputField)
case tcell.KeyEnter:
fallthrough
case tcell.KeyUp:
SnippetLength = min(SnippetLength+100, 8000)
snippetInputField.SetText(fmt.Sprintf("%d", SnippetLength))
debounced(applicationController.DoSearch)
case tcell.KeyPgUp:
SnippetLength = min(SnippetLength+200, 8000)
snippetInputField.SetText(fmt.Sprintf("%d", SnippetLength))
debounced(applicationController.DoSearch)
case tcell.KeyDown:
SnippetLength = max(100, SnippetLength-100)
snippetInputField.SetText(fmt.Sprintf("%d", SnippetLength))
debounced(applicationController.DoSearch)
case tcell.KeyPgDn:
SnippetLength = max(100, SnippetLength-200)
snippetInputField.SetText(fmt.Sprintf("%d", SnippetLength))
debounced(applicationController.DoSearch)
case tcell.KeyESC:
tviewApplication.Stop()
os.Exit(0)
}
})
statusView = tview.NewTextView().
SetDynamicColors(false).
SetRegions(false).
ScrollToBeginning()
// setup the flex containers to have everything rendered neatly
queryFlex = tview.NewFlex().SetDirection(tview.FlexColumn).
AddItem(inputField, 0, 8, false).
AddItem(snippetInputField, 5, 1, false)
resultsFlex = tview.NewFlex().SetDirection(tview.FlexRow)
overallFlex = tview.NewFlex().SetDirection(tview.FlexRow).
AddItem(queryFlex, 1, 0, false).
AddItem(nil, 1, 0, false).
AddItem(statusView, 1, 0, false).
AddItem(resultsFlex, 0, 1, false)
// add all of the display codeResults into the container ready to be populated
for _, t := range tuiDisplayResults {
resultsFlex.AddItem(t.SpacerOne, 1, 0, false)
resultsFlex.AddItem(t.Title, 1, 0, false)
resultsFlex.AddItem(t.SpacerTwo, 1, 0, false)
resultsFlex.AddItem(t.Body, t.BodyHeight, 1, false)
}
if err := tviewApplication.SetRoot(overallFlex, true).SetFocus(inputField).Run(); err != nil {
panic(err)
}
}
func getLocated(res *FileJob, v3 Snippet) [][]int {
var l [][]int
// For all the match locations we have only keep the ones that should be inside
// where we are matching
for _, value := range res.MatchLocations {
for _, s := range value {
if s[0] >= v3.StartPos && s[1] <= v3.EndPos {
// Have to create a new one to avoid changing the position
// unlike in others where we throw away the results afterwards
t := []int{s[0] - v3.StartPos, s[1] - v3.StartPos}
l = append(l, t)
}
}
}
return l
}
|
// Copyright 2019 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package platform
import (
"context"
"time"
"chromiumos/tast/local/memory/memoryuser"
"chromiumos/tast/testing"
)
func init() {
testing.AddTest(&testing.Test{
Func: HeavyMemoryUser,
LacrosStatus: testing.LacrosVariantNeeded,
Desc: "Tests heavy memory use with Chrome, ARC and VMs running",
Contacts: []string{"asavery@chromium.org", "chromeos-storage@google.com"},
// TODO(http://b/172075721): Test is disabled until it can be fixed
// Attr: []string{"group:crosbolt", "crosbolt_memory_nightly"},
Timeout: 10 * time.Minute,
SoftwareDeps: []string{"chrome", "vm_host"},
Params: []testing.Param{{
ExtraSoftwareDeps: []string{"android_p"},
}, {
Name: "vm",
ExtraSoftwareDeps: []string{"android_vm"},
}},
})
}
func HeavyMemoryUser(ctx context.Context, s *testing.State) {
urls := []string{
"https://drive.google.com",
"https://photos.google.com",
"https://news.google.com",
"https://maps.google.com",
"https://play.google.com/store",
"https://play.google.com/music",
"https://youtube.com",
"https://www.nytimes.com",
"https://www.whitehouse.gov",
"https://www.wsj.com",
"https://washingtonpost.com",
"https://www.foxnews.com",
"https://www.nbc.com",
"https://www.amazon.com",
"https://www.cnn.com",
}
cTask := memoryuser.ChromeTask{URLs: urls, NumTabs: 50}
vmCmd := memoryuser.VMCmd{"dd", "if=/dev/urandom", "of=foo", "bs=3M", "count=1K"}
vmCommands := []memoryuser.VMCmd{vmCmd, vmCmd}
vmTask := memoryuser.VMTask{Cmds: vmCommands}
rp := &memoryuser.RunParameters{
ParallelTasks: true,
}
memTasks := []memoryuser.MemoryTask{&cTask, &vmTask}
if err := memoryuser.RunTest(ctx, s.OutDir(), memTasks, rp); err != nil {
s.Fatal("RunTest failed: ", err)
}
}
|
package altrudos
import "testing"
func TestConfig(t *testing.T) {
c, err := ParseConfig("./config.example.toml")
if err != nil {
t.Fatal(err)
}
if c.JustGiving.Mode != "staging" {
t.Fatal("Expecting mode to be staging")
}
if c.JustGiving.AppId != "some-app-id" {
t.Fatal("Expecting app id to be some-app-id")
}
}
|
package logger
import (
"ekgo/api/boot/config"
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
"github.com/rifflock/lfshook"
"github.com/sirupsen/logrus"
"log"
"os"
"time"
)
var Log = logrus.New()
//日志初始化
func Load(logPath string) *logrus.Logger {
src, err := os.OpenFile(os.DevNull, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
if err != nil {
log.Println("日志启动异常" + err.Error())
}
Log.Out = src
Log.SetLevel(logrus.InfoLevel)
//文件最大保存时间
maximum := config.Get.Log.Maximum
//文件最大保存时间
split := config.Get.Log.Split
logWriter, err := rotatelogs.New(
logPath+"%Y-%m-%d-%H-%M.log",
rotatelogs.WithLinkName(logPath), // 生成软链,指向最新日志文件
rotatelogs.WithMaxAge(time.Duration(maximum)*time.Hour), // 文件最大保存时间
rotatelogs.WithRotationTime(time.Duration(split)*time.Hour), // 日志切割时间间隔
)
writeMap := lfshook.WriterMap{
logrus.InfoLevel: logWriter,
logrus.FatalLevel: logWriter,
}
lfHook := lfshook.NewHook(writeMap, &logrus.JSONFormatter{})
Log.AddHook(lfHook)
return Log
}
|
package keypair
import (
"errors"
"golang.org/x/crypto/ssh"
admissionregv1 "k8s.io/api/admissionregistration/v1"
"k8s.io/apimachinery/pkg/runtime"
"github.com/harvester/harvester/pkg/apis/harvesterhci.io/v1beta1"
ctlharvesterv1 "github.com/harvester/harvester/pkg/generated/controllers/harvesterhci.io/v1beta1"
werror "github.com/harvester/harvester/pkg/webhook/error"
"github.com/harvester/harvester/pkg/webhook/types"
)
const (
fieldPublicKey = "spec.publicKey"
)
func NewValidator(keypairs ctlharvesterv1.KeyPairCache) types.Validator {
return &keyPairValidator{
keypairs: keypairs,
}
}
type keyPairValidator struct {
types.DefaultValidator
keypairs ctlharvesterv1.KeyPairCache
}
func (v *keyPairValidator) Resource() types.Resource {
return types.Resource{
Name: v1beta1.KeyPairResourceName,
Scope: admissionregv1.NamespacedScope,
APIGroup: v1beta1.SchemeGroupVersion.Group,
APIVersion: v1beta1.SchemeGroupVersion.Version,
ObjectType: &v1beta1.KeyPair{},
OperationTypes: []admissionregv1.OperationType{
admissionregv1.Create,
admissionregv1.Update,
},
}
}
func (v *keyPairValidator) Create(request *types.Request, newObj runtime.Object) error {
keypair := newObj.(*v1beta1.KeyPair)
if err := v.checkPublicKey(keypair.Spec.PublicKey); err != nil {
return werror.NewInvalidError(err.Error(), fieldPublicKey)
}
return nil
}
func (v *keyPairValidator) Update(request *types.Request, oldObj runtime.Object, newObj runtime.Object) error {
keypair := newObj.(*v1beta1.KeyPair)
if err := v.checkPublicKey(keypair.Spec.PublicKey); err != nil {
return werror.NewInvalidError(err.Error(), fieldPublicKey)
}
return nil
}
func (v *keyPairValidator) checkPublicKey(publicKey string) error {
if publicKey == "" {
return errors.New("public key is required")
}
if _, _, _, _, err := ssh.ParseAuthorizedKey([]byte(publicKey)); err != nil {
return errors.New("key is not in valid OpenSSH public key format")
}
return nil
}
|
package redlock
import (
"fmt"
"github.com/garyburd/redigo/redis"
"math/rand"
"runtime"
"sync"
"testing"
"time"
)
var locker *Rdm
var addrs []string = []string{
"127.0.0.1:6379",
"127.0.0.1:6377",
"127.0.0.1:6375",
"127.0.0.1:6373",
"127.0.0.1:6371",
}
func newPool(addr string) *redis.Pool {
return &redis.Pool{
MaxIdle: 3000,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", addr, redis.DialDatabase(0))
if err != nil {
return nil, err
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
if time.Since(t) < 5*time.Second {
return nil
}
_, err := c.Do("PING")
return err
},
}
}
func init() {
pools := []*redis.Pool{}
for _, addr := range addrs {
pool := newPool(addr)
pools = append(pools, pool)
}
var err error
locker, err = NewRdm(30*time.Millisecond, 300*time.Millisecond, pools, 10)
if err != nil {
panic(err)
}
runtime.GOMAXPROCS(4)
}
type Client struct {
TimeTook time.Duration
}
func (c *Client) Do() {
time.Sleep(c.TimeTook)
}
func RandClient() *Client {
time_took := time.Millisecond * time.Duration(rand.Int63n(1000))
return &Client{
TimeTook: time_took,
}
}
func TestFunc(t *testing.T) {
cs := make([]*Client, 100)
wg := sync.WaitGroup{}
wg.Add(100)
for i := 0; i < 100; i++ {
cs[i] = RandClient()
}
j := 0
for i := 0; i < 100; i++ {
c := cs[i]
go func(c *Client) {
defer wg.Done()
locked, val := locker.Lock("foo-lock2")
fmt.Printf("locked:%v,val:%s,j:%d\n", locked, val, j)
tmp := j
j = tmp + 1
c.Do()
}(c)
}
wg.Wait()
}
|
package infrastructure
import (
"encoding/json"
"net/http"
)
//Response Response
type Response struct {
Body interface{}
}
//Error Error
type Error struct {
Message string `json:"message"`
}
//StatusOK StatusOK 200
func (r *Response) StatusOK(w http.ResponseWriter, data interface{}) {
r.statusSuccess(w, http.StatusOK, data)
}
//StatusCreated StatusCreated 201
func (r *Response) StatusCreated(w http.ResponseWriter) {
r.statusSuccess(w, http.StatusCreated, nil)
}
//StatusAccepted StatusAccepted 202
func (r *Response) StatusAccepted(w http.ResponseWriter) {
r.statusSuccess(w, http.StatusAccepted, nil)
}
//StatusNoContent StatusNoContent 204
func (r *Response) StatusNoContent(w http.ResponseWriter) {
r.statusSuccess(w, http.StatusNoContent, nil)
}
//StatusBadRequest StatusBadRequest 400
func (r *Response) StatusBadRequest(w http.ResponseWriter, err error) {
r.statusFailure(w, http.StatusBadRequest, err)
}
//StatusInternalServerError StatusInternalServerError 500
func (r *Response) StatusInternalServerError(w http.ResponseWriter, err error) {
r.statusFailure(w, http.StatusInternalServerError, err)
}
func (r *Response) statusSuccess(w http.ResponseWriter, status int, data interface{}) {
r.response(w, status, data)
}
func (r *Response) statusFailure(w http.ResponseWriter, status int, err error) {
r.response(w, status, Error{Message: err.Error()})
}
func (r *Response) response(w http.ResponseWriter, status int, body interface{}) {
r.Body = body
w.Header().Set(`Content-Type`, `application/json`)
w.WriteHeader(status)
w.Write(r.toJSON())
}
//toJSON toJSON
func (r *Response) toJSON() []byte {
b, err := json.Marshal(r.Body)
if err != nil {
return ([]byte)(`{
Message: "JSON Parse error."
}`)
}
return b
}
|
package leetcode
func addDigits0(num int) int {
return (num-1)%9 + 1
}
func addDigits1(num int) int {
if num <= 9 {
return num
}
for num > 9 {
var ans int
for num != 0 {
ans += num % 10
num /= 10
}
num = ans
}
return num
}
func addDigits(num int) int {
if num <= 9 {
return num
}
if num > 9 {
num %= 9
if num == 0 {
return 9
}
}
return num
}
|
// Copyright 2019 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package printer
import (
"context"
"chromiumos/tast/local/bundles/cros/printer/usbprintertests"
"chromiumos/tast/testing"
)
func init() {
testing.AddTest(&testing.Test{
Func: IPPUSBPPDCopiesSupported,
LacrosStatus: testing.LacrosVariantUnneeded,
Desc: "Verifies that the 'copies-supported' attribute of the printer is used to populate the cupsManualCopies and cupsMaxCopies values in the corresponding generated PPD",
Contacts: []string{"bmgordon@chromium.org", "project-bolton@google.com"},
Attr: []string{
"group:mainline",
"group:paper-io",
"paper-io_printing",
},
SoftwareDeps: []string{"chrome", "cros_internal", "cups", "virtual_usb_printer"},
Data: []string{"ippusb_copies_supported.json"},
Fixture: "virtualUsbPrinterModulesLoadedWithChromeLoggedIn",
})
}
// IPPUSBPPDCopiesSupported tests that the "cupsManualCopies" and
// "cupsMaxCopies" PPD fields will be correctly populated when configuring an
// IPP-over-USB printer whose "copies-supported" attribute has an upper limit
// greater than 1 (i.e., it supports copies).
func IPPUSBPPDCopiesSupported(ctx context.Context, s *testing.State) {
usbprintertests.RunIPPUSBPPDTest(ctx, s, s.DataPath("ippusb_copies_supported.json"), map[string]string{
"*cupsManualCopies": "False",
"*cupsMaxCopies": "99",
})
}
|
package cmd
import (
"errors"
"regexp"
"github.com/kronostechnologies/richman/action"
"github.com/spf13/cobra"
)
var appsRunCmd = &cobra.Command{
Use: "run -a APPLICATION",
Short: "run app ops env",
Long: "run app ops env",
Args: func(cmd *cobra.Command, args []string) error {
if len(args) != 0 {
//TODO : Default to current context, allow to append context
return errors.New("too many arguments")
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
app_filters, _ := cmd.Flags().GetString("app")
if app_filters == "" {
return errors.New("please provide an application to run with the -a flag")
}
configArgs, _ := cmd.Flags().GetStringArray("config")
splitRegex := regexp.MustCompile(`^([^=]+)=(.*)$`)
configs := make(map[string]string)
for _, configArg := range configArgs {
split := splitRegex.FindStringSubmatch(configArg)
key := split[1]
value := split[2]
configs[key] = value
}
c := action.AppsRun{
Application: app_filters,
Config: configs,
}
return c.Run()
},
}
func init() {
appsRunCmd.Flags().StringP("app", "a", "", "select app by name")
appsRunCmd.Flags().StringArrayP("config", "c", []string{}, "set config key=value")
}
|
package main
import (
//"bufio"
"fmt"
//"math/rand"
//"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/bwmarrin/discordgo"
)
//RegisterCommands registrates all commands to commandHandler
func RegisterCommands() {
commandHandler.RegisterCommand("best", bestCommand)
commandHandler.RegisterCommand("raffle", newRaffle)
commandHandler.RegisterCommand("enter", addEntry)
commandHandler.RegisterCommand("entries", entries)
commandHandler.RegisterCommand("joinme", joinVoice)
commandHandler.RegisterCommand("hug", hugSend)
commandHandler.RegisterCommand("slap", slapSend)
commandHandler.RegisterCommand("pat", patSend)
commandHandler.RegisterCommand("facepalm", faceSend)
commandHandler.RegisterCommand("role", getRole)
commandHandler.RegisterCommand("addM", addM)
commandHandler.RegisterCommand("getPL", getPL)
}
func bestCommand(m *discordgo.Message) {
message := new(MessageInfo)
message.channelID = m.ChannelID
message.message = m.Author.Username + " is the best!"
commandHandler.SendMessage(message)
}
func joinVoice(m *discordgo.Message) {
message := new(MessageInfo)
message.channelID = m.ChannelID
guild, err := commandHandler.session.Guild("139445313738899456")
if err == nil {
var channel string
for i := 0; i < len(guild.VoiceStates); i++ {
if guild.VoiceStates[i].UserID == m.Author.ID {
channel = guild.VoiceStates[i].ChannelID
}
}
if len(channel) > 0 {
commandHandler.session.ChannelVoiceJoin("139445313738899456", channel, false, false)
message.message = ToMention(m.Author) + " successfully joined your channel."
} else {
message.message = ToMention(m.Author) + " you are currently not in a voice channel."
}
} else {
message.message = "An error occurred while trying to join voice channel."
}
commandHandler.SendMessage(message)
}
func setGuildID(m *discordgo.Message) {
fields := strings.Fields(m.Content)
message := new(MessageInfo)
message.channelID = m.ChannelID
if len(fields) > 0 {
//guildID := fields[1]
//TODO SAVE guildID
message.message = "Guild ID was saved"
} else {
message.message = "Please provide your guild ID"
}
commandHandler.SendMessage(message)
}
func getRole(m *discordgo.Message) { //still expiremental
//member, err := commandHandler.session.State.Member("139695564030869504", m.Author.ID)
//if err != nil {
// fmt.Println(err)
// return
//}
roles, err := commandHandler.session.GuildRoles("139445313738899456") //139445313738899456 TWN
if err != nil {
fmt.Println(err)
return
}
message := new(MessageInfo)
message.channelID = m.ChannelID
message.message = "The roles are "
commandHandler.SendMessage(message)
for index := range roles {
time.Sleep(100 * time.Millisecond)
message := new(MessageInfo)
message.channelID = m.ChannelID
message.message = roles[index].Name
commandHandler.SendMessage(message)
}
}
func getPL(m *discordgo.Message) { // get permission level
permissionLevel := getPermission(m, m.Mentions[0])
//_ = permissionLevel
message := new(MessageInfo)
message.channelID = m.ChannelID
message.message = "The permission level of " + ToMention(m.Mentions[0]) + fmt.Sprintf(" = %v", permissionLevel)
commandHandler.SendMessage(message)
}
func addM(m *discordgo.Message) { // add Member to database
var permission int
permissionRegex, err := regexp.Compile("-p=(\\d+)")
if err == nil {
permissionResult := permissionRegex.FindStringSubmatch(m.Content)
if len(permissionResult) > 0 {
permission, err = strconv.Atoi(permissionResult[1])
if err != nil {
message := new(MessageInfo)
message.channelID = m.ChannelID
message.message = ToMention(m.Author) + ", no permission level is given. Use \"-p=\" to specify"
commandHandler.SendMessage(message)
}
}
}
authorPL := getPermission(m, m.Author)
if authorPL >= permission && authorPL >= 2 {
addMember(m)
} else {
message := new(MessageInfo)
message.channelID = m.ChannelID
message.message = ToMention(m.Author) + ", your permission level is to low. Ask a Nerd, Officer or the Guild leader to change your permission level."
commandHandler.SendMessage(message)
}
return
}
|
package shop
import (
sa "github.com/atymkiv/sa/model"
"github.com/atymkiv/sa/pkg/utl/messages"
"github.com/labstack/echo"
"log"
)
const TOPIC = "shops"
type Service interface {
View(echo.Context, string)(*sa.Shop, error)
ViewAll(echo.Context) ([]sa.Shop, error)
GetAddressByShopId(echo.Context, string) (*sa.Address, error)
}
func New(sdb DB, nats *messages.Service) *Shop {
return &Shop{sdb: sdb, nats:nats}
}
type Shop struct {
sdb DB
nats *messages.Service
}
type DB interface {
View(id string)(*sa.Shop, error)
ViewAll() ([]sa.Shop, error)
GetAddress(id int)(*sa.Address, error)
}
func (s *Shop) View(c echo.Context, id string) (*sa.Shop, error) {
shop, err := s.sdb.View(id)
if err != nil {
return nil, err
}
if err := s.nats.PushMessage(shop, TOPIC); err != nil {
log.Printf("failed pushing user into nuts; err: %v", err)
return nil, err
}
return shop, nil
}
func (s *Shop) ViewAll(c echo.Context) ([]sa.Shop, error) {
shops, err := s.sdb.ViewAll()
if err != nil {
return nil, err
}
return shops, nil
}
func(s *Shop) GetAddressByShopId(ctx echo.Context, id string) (*sa.Address, error) {
shop, err := s.sdb.View(id)
if err != nil{
return nil, err
}
address, err := s.sdb.GetAddress(shop.Address_id)
if err != nil {
return nil, err
}
return address, nil
}
|
package Week_01
func trap(height []int) int {
l := len(height)
lefts := make([]int, l)
rights := make([]int, l)
for i := 1; i < l-1; i++ { // i表示当前的列,求它的左边 的最大的柱子
if height[i-1] > lefts[i-1] {
lefts[i] = height[i-1]
} else {
lefts[i] = lefts[i-1]
}
}
for i := l - 2; i >= 0; i-- { // i表示当前的列,求它的右边 的最大的柱子
if height[i+1] > rights[i+1] {
rights[i] = height[i+1]
} else {
rights[i] = rights[i+1]
}
}
sum := 0
for i := 0; i < l; i++ {
min := lefts[i]
if lefts[i] > rights[i] {
min = rights[i]
}
if min > height[i] {
sum = sum + (min - height[i])
}
}
return sum
}
|
package main
import "fmt"
func main() {
nTask := 5
ch := make(chan int)
for i := 0; i < nTask; i++ {
go doTask(ch, i)
}
for i := 0; i < nTask; i++ {
fmt.Println(<-ch)
}
fmt.Println("run is finished")
}
func doTask(ch chan<- int, data int) {
//do sth
ch <- data
}
|
package metascraper
import (
"reflect"
"testing"
"github.com/twistedogic/spero/pkg/schema/match"
)
func setup() *MetaScraper {
eventURL := "https://lsc.fn.sportradar.com/hkjc/en"
return New(eventURL, 5)
}
func TestMetaScraper_GetMatchDetail(t *testing.T) {
m := setup()
id := 14728777
detail, err := m.GetMatchDetail(id)
if err != nil {
t.Error(err)
}
if reflect.DeepEqual(detail, match.Detail{}) {
t.Fail()
}
}
func TestMetaScraper_GetMatchEvents(t *testing.T) {
m := setup()
id := 14971653
events, err := m.GetMatchEvents(id)
if err != nil {
t.Error(err)
}
if len(events) == 0 {
t.Fail()
}
}
func TestMetaScraper_GetMatchSituations(t *testing.T) {
m := setup()
id := 14971653
situations, err := m.GetMatchSituations(id)
if err != nil {
t.Error(err)
}
if len(situations) == 0 {
t.Fail()
}
}
func TestMetaScraper_GetMatchMeta(t *testing.T) {
m := setup()
id := 14971653
input := match.Match{ID: id}
output, err := m.GetMatchMeta(input)
if err != nil {
t.Error(err)
}
detail := output.Detail
data := output.Match
events := output.Events
situations := output.Situations
switch {
case reflect.DeepEqual(detail, match.Detail{}):
t.Log(detail)
t.Error("empty detail")
case !reflect.DeepEqual(data, input):
t.Error("match not equal to input")
case len(events) == 0:
t.Error("empty events")
case len(situations) == 0:
t.Error("empty situations")
}
}
func TestMetaScraper_GetMatches(t *testing.T) {
m := setup()
offset := -1
matches, err := m.GetMatches(offset)
if err != nil {
t.Error(err)
}
if len(matches) == 0 {
t.Fail()
}
}
|
package main
import "fmt"
func main(){
var a int16 = 26
var out int16 =0
out = a%2 + a/2%2*10 + a/4%2*100 + a/8%2*1000+a/16%2*10000
fmt.Printf("作业一 十进制转二进制:")
fmt.Printf("%d %d \n",a,out)
a=31
out = 0
out = a%8 + a/8%8*10
fmt.Printf("作业二 十进制转八进制:")
fmt.Printf("%d %d \n",a,out)
a=1
out =2
fmt.Printf("作业三 运算符运用:")
fmt.Printf(" a>out=%t a<out=%t a>=out=%t a<=out=%t a==out=%t a!=out=%t \n",a>out,out>a,a>=out,a<=out,a==out,a!=out)
a = 4
var b int16 = 3
res1 := a<b&&b/2==1&&a%3!=0
res2 := (a+b)*3<a<<2||(a-b)>0
fmt.Printf("作业四 a:=4,b:=3求表达式的值:\n")
fmt.Printf("1.res1:=a<b&&b/2==1&&a余3!=0 %t \n",res1)
fmt.Printf("2.res2:=(a+b)*3<a<<2||(a-b)>0 %t \n",res2)
}
// %T 返回对象数据类型 \t 空格 |
func RemoveStringDuplicate(strSlice []string) []string {
if len(strSlice) == 0 {
return strSlice
}
strMap := make(map[string]bool)
for _, d := range strSlice {
strMap[d] = true
}
result := make([]string, len(strMap))
i := 0
for k, _ := range strMap {
result[i] = k
i++
}
return result
}
|
package usecase
import (
"amazonOpenApi/internal/http/gen"
"amazonOpenApi/internal/repository"
"net/http"
"time"
"github.com/labstack/echo/v4"
"gorm.io/gorm"
)
type Amazon struct {
db *gorm.DB
}
func NewAmazon(db *gorm.DB) *Amazon {
return &Amazon{
db: db,
}
}
func (p *Amazon) AddAmazon(ctx echo.Context) error {
// リクエストを取得
amazon := new(gen.Amazon)
err := ctx.Bind(amazon)
if err != nil {
return sendError(ctx, http.StatusBadRequest, "Invalid format")
}
// Create
now := time.Now()
p.db.Create(&repository.AmazonData{
Asin: amazon.Asin,
ProductName: amazon.ProductName,
MakerName: amazon.MakerName,
Price: amazon.Price,
Reason: amazon.Reason,
Url: amazon.Url,
CreatedAt: now,
UpdatedAt: now,
})
return ctx.JSON(http.StatusCreated, amazon)
}
func (p *Amazon) FindAmazonById(ctx echo.Context, asin string) error {
// データを取得
m := new(repository.AmazonData)
if tx := p.db.First(m, "asin = ?", asin); tx.Error != nil {
return sendError(ctx, http.StatusNotFound, tx.Error.Error())
}
amazon := &gen.Amazon{
ProductName: m.ProductName,
MakerName: m.MakerName,
Price: m.Price,
Reason: m.Reason,
Url: m.Url,
Asin: m.Asin,
}
return ctx.JSON(http.StatusOK, amazon)
}
func (p *Amazon) UpdateAmazon(ctx echo.Context, asin string) error {
// リクエストを取得
amazon := new(gen.Amazon)
err := ctx.Bind(amazon)
if err != nil {
return sendError(ctx, http.StatusBadRequest, "Invalid format")
}
// Update
now := time.Now()
p.db.Model(repository.AmazonData{}).
Where("asin = ?", asin).
Updates(repository.AmazonData{
ProductName: amazon.ProductName,
MakerName: amazon.MakerName,
Price: amazon.Price,
Reason: amazon.Reason,
Url: amazon.Url,
Asin: amazon.Asin,
UpdatedAt: now,
})
return ctx.JSON(http.StatusOK, amazon)
}
func (p *Amazon) PatchAmazon(ctx echo.Context, asin string) error {
// リクエストを取得
amazonPatch := new(gen.AmazonPatch)
err := ctx.Bind(amazonPatch)
if err != nil {
return sendError(ctx, http.StatusBadRequest, "Invalid format")
}
m := new(repository.AmazonData)
if tx := p.db.Model(m).First(m, "asin = ?", asin); tx.Error != nil {
return sendError(ctx, http.StatusBadRequest, tx.Error.Error())
}
if amazonPatch.MakerName != nil {
m.MakerName = *amazonPatch.MakerName
}
if amazonPatch.ProductName != nil {
m.ProductName = *amazonPatch.ProductName
}
if amazonPatch.Price != nil {
m.Price = *amazonPatch.Price
}
if amazonPatch.Reason != nil {
m.Reason = *amazonPatch.Reason
}
if amazonPatch.Url != nil {
m.Url = *amazonPatch.Url
}
// Update
m.UpdatedAt = time.Now()
p.db.Model(m).
Where("asin = ?", asin).
Updates(m)
return ctx.JSON(http.StatusOK, gen.Amazon{
ProductName: m.ProductName,
MakerName: m.MakerName,
Price: m.Price,
Reason: m.Reason,
Url: m.Url,
Asin: m.Asin,
})
}
func (p *Amazon) DeleteAmazon(ctx echo.Context, asin string) error {
tx := p.db.Model(repository.AmazonData{}).
Where("asin = ?", asin).
Update("is_delete", repository.DELETE)
if tx.Error != nil {
return sendError(ctx, http.StatusNotFound, tx.Error.Error())
}
return ctx.String(http.StatusNoContent, "")
}
func (p *Amazon) UndeleteAmazon(ctx echo.Context, asin string) error {
tx := p.db.Unscoped().Model(repository.AmazonData{}).
Where("asin = ?", asin).
Update("is_delete", repository.NOT_DELETE)
if tx.Error != nil {
return sendError(ctx, http.StatusNotFound, tx.Error.Error())
}
return ctx.String(http.StatusNoContent, "")
}
|
package main
import "fmt"
func findMedianSortedArrays(nums1 []int, nums2 []int) float64 {
return 0
}
func main() {
nums1 := []int{1, 2}
nums2 := []int{3, 4}
fmt.Println(findMedianSortedArrays(nums1, nums2))
}
|
// Copyright 2020 Comcast Cable Communications Management, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package app
import (
"github.com/gorilla/mux"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/xmidt-org/ears/internal/pkg/jwt"
"github.com/xmidt-org/ears/internal/pkg/rtsemconv"
"github.com/xmidt-org/ears/pkg/logs"
"github.com/xmidt-org/ears/pkg/panics"
"github.com/xmidt-org/ears/pkg/tenant"
"go.opentelemetry.io/contrib/instrumentation/github.com/gorilla/mux/otelmux"
"go.opentelemetry.io/contrib/propagators/b3"
"go.opentelemetry.io/otel/trace"
"net/http"
"regexp"
"strings"
)
var middlewareLogger *zerolog.Logger
var jwtMgr jwt.JWTConsumer
var eventUrlValidator = regexp.MustCompile(`^\/ears\/v1\/orgs\/[a-zA-Z0-9][a-zA-Z0-9_\-]*[a-zA-Z0-9]\/applications\/[a-zA-Z0-9][a-zA-Z0-9_\-]*[a-zA-Z0-9]\/routes\/[a-zA-Z0-9][a-zA-Z0-9_\-\.]*[a-zA-Z0-9]\/event$`)
func NewMiddleware(logger *zerolog.Logger, jwtManager jwt.JWTConsumer) []func(next http.Handler) http.Handler {
middlewareLogger = logger
jwtMgr = jwtManager
otelMiddleware := otelmux.Middleware("ears", otelmux.WithPropagators(b3.New()))
return []func(next http.Handler) http.Handler{
authenticateMiddleware,
otelMiddleware,
initRequestMiddleware,
}
}
func initRequestMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
subCtx := logs.SubLoggerCtx(ctx, middlewareLogger)
defer func() {
p := recover()
if p != nil {
panicErr := panics.ToError(p)
resp := ErrorResponse(&InternalServerError{panicErr})
resp.Respond(subCtx, w, doYaml(r))
log.Ctx(subCtx).Error().Str("op", "initRequestMiddleware").Str("error", panicErr.Error()).
Str("stackTrace", panicErr.StackTrace()).Msg("A panic has occurred")
}
}()
//extract any trace information
traceId := trace.SpanFromContext(subCtx).SpanContext().TraceID().String()
logs.StrToLogCtx(subCtx, rtsemconv.EarsLogTraceIdKey, traceId)
log.Ctx(subCtx).Debug().Msg("initializeRequestMiddleware")
next.ServeHTTP(w, r.WithContext(subCtx))
})
}
func authenticateMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if r.URL.Path == "/ears/version" {
next.ServeHTTP(w, r)
return
}
if strings.HasPrefix(r.URL.Path, "/ears/openapi") {
next.ServeHTTP(w, r)
return
}
var tid *tenant.Id
if strings.HasPrefix(r.URL.Path, "/eel/v1/events") ||
strings.HasPrefix(r.URL.Path, "/ears/v1/events") {
// do not authenticate event API calls here (will be authenticated in API code if needed)
next.ServeHTTP(w, r)
return
} else if strings.HasPrefix(r.URL.Path, "/ears/v1/routes") ||
strings.HasPrefix(r.URL.Path, "/ears/v1/senders") ||
strings.HasPrefix(r.URL.Path, "/ears/v1/receivers") ||
strings.HasPrefix(r.URL.Path, "/ears/v1/filters") ||
strings.HasPrefix(r.URL.Path, "/ears/v1/fragments") ||
strings.HasPrefix(r.URL.Path, "/ears/v1/tenants") {
} else {
var tenantErr ApiError
vars := mux.Vars(r)
tid, tenantErr = getTenant(ctx, vars)
if tenantErr != nil {
log.Ctx(ctx).Error().Str("op", "authenticateMiddleware").Str("error", tenantErr.Error()).Msg("orgId or appId empty")
resp := ErrorResponse(tenantErr)
resp.Respond(ctx, w, doYaml(r))
return
}
// do not authenticate event API calls here (will be authenticated in API code if needed)
if eventUrlValidator.MatchString(r.URL.Path) {
next.ServeHTTP(w, r)
return
}
}
bearerToken := getBearerToken(r)
_, _, authErr := jwtMgr.VerifyToken(ctx, bearerToken, r.URL.Path, r.Method, tid)
if authErr != nil {
log.Ctx(ctx).Error().Str("op", "authenticateMiddleware").Str("error", authErr.Error()).Msg("authorization error")
resp := ErrorResponse(convertToApiError(ctx, authErr))
resp.Respond(ctx, w, doYaml(r))
return
}
next.ServeHTTP(w, r)
})
}
|
package controllers
import (
"html/template"
"net/http"
)
func unit2Rot13(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("templates/rot13.html")
err := t.Execute(w, encodeROT13(r.FormValue("text")))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func encodeROT13(text string) string {
b := []byte(text)
for i := 0; i < len(text); i++ {
b[i] = rot13(b[i])
}
return string(b)
}
func rot13(b byte) byte {
var a, z byte
switch {
case 'a' <= b && b <= 'z':
a, z = 'a', 'z'
case 'A' <= b && b <= 'Z':
a, z = 'A', 'Z'
default:
return b
}
return (b-a+13)%(z-a+1) + a
}
func unit2Signup(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
form := struct {
Username string
Password string
Verify string
Email string
ErrorUsername string
ErrorPassword string
ErrorVerify string
ErrorEmail string
}{
"", "", "", "", "", "", "", "",
}
writeForm(w, form)
}
if r.Method == "POST" {
errorUsername := ""
errorPassword := ""
errorVerify := ""
errorEmail := ""
// Get form field values
username := r.FormValue("username")
password := r.FormValue("password")
verify := r.FormValue("verify")
email := r.FormValue("email")
// Validate form fields
if ! (validUsername(username) && validPassword(password) && (password == verify) && validEmail(email)) {
if !validUsername(username) {
errorUsername = "That's not a valid username"
}
if !validPassword(password) {
errorPassword = "That's not a valid password"
}
if(password != verify) {
errorVerify = "Your passwords didn't match"
}
if !validEmail(email) {
errorEmail = "That's not a valid email"
}
password = ""
verify = ""
form := struct {
Username string
Password string
Verify string
Email string
ErrorUsername string
ErrorPassword string
ErrorVerify string
ErrorEmail string
}{
username,
password,
verify,
email,
errorUsername,
errorPassword,
errorVerify,
errorEmail,
}
writeForm(w, form)
}else {
http.Redirect(w, r, "/unit2/welcome?username="+username, http.StatusFound)
return
}
}
}
func unit2Welcome(w http.ResponseWriter, r *http.Request) {
// get 'username' parameter
parameter := r.FormValue("username")
t, _ := template.ParseFiles("templates/welcome.html")
err := t.Execute(w, parameter)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
|
package main
import (
"bufio"
"flag"
"fmt"
"log"
"os"
"os/exec"
"path"
"strings"
homedir "github.com/mitchellh/go-homedir"
)
const (
RESET = iota
BOLD
)
const (
BLACK = 30 + iota
RED
GREEN
YELLOW
)
var debug = flag.Bool("debug", false, "debug mode")
func DebugLogf(s string, v ...interface{}) {
if *debug {
log.Printf(s, v...)
}
}
func Fatal(e error) {
fmt.Printf("goprompt-err(%s)", e)
os.Exit(1)
}
var collapsablePrefixes = map[string]string{
"~/Code/go/src/": "",
}
func colorCode(codes ...int) string {
ret := "\\[\x1b["
for i, c := range codes {
if i > 0 {
ret += ";"
}
ret += fmt.Sprintf("%d", c)
}
ret += "m\\]"
return ret
}
func main() {
flag.Parse()
var prompt string
cwd, err := os.Getwd()
if err != nil {
Fatal(err)
}
displayPath := cwd
// home prefix
home, err := homedir.Dir()
if err != nil {
Fatal(err)
}
if strings.HasPrefix(displayPath, home) {
displayPath = "~" + strings.TrimPrefix(displayPath, home)
}
// other collapsable prefixes
for k, v := range collapsablePrefixes {
if strings.HasPrefix(displayPath, k) {
displayPath = v + strings.TrimPrefix(displayPath, k)
}
}
prompt += displayPath
// git
isGit := false
ccwd := cwd
for {
if path.Base(ccwd) == ".git" {
DebugLogf("In git dir: %s", ccwd)
prompt += "\x1b[31;1m" // red
prompt += "[GIT DIR!]"
prompt += "\x1b[0m"
break
}
gitPath := path.Join(ccwd, ".git")
DebugLogf("Checking for %s", gitPath)
s, err := os.Stat(gitPath)
if err == nil && s.IsDir() {
isGit = true
DebugLogf("Found git dir: %s", gitPath)
break
}
if ccwd == "/" {
break
}
ccwd = path.Dir(ccwd)
}
if isGit {
cmd := exec.Command("git", "status", "--porcelain", "--branch")
stdout, err := cmd.StdoutPipe()
if err != nil {
Fatal(err)
}
if err := cmd.Start(); err != nil {
Fatal(err)
}
reader := bufio.NewReader(stdout)
branch, err := reader.ReadString('\n')
if err != nil {
Fatal(err)
}
branch = strings.TrimPrefix(branch, "## ")
branch = strings.SplitN(branch, "...", 2)[0]
branch = strings.TrimSpace(branch)
scanner := bufio.NewScanner(reader)
untracked := false
isDirty := false // work tree != index
isPending := false // index != HEAD
for scanner.Scan() {
line := string(scanner.Text())
if strings.HasPrefix(line, "?? ") {
untracked = true
continue
}
if line[0] != ' ' {
isPending = true
}
if line[1] != ' ' {
isDirty = true
}
}
prompt += ":"
switch {
case isPending:
prompt += colorCode(YELLOW, BOLD)
case isDirty, untracked:
prompt += colorCode(RED, BOLD)
case untracked:
prompt += colorCode(RED, BOLD)
default:
prompt += colorCode(GREEN, BOLD)
}
prompt += branch
if untracked {
prompt += "+?"
}
}
// clear formatting for sure so we don't mess up the terminal
prompt += colorCode(RESET)
fmt.Printf("%s", prompt)
}
|
package post_store
const (
/*getPostsOfFollowing = `SELECT posts.username, images.path, posts.name, posts.created_on
FROM followers
INNER JOIN posts ON followers.following=posts.username
INNER JOIN images ON images.id = posts.image_id
WHERE followers.username = $1
ORDER BY posts.created_on DESC;`*/
getPostsOfFollowing = `SELECT posts.username, images.path, posts.name, posts.created_on
FROM posts
INNER JOIN images ON images.id=posts.image_id
WHERE posts.username IN $1
ORDER BY posts.created_on DESC;`
searchPosts = `SELECT posts.name, images.path, posts.username,posts.created_on
FROM posts
INNER JOIN images ON posts.image_id=images.id
WHERE LOWER(posts.name) LIKE LOWER($1);`
getUserPosts = `SELECT posts.name, images.path, posts.username, posts.created_on
FROM posts
INNER JOIN images ON images.id = posts.image_id
WHERE posts.username=$1
ORDER BY posts.created_on DESC;`
)
|
package bolt
import "github.com/boltdb/bolt"
// Truncate the whole database
func (b *Storage) Truncate() error {
db := b.Database
return db.Update(func(tx *bolt.Tx) error {
return tx.ForEach(func(name []byte, b *bolt.Bucket) error {
return tx.DeleteBucket(name)
})
})
}
|
package designBrowser
import (
"fmt"
"io/ioutil"
"net/http"
)
func GetMore(w http.ResponseWriter, r *http.Request, q string) {
url := fmt.Sprintf("http://design-seeds.com/index.php/P%v", q)
resp, err := http.Get(url)
if err != nil || resp.StatusCode != 200 {
return
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
w.Write(body)
}
|
package main
import "fmt"
type Set map[interface{}]bool
func (s *Set) Add(key interface{}) {
(*s)[key] = true
}
func (s *Set) Find(key interface{}) bool {
return (*s)[key]
}
func (s *Set) Remove(key interface{}) {
delete(*s, key)
}
func (s *Set) Size() int {
return len(*s)
}
func main() {
set := make(Set)
set.Add("a")
set.Add("b")
set.Add(1)
fmt.Println(set.Size())
fmt.Println("is 'a' exist?", set.Find("a"))
fmt.Println("is 'c' exist?", set.Find("c"))
fmt.Println("is 'b' exist?", set.Find("b"))
fmt.Println("is 1 exist?", set.Find(1))
}
|
// Copyright 2021 The gVisor 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, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package sandbox
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"strings"
)
// totalSystemMemory extracts "MemTotal" from "/proc/meminfo".
func totalSystemMemory() (uint64, error) {
f, err := os.Open("/proc/meminfo")
if err != nil {
return 0, err
}
defer f.Close()
return parseTotalSystemMemory(f)
}
func parseTotalSystemMemory(r io.Reader) (uint64, error) {
for scanner := bufio.NewScanner(r); scanner.Scan(); {
line := scanner.Text()
totalStr := strings.TrimPrefix(line, "MemTotal:")
if len(totalStr) < len(line) {
fields := strings.Fields(totalStr)
if len(fields) == 0 || len(fields) > 2 {
return 0, fmt.Errorf(`malformed "MemTotal": %q`, line)
}
totalStr = fields[0]
unit := ""
if len(fields) == 2 {
unit = fields[1]
}
mem, err := strconv.ParseUint(totalStr, 10, 64)
if err != nil {
return 0, err
}
switch unit {
case "":
// do nothing.
case "kB":
memKb := mem
mem = memKb * 1024
if mem < memKb {
return 0, fmt.Errorf(`"MemTotal" too large: %d`, memKb)
}
default:
return 0, fmt.Errorf("unknown unit %q: %q", unit, line)
}
return mem, nil
}
}
return 0, fmt.Errorf(`malformed "/proc/meminfo": "MemTotal" not found`)
}
|
package main
import "fmt"
func main(){
fmt.Println("Enter numbers=")
var n,m int
fmt.Scan(&n,&m)
a:=func(num1, num2 int) {
sum:=num1+num2
fmt.Println("addition=",sum)
}
a(n,m)
}
|
package utils
import (
"crypto/tls"
"fmt"
"github.com/parnurzeal/gorequest"
)
// request is a new SuperAgent object with a setting of not verifying
// server's certificate chain and host name.
var request = gorequest.New().TLSClientConfig(&tls.Config{InsecureSkipVerify: true})
func AgentGet() *gorequest.SuperAgent {
return request
}
func Get(targetURL string) {
fmt.Println("==> GET", targetURL)
c, _ := CookieLoad()
request.Get(targetURL).
Set("Cookie", "harbor-lang=zh-cn; beegosessionID="+c).
End(printStatus)
}
func Delete(targetURL string) {
fmt.Println("==> DELETE", targetURL)
c, _ := CookieLoad()
request.Delete(targetURL).
Set("Cookie", "harbor-lang=zh-cn; beegosessionID="+c).
End(printStatus)
}
func Post(targetURL string, body string) {
fmt.Println("==> POST", targetURL)
c, _ := CookieLoad()
request.Post(targetURL).
Set("Cookie", "harbor-lang=zh-cn; beegosessionID="+c).
Send(body).
End(printStatus)
}
func Put(targetURL string, body string) {
fmt.Println("==> PUT", targetURL)
c, _ := CookieLoad()
request.Put(targetURL).
Set("Cookie", "harbor-lang=zh-cn; beegosessionID="+c).
Send(body).
End(printStatus)
}
func Head(targetURL string) {
fmt.Println("==> HEAD", targetURL)
request.Head(targetURL).End(printStatus)
}
// printStatus is a regular simple output callback function.
func printStatus(resp gorequest.Response, body string, errs []error) {
fmt.Println("<== ")
for _, e := range errs {
if e != nil {
fmt.Println(e)
return
}
}
fmt.Println("<== Rsp Status:", resp.Status)
fmt.Printf("<== Rsp Body: %s\n", body)
}
|
package flag
import (
"regexp"
"strings"
)
// StringArray defines a flag that can be invoked multiple times with values accumulated in an array.
// Comma-separated values may be combined in a single flag argument to be separated into the array.
// Extra space(s) around the commas are removed.
type StringArray []string
// String representation of the array of flag values.
func (i *StringArray) String() string {
return "[" + strings.Join(*i, ",") + "]"
}
var commaSplitter = regexp.MustCompile("\\s*,\\s*")
// Set a value(s) into the array.
func (i *StringArray) Set(value string) error {
*i = append(*i, commaSplitter.Split(value, -1)...)
return nil
}
|
package task
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"os"
"strings"
"text/tabwriter"
"golang.org/x/sync/errgroup"
"github.com/go-task/task/v3/internal/editors"
"github.com/go-task/task/v3/internal/fingerprint"
"github.com/go-task/task/v3/internal/logger"
"github.com/go-task/task/v3/internal/sort"
"github.com/go-task/task/v3/taskfile"
)
// ListOptions collects list-related options
type ListOptions struct {
ListOnlyTasksWithDescriptions bool
ListAllTasks bool
FormatTaskListAsJSON bool
}
// NewListOptions creates a new ListOptions instance
func NewListOptions(list, listAll, listAsJson bool) ListOptions {
return ListOptions{
ListOnlyTasksWithDescriptions: list,
ListAllTasks: listAll,
FormatTaskListAsJSON: listAsJson,
}
}
// ShouldListTasks returns true if one of the options to list tasks has been set to true
func (o ListOptions) ShouldListTasks() bool {
return o.ListOnlyTasksWithDescriptions || o.ListAllTasks
}
// Validate validates that the collection of list-related options are in a valid configuration
func (o ListOptions) Validate() error {
if o.ListOnlyTasksWithDescriptions && o.ListAllTasks {
return fmt.Errorf("task: cannot use --list and --list-all at the same time")
}
if o.FormatTaskListAsJSON && !o.ShouldListTasks() {
return fmt.Errorf("task: --json only applies to --list or --list-all")
}
return nil
}
// Filters returns the slice of FilterFunc which filters a list
// of taskfile.Task according to the given ListOptions
func (o ListOptions) Filters() []FilterFunc {
filters := []FilterFunc{FilterOutInternal}
if o.ListOnlyTasksWithDescriptions {
filters = append(filters, FilterOutNoDesc)
}
return filters
}
// ListTasks prints a list of tasks.
// Tasks that match the given filters will be excluded from the list.
// The function returns a boolean indicating whether tasks were found
// and an error if one was encountered while preparing the output.
func (e *Executor) ListTasks(o ListOptions) (bool, error) {
tasks, err := e.GetTaskList(o.Filters()...)
if err != nil {
return false, err
}
if o.FormatTaskListAsJSON {
output, err := e.ToEditorOutput(tasks)
if err != nil {
return false, err
}
encoder := json.NewEncoder(e.Stdout)
encoder.SetIndent("", " ")
if err := encoder.Encode(output); err != nil {
return false, err
}
return len(tasks) > 0, nil
}
if len(tasks) == 0 {
if o.ListOnlyTasksWithDescriptions {
e.Logger.Outf(logger.Yellow, "task: No tasks with description available. Try --list-all to list all tasks\n")
} else if o.ListAllTasks {
e.Logger.Outf(logger.Yellow, "task: No tasks available\n")
}
return false, nil
}
e.Logger.Outf(logger.Default, "task: Available tasks for this project:\n")
// Format in tab-separated columns with a tab stop of 8.
w := tabwriter.NewWriter(e.Stdout, 0, 8, 6, ' ', 0)
for _, task := range tasks {
e.Logger.FOutf(w, logger.Yellow, "* ")
e.Logger.FOutf(w, logger.Green, task.Task)
e.Logger.FOutf(w, logger.Default, ": \t%s", task.Desc)
if len(task.Aliases) > 0 {
e.Logger.FOutf(w, logger.Cyan, "\t(aliases: %s)", strings.Join(task.Aliases, ", "))
}
_, _ = fmt.Fprint(w, "\n")
}
if err := w.Flush(); err != nil {
return false, err
}
return true, nil
}
// ListTaskNames prints only the task names in a Taskfile.
// Only tasks with a non-empty description are printed if allTasks is false.
// Otherwise, all task names are printed.
func (e *Executor) ListTaskNames(allTasks bool) {
// if called from cmd/task.go, e.Taskfile has not yet been parsed
if e.Taskfile == nil {
if err := e.readTaskfile(); err != nil {
log.Fatal(err)
return
}
}
// use stdout if no output defined
var w io.Writer = os.Stdout
if e.Stdout != nil {
w = e.Stdout
}
// Get the list of tasks and sort them
tasks := e.Taskfile.Tasks.Values()
// Sort the tasks
if e.TaskSorter == nil {
e.TaskSorter = &sort.AlphaNumericWithRootTasksFirst{}
}
e.TaskSorter.Sort(tasks)
// Create a list of task names
taskNames := make([]string, 0, e.Taskfile.Tasks.Len())
for _, task := range tasks {
if (allTasks || task.Desc != "") && !task.Internal {
taskNames = append(taskNames, strings.TrimRight(task.Task, ":"))
for _, alias := range task.Aliases {
taskNames = append(taskNames, strings.TrimRight(alias, ":"))
}
}
}
for _, t := range taskNames {
fmt.Fprintln(w, t)
}
}
func (e *Executor) ToEditorOutput(tasks []*taskfile.Task) (*editors.Taskfile, error) {
o := &editors.Taskfile{
Tasks: make([]editors.Task, len(tasks)),
Location: e.Taskfile.Location,
}
var g errgroup.Group
for i := range tasks {
task := tasks[i]
j := i
g.Go(func() error {
// Get the fingerprinting method to use
method := e.Taskfile.Method
if task.Method != "" {
method = task.Method
}
upToDate, err := fingerprint.IsTaskUpToDate(context.Background(), task,
fingerprint.WithMethod(method),
fingerprint.WithTempDir(e.TempDir),
fingerprint.WithDry(e.Dry),
fingerprint.WithLogger(e.Logger),
)
if err != nil {
return err
}
o.Tasks[j] = editors.Task{
Name: task.Name(),
Desc: task.Desc,
Summary: task.Summary,
UpToDate: upToDate,
Location: &editors.Location{
Line: task.Location.Line,
Column: task.Location.Column,
Taskfile: task.Location.Taskfile,
},
}
return nil
})
}
return o, g.Wait()
}
|
package wireguard
import (
"errors"
"net"
"os"
"path/filepath"
"github.com/vishvananda/netlink"
"golang.zx2c4.com/wireguard/device"
"golang.zx2c4.com/wireguard/wgctrl"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
"github.com/utilitywarehouse/semaphore-wireguard/log"
)
// Device is the struct to hold the link device and the wireguard attributes we
// need.
type Device struct {
deviceName string
link netlink.Link
keyFilename string
listenPort int
pubKey string
}
// NewDevice returns a new device struct.
func NewDevice(name string, keyFilename string, mtu, listenPort int) *Device {
if mtu == 0 {
mtu = device.DefaultMTU
}
return &Device{
deviceName: name,
link: &netlink.Wireguard{LinkAttrs: netlink.LinkAttrs{
MTU: mtu,
Name: name,
TxQLen: 1000,
}},
keyFilename: keyFilename,
listenPort: listenPort,
}
}
// Name returns the name of the device.
func (d *Device) Name() string {
return d.deviceName
}
// PublicKey returns the device's wg public key
func (d *Device) PublicKey() string {
return d.pubKey
}
// ListenPort returns the wg listen port
func (d *Device) ListenPort() int {
return d.listenPort
}
// Run creates the wireguard device or sets mtu and txqlen if the device exists.
func (d *Device) Run() error {
h := netlink.Handle{}
defer h.Delete()
l, err := h.LinkByName(d.deviceName)
if err != nil {
log.Logger.Info(
"Could not get wg device by name, will try creating",
"name", d.deviceName,
"err", err,
)
if err := h.LinkAdd(d.link); err != nil {
return err
}
} else {
if err := h.LinkSetMTU(l, d.link.Attrs().MTU); err != nil {
return err
}
if err := h.LinkSetTxQLen(l, d.link.Attrs().TxQLen); err != nil {
return err
}
}
return nil
}
// Configure configures wireguard keys and listen port on the device.
func (d *Device) Configure() error {
wg, err := wgctrl.New()
if err != nil {
return err
}
defer func() {
if err := wg.Close(); err != nil {
log.Logger.Error("Failed to close wireguard client", "err", err)
}
}()
key, err := d.privateKey()
if err != nil {
return err
}
log.Logger.Info(
"Configuring wireguard",
"device", d.deviceName,
"port", d.listenPort,
"pubKey", key.PublicKey(),
)
d.pubKey = key.PublicKey().String()
return wg.ConfigureDevice(d.deviceName, wgtypes.Config{
PrivateKey: &key,
ListenPort: &d.listenPort,
})
}
func (d *Device) privateKey() (wgtypes.Key, error) {
kd, err := os.ReadFile(d.keyFilename)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
log.Logger.Info(
"No key found, generating a new private key",
"path", d.keyFilename,
)
keyDir := filepath.Dir(d.keyFilename)
err := os.MkdirAll(keyDir, 0755)
if err != nil {
log.Logger.Error(
"Unable to create directory=%s",
keyDir,
)
return wgtypes.Key{}, err
}
key, err := wgtypes.GeneratePrivateKey()
if err != nil {
return wgtypes.Key{}, err
}
if err := os.WriteFile(d.keyFilename, []byte(key.String()), 0600); err != nil {
return wgtypes.Key{}, err
}
return key, nil
}
return wgtypes.Key{}, err
}
return wgtypes.ParseKey(string(kd))
}
// UpdateAddress will patch the device interface so it is assigned only the
// given address.
func (d *Device) UpdateAddress(address *net.IPNet) error {
h := netlink.Handle{}
defer h.Delete()
link, err := h.LinkByName(d.deviceName)
if err != nil {
return err
}
d.FlushAddresses()
if err := h.AddrAdd(link, &netlink.Addr{IPNet: address}); err != nil {
return err
}
return nil
}
// FlushAddresses deletes all ips from the device network interface
func (d *Device) FlushAddresses() error {
h := netlink.Handle{}
defer h.Delete()
link, err := h.LinkByName(d.deviceName)
if err != nil {
return err
}
ips, err := h.AddrList(link, 2)
for _, ip := range ips {
if err := h.AddrDel(link, &ip); err != nil {
return err
}
}
return nil
}
// EnsureLinkUp brings up the wireguard device.
func (d *Device) EnsureLinkUp() error {
h := netlink.Handle{}
defer h.Delete()
link, err := h.LinkByName(d.deviceName)
if err != nil {
return err
}
return h.LinkSetUp(link)
}
// AddRouteToNet adds a route to the passed subnet via the device
func (d *Device) AddRouteToNet(subnet *net.IPNet) error {
h := netlink.Handle{}
defer h.Delete()
link, err := h.LinkByName(d.deviceName)
if err != nil {
return err
}
return h.RouteReplace(&netlink.Route{
LinkIndex: link.Attrs().Index,
Dst: subnet,
Scope: netlink.SCOPE_LINK,
})
}
|
package strategies
import (
"fmt"
"github.com/matang28/reshape/reshape"
"time"
)
func tick() {
time.Sleep(100 * time.Millisecond)
}
func predefinedSource(ch chan interface{}, elements ...interface{}) {
defer func() {
recover()
}()
for _, e := range elements {
ch <- e
}
}
func delayedSource(ch chan interface{}, delay time.Duration, elements ...interface{}) {
defer func() {
recover()
}()
go func() {
for _, e := range elements {
ch <- e
time.Sleep(delay)
}
}()
}
var badTrans reshape.Transformation = func(in interface{}) (out interface{}, err error) {
return nil, fmt.Errorf("")
}
var plusOneTrans = func(in interface{}) (out interface{}, err error) {
out = in.(int) + 1
return out, nil
}
var dropEvens = func(in interface{}) bool {
return in.(int)%2 != 0
}
type badSink struct {
}
func (this *badSink) Dump(object ...interface{}) error {
return fmt.Errorf("")
}
func (this *badSink) Close() error {
return fmt.Errorf("")
}
|
package handler
import (
"path/filepath"
"strings"
"time"
"github.com/futurehomeno/fimpgo/edgeapp"
"github.com/futurehomeno/fimpgo/utils"
"github.com/futurehomeno/fimpgo"
scribble "github.com/nanobox-io/golang-scribble"
log "github.com/sirupsen/logrus"
"github.com/tskaard/sensibo/model"
"github.com/tskaard/sensibo/sensibo-api"
)
// FimpSensiboHandler structure
type FimpSensiboHandler struct {
inboundMsgCh fimpgo.MessageCh
mqt *fimpgo.MqttTransport
api *sensibo.Sensibo
db *scribble.Driver
state model.State
ticker *time.Ticker
configs model.Configs
appLifecycle *edgeapp.Lifecycle
env string
}
// NewFimpSensiboHandler construct new handler
func NewFimpSensiboHandler(transport *fimpgo.MqttTransport, stateFile string, appLifecycle *edgeapp.Lifecycle) *FimpSensiboHandler {
fc := &FimpSensiboHandler{inboundMsgCh: make(fimpgo.MessageCh, 5), mqt: transport, appLifecycle: appLifecycle}
fc.mqt.RegisterChannel("ch1", fc.inboundMsgCh)
hubInfo, err := utils.NewHubUtils().GetHubInfo()
if err == nil && hubInfo != nil {
fc.env = hubInfo.Environment
} else {
fc.env = utils.EnvProd
}
fc.api = sensibo.NewSensibo("")
fc.db, _ = scribble.New(stateFile, nil)
fc.state = model.State{}
return fc
}
// Start start handler
func (fc *FimpSensiboHandler) Start(pollTimeSec int) error {
if err := fc.db.Read("data", "state", &fc.state); err != nil {
log.Error("Error loading state from file: ", err)
fc.state.Connected = false
log.Info("setting state connected to false")
if err = fc.db.Write("data", "state", fc.state); err != nil {
log.Error("Did not manage to write to file: ", err)
}
}
fc.api.Key = fc.state.APIkey
var errr error
go func(msgChan fimpgo.MessageCh) {
for {
select {
case newMsg := <-msgChan:
fc.routeFimpMessage(newMsg)
}
}
}(fc.inboundMsgCh)
// Setting up ticker to poll information from cloud
fc.ticker = time.NewTicker(time.Second * time.Duration(pollTimeSec))
go func() {
for range fc.ticker.C {
// Check if app is connected
if fc.state.Connected {
log.Debug("")
log.Debug("------------------TICKER START-------------------")
pods, err := fc.api.GetPodsV1(fc.api.Key) // Update on all ticks
log.Debug("oldtemp after getpods: ", fc.state.Pods[0].OldTemp)
if err != nil {
log.Error("Can't get pods in tick")
}
oldPods := fc.state.Pods
fc.state.Pods = pods
for i, p := range fc.state.Pods {
pod := p
log.Debug("")
log.Debug("pod.ID: ", pod.ID)
if pod.MainMeasurementSensor.IsMainSensor {
log.Debug("Sensor: external")
temp := pod.MainMeasurementSensor.Measurements.Temperature
humid := pod.MainMeasurementSensor.Measurements.Humidity
motion := pod.MainMeasurementSensor.Measurements.Motion
if oldPods[i].ExtOldTemp != temp {
log.Debug("ext sensor temperature: ", temp)
log.Debug("extoldTemp, ", oldPods[i].ExtOldTemp)
fc.sendTemperatureMsg(pod.ID, temp, nil, 1)
}
fc.state.Pods[i].ExtOldTemp = temp
if oldPods[i].ExtOldHumid != float64(humid) {
log.Debug("ext sensor humidity: ", humid)
log.Debug("extoldHumid, ", oldPods[i].ExtOldHumid)
fc.sendHumidityMsg(pod.ID, float64(humid), nil, 1)
}
fc.state.Pods[i].ExtOldHumid = float64(humid)
if oldPods[i].ExtOldMotion != motion {
log.Debug("ext sensor motion: ", motion)
log.Debug("extoldMotion, ", oldPods[i].ExtOldMotion)
fc.SendMotionMsg(pod.ID, motion, nil)
}
fc.state.Pods[i].ExtOldMotion = motion
}
log.Debug("Sensor: internal")
measurements, err := fc.api.GetMeasurements(pod.ID, fc.api.Key)
if err != nil {
log.Error("Cannot get measurements from internal device")
continue
}
temp := measurements[0].Temperature
if oldPods[i].OldTemp != temp {
log.Debug("temp, ", temp)
log.Debug("oldTemp, ", oldPods[i].OldTemp)
fc.sendTemperatureMsg(pod.ID, temp, nil, 0)
}
fc.state.Pods[i].OldTemp = temp
humid := measurements[0].Humidity
if oldPods[i].OldHumid != humid {
log.Debug("humid, ", humid)
log.Debug("oldHumid, ", oldPods[i].OldHumid)
fc.sendHumidityMsg(pod.ID, humid, nil, 0)
}
fc.state.Pods[i].OldHumid = humid
states, err := fc.api.GetAcStates(pod.ID, fc.api.Key)
if err != nil {
log.Error("Faild to get current acState: ", err)
continue
}
if len(states) > 0 {
state := states[0].AcState
if oldPods[i].OldState != state {
log.Debug("state, ", state)
log.Debug("oldState, ", oldPods[i].OldState)
fc.sendAcState(pod.ID, state, nil, 0)
}
fc.state.Pods[i].OldState = state
} else {
log.Error("GetAcStates return empty results.")
}
}
} else {
log.Debug("------- NOT CONNECTED -------")
// Do nothing
}
}
}()
return errr
}
func (fc *FimpSensiboHandler) routeFimpMessage(newMsg *fimpgo.Message) {
// configs := model.Configs{}
log.Debug("New fimp msg")
if fc.state.IsConfigured() {
fc.appLifecycle.SetConnectionState(edgeapp.ConnStateConnected)
fc.appLifecycle.SetConfigState(edgeapp.ConfigStateConfigured)
}
switch newMsg.Payload.Type {
case "cmd.auth.set_tokens":
err := newMsg.Payload.GetObjectValue(&fc.state)
fc.appLifecycle.SetAuthState(edgeapp.AuthStateInProgress)
if err != nil {
log.Error("Wrong payload type , expected Object")
fc.appLifecycle.SetAuthState(edgeapp.AuthStateNotAuthenticated)
return
}
fc.systemConnect(newMsg)
fc.getAuthStatus(newMsg)
fc.configs.SaveToFile()
fc.state.SaveToFile()
case "cmd.system.disconnect":
fc.systemDisconnect(newMsg)
fc.state.SaveToFile()
case "cmd.auth.logout":
fc.systemDisconnect(newMsg)
fc.state.SaveToFile()
case "cmd.app.uninstall":
fc.systemDisconnect(newMsg)
fc.state.SaveToFile()
case "cmd.config.extended_set":
err := newMsg.Payload.GetObjectValue(&fc.state)
if err != nil {
log.Debug("Can't get object value")
}
fanMode := fc.state.FanMode
mode := fc.state.Mode
fc.state.SaveToFile()
for i := 0; i < len(fc.state.Pods); i++ {
podID := fc.state.Pods[i].ID
log.Debug(podID)
adr, _ := fimpgo.NewAddressFromString("pt:j1/mt:cmd/rt:dev/rn:sensibo/ad:1/sv:fan_ctrl/ad:" + podID)
msg := fimpgo.NewMessage("cmd.mode.set", "fan_ctrl", fimpgo.VTypeString, fanMode, nil, nil, newMsg.Payload)
fc.mqt.Publish(adr, msg)
adr, _ = fimpgo.NewAddressFromString("pt:j1/mt:cmd/rt:dev/rn:sensibo/ad:1/sv:thermostat/ad:" + podID)
msg = fimpgo.NewMessage("cmd.mode.set", "thermostat", fimpgo.VTypeString, mode, nil, nil, newMsg.Payload)
fc.mqt.Publish(adr, msg)
}
configReport := model.ConfigReport{
OpStatus: "ok",
AppState: *fc.appLifecycle.GetAllStates(),
}
msg := fimpgo.NewMessage("evt.app.config_report", model.ServiceName, fimpgo.VTypeObject, configReport, nil, nil, newMsg.Payload)
msg.Source = "sensibo"
if err := fc.mqt.RespondToRequest(newMsg.Payload, msg); err != nil {
log.Debug("cant respond to wanted topic")
}
case "cmd.system.get_connect_params":
fc.systemGetConnectionParameter(newMsg)
case "cmd.system.connect":
fc.systemConnect(newMsg)
fc.state.SaveToFile()
case "cmd.system.sync":
var val model.ButtonActionResponse
if fc.systemSync(newMsg) {
val = model.ButtonActionResponse{
Operation: "cmd.system.sync",
OperationStatus: "ok",
Next: "reload",
ErrorCode: "",
ErrorText: "",
}
log.Info("All devices synced")
} else {
val = model.ButtonActionResponse{
Operation: "cmd.system.sync",
OperationStatus: "err",
Next: "reload",
ErrorCode: "",
ErrorText: "Sensibo is not connected",
}
}
msg := fimpgo.NewMessage("evt.app.config_action_report", model.ServiceName, fimpgo.VTypeObject, val, nil, nil, newMsg.Payload)
if err := fc.mqt.RespondToRequest(newMsg.Payload, msg); err != nil {
log.Error("Could not respond to wanted request")
}
case "cmd.setpoint.set":
fc.setpointSet(newMsg)
case "cmd.setpoint.get_report":
fc.setpointGetReport(newMsg)
case "cmd.mode.set":
fc.modeSet(newMsg)
case "cmd.mode.get_report":
fc.modeGetReport(newMsg)
case "cmd.thing.get_inclusion_report":
fc.sendSingleInclusionReport(newMsg)
//case "cmd.state.get_report":
case "cmd.app.get_manifest":
mode, err := newMsg.Payload.GetStringValue()
if err != nil {
log.Error("Incorrect request format ")
return
}
manifest := edgeapp.NewManifest()
err = manifest.LoadFromFile(filepath.Join(fc.configs.GetDefaultDir(), "app-manifest.json"))
if err != nil {
log.Error("Failed to load manifest file .Error :", err.Error())
return
}
if mode == "manifest_state" {
manifest.AppState = *fc.appLifecycle.GetAllStates()
fc.configs.ConnectionState = string(fc.appLifecycle.ConnectionState())
fc.configs.Errors = fc.appLifecycle.LastError()
manifest.ConfigState = fc.state
}
if errConf := manifest.GetAppConfig("errors"); errConf != nil {
if fc.configs.Errors == "" {
errConf.Hidden = true
} else {
errConf.Hidden = false
}
}
fanConfig := manifest.GetAppConfig("fan_ctrl")
modeConfig := manifest.GetAppConfig("mode")
fanConfig.Val.Default = fc.state.FanMode
modeConfig.Val.Default = fc.state.Mode
fanCtrlBlock := manifest.GetUIBlock("fan_ctrl")
modeBlock := manifest.GetUIBlock("mode")
syncButton := manifest.GetButton("sync")
if fc.appLifecycle.ConnectionState() == edgeapp.ConnStateConnected {
fanCtrlBlock.Hidden = false
modeBlock.Hidden = false
syncButton.Hidden = false
} else {
fanCtrlBlock.Hidden = true
modeBlock.Hidden = true
syncButton.Hidden = true
}
if fc.env == utils.EnvBeta {
manifest.Auth.AuthEndpoint = "https://partners-beta.futurehome.io/api/edge/proxy/custom/auth-code"
manifest.Auth.RedirectURL = "https://app-static-beta.futurehome.io/playground_oauth_callback"
} else {
manifest.Auth.AuthEndpoint = "https://partners.futurehome.io/api/edge/proxy/custom/auth-code"
manifest.Auth.RedirectURL = "https://app-static.futurehome.io/playground_oauth_callback"
}
msg := fimpgo.NewMessage("evt.app.manifest_report", "sensibo", fimpgo.VTypeObject, manifest, nil, nil, newMsg.Payload)
msg.Source = "sensibo"
adr := &fimpgo.Address{MsgType: "rsp", ResourceType: "cloud", ResourceName: "remote-client", ResourceAddress: "smarthome-app"}
if fc.mqt.RespondToRequest(newMsg.Payload, msg); err != nil {
fc.mqt.Publish(adr, msg)
}
case "cmd.sensor.get_report":
log.Debug("cmd.sensor.get_report")
if !(newMsg.Payload.Service == "sensor_temp" || newMsg.Payload.Service == "sensor_humid") {
log.Error("sensor.get_report - Wrong service")
break
}
log.Debug("Getting measurements")
address := strings.Replace(newMsg.Addr.ServiceAddress, "_0", "", 1)
address = strings.Replace(address, "_1", "", 1)
// address := newMsg.Addr.ServiceAddress
measurements, err := fc.api.GetMeasurements(address, fc.api.Key)
if err != nil {
log.Error("Cannot get measurements from device")
break
}
fc.state.Pods, err = fc.api.GetPodsV1(fc.api.Key)
if err != nil {
log.Error("Cannot get pods")
break
}
var podNr int
for i, p := range fc.state.Pods {
pod := p
if pod.ID == address {
podNr = i
}
}
switch newMsg.Payload.Service {
case "sensor_temp":
log.Debug("Getting temperature")
temp := measurements[0].Temperature
fc.sendTemperatureMsg(address, temp, newMsg.Payload, 0)
if fc.state.Pods[podNr].MainMeasurementSensor.UID != "" {
extTemp := fc.state.Pods[podNr].MainMeasurementSensor.Measurements.Temperature
fc.sendTemperatureMsg(address, extTemp, newMsg.Payload, 1)
}
case "sensor_humid":
log.Debug("Getting humidity")
humid := measurements[0].Humidity
fc.sendHumidityMsg(address, humid, newMsg.Payload, 0)
if fc.state.Pods[podNr].MainMeasurementSensor.UID != "" {
extHumid := fc.state.Pods[podNr].MainMeasurementSensor.Measurements.Humidity
fc.sendHumidityMsg(address, float64(extHumid), newMsg.Payload, 1)
}
case "sensor_presence":
log.Debug("Getting presence")
extMotion := fc.state.Pods[podNr].MainMeasurementSensor.Measurements.Motion
fc.SendMotionMsg(address, extMotion, newMsg.Payload)
}
case "cmd.thing.delete":
// remove device from network
val, err := newMsg.Payload.GetStrMapValue()
if err != nil {
log.Error("Wrong msg format")
return
}
deviceID := val["address"]
exists := 9999
for i := 0; i < len(fc.state.Pods); i++ {
podID := fc.state.Pods[i].ID
if deviceID == podID {
exists = i
}
}
if exists != 9999 {
fc.sendExclusionReport(deviceID, newMsg.Payload)
}
}
fc.state.SaveToFile()
fc.configs.SaveToFile()
}
|
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
arguments := os.Args[1:]
if len(arguments) == 0 {
fmt.Println("usage: main.exe <percent_1> <percent_2>...")
fmt.Println("ie main.exe 60")
return
}
for _, value := range arguments {
input, fail := strconv.ParseFloat(value, 10)
if fail != nil {
fmt.Printf("invalid input %s", value)
} else {
fraction := toFraction(input)
result := toHex(fraction)
fmt.Printf("result for %.1f is %s\n", input, result)
}
}
}
func toFraction(percent float64) float64 {
if percent < 0 {
return -1
}
result := 2.5 * percent
return result
}
func toHex(fraction float64) string {
i := int(fraction)
return fmt.Sprintf("%x", i)
}
|
package main
import (
"fmt"
)
func spiralOrder(matrix [][]int) []int {
if len(matrix) == 0 {
return []int{}
}
d := [][]int{
{0, 1},
{1, 0},
{0, -1},
{-1, 0},
}
row := len(matrix)
col := len(matrix[0])
border := []int{col, row, 0, 0}
borderOp := []int{-1, -1, 1, 1}
ans := make([]int, row*col)
now := 0
x := 0
y := 0
k := 0
for {
ans[now] = matrix[x][y]
now = now + 1
if now == len(ans) {
break
}
for {
nx := x + d[k][0]
ny := y + d[k][1]
if k == 0 || k == 2 {
if ny < border[0] && ny >= border[2] {
x = nx
y = ny
break
}
} else {
if nx < border[1] && nx >= border[3] {
x = nx
y = ny
break
}
}
border[(k+3)%4] = border[(k+3)%4] + borderOp[(k+3)%4]
k = (k + 1) % 4
}
// for i := 0
}
return ans
}
func main() {
input := [][]int{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
}
fmt.Println(spiralOrder(input))
}
|
package ffmpeg
//#include <libavutil/avutil.h>
import "C"
const (
MediaTypeUnknown = MediaType(C.AVMEDIA_TYPE_UNKNOWN)
MediaTypeVideo = MediaType(C.AVMEDIA_TYPE_VIDEO)
MediaTypeAudio = MediaType(C.AVMEDIA_TYPE_AUDIO)
MediaTypeData = MediaType(C.AVMEDIA_TYPE_DATA)
MediaTypeSubtitle = MediaType(C.AVMEDIA_TYPE_SUBTITLE)
MediaTypeAttachment = MediaType(C.AVMEDIA_TYPE_ATTACHMENT)
MediaTypeNB = MediaType(C.AVMEDIA_TYPE_NB)
)
type MediaType int
func (mt MediaType) ctype() C.enum_AVMediaType {
return (C.enum_AVMediaType)(mt)
}
|
// This file is part of CycloneDX GoMod
//
// Licensed under the Apache License, Version 2.0 (the “License”);
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an “AS IS” BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) OWASP Foundation. All Rights Reserved.
package gomod
import (
"testing"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/stretchr/testify/require"
)
func TestGetLatestTag(t *testing.T) {
repo, err := git.PlainClone(t.TempDir(), false, &git.CloneOptions{
URL: "https://github.com/CycloneDX/cyclonedx-go.git",
})
require.NoError(t, err)
headCommit, err := repo.CommitObject(plumbing.NewHash("a20be9f00d406e7b792973ee1826e637e58a23d7"))
require.NoError(t, err)
tag, err := GetLatestTag(repo, headCommit)
require.NoError(t, err)
require.NotNil(t, tag)
require.Equal(t, "v0.3.0", tag.name)
require.Equal(t, "a20be9f00d406e7b792973ee1826e637e58a23d7", tag.commit.Hash.String())
}
|
package alldebrid
import (
"encoding/json"
"errors"
"fmt"
"net/http"
)
//Domains is the domains response struct
type Domains struct {
Status string `json:"status"`
Data domainsData `json:"data,omitempty"`
Error alldebridError `json:"error,omitempty"`
}
type domainsData struct {
Hosts []string `json:"hosts"`
Streams []string `json:"streams"`
Redirectors []string `json:"redirectors"`
}
//GetDomainsOnly returns list of supported hosts domains and redirectors
func (c *Client) GetDomainsOnly() (Domains, error) {
resp, err := http.Get(fmt.Sprintf(hostsdomains, getHostsEndpoint(), c.ic.appName))
if err != nil {
return Domains{}, err
}
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
var doms Domains
err = decoder.Decode(&doms)
if err != nil {
return Domains{}, err
}
if doms.Status != "success" {
return Domains{}, errors.New(doms.Error.Message)
}
return doms, nil
}
|
package eoy
import (
"encoding/json"
"fmt"
"log"
"os"
"strings"
"time"
"github.com/360EntSecGroup-Skylar/excelize"
"github.com/jinzhu/gorm"
goengage "github.com/salsalabs/goengage/pkg"
)
const (
//DefaultColumnWidth is the Excel size for a column that contains numbers.
DefaultColumnWidth = 14.0
//ActivityFormWidth is the Excel size for form names.
ActivityFormWidth = 60.0
)
//Runtime contains the variables that we need to run this application.
type Runtime struct {
Env *goengage.Environment
DB *gorm.DB
Log *log.Logger
Channels []chan goengage.Fundraise
Spreadsheet *excelize.File
CountStyle int
ValueStyle int
KeyStyle int
TitleStyle int
HeaderStyle int
StatHeaderStyle int
TopDonorLimit int
Year int
YearStart time.Time
YearEnd time.Time
OrgLocation *time.Location
}
//KeyValuer returns a key value for the specified offset.
type KeyValuer interface {
KeyValue(i int) interface{}
}
//KeyFiller inserts stats objects into an Excel spreadsheet starting at the
//specified zero-based row.
type KeyFiller interface {
FillKeys(rt *Runtime, sheet Sheet, row, col int) int
}
//Filler inserts stats objects into an Excel spreadsheet starting at the
//specified zero-based row and column.
type Filler interface {
Fill(rt *Runtime, sheet Sheet, row, col int) int
}
//Sheet contains the stuff that we need to create and populate a sheet
//in the EOY spreadsheet.
type Sheet struct {
Name string
Titles []string
KeyNames []string
KeyStyles []int
Filler Filler
KeyFiller KeyFiller
}
//font contains the font definition for a style.
type font struct {
Bold bool `json:"bold,omitempty"`
Italic bool `json:"italic,omitempty"`
Family string `json:"family,omitempty"`
Size int `json:"size,omitempty"`
Color string `json:"color,omitempty"`
}
//alignment contains alignment definitions for a style.
type alignment struct {
Horizontal string `json:"horizontal,omitempty"`
ShrinkToFit bool `json:"shrink_to_fit,omitempty"`
}
//style contains style declarations, ready to marshall into JSON.
type style struct {
NumberFormat int `json:"number_format,omitempty"`
Font font `json:"font"`
Alignment alignment `json:"alignment"`
}
//Axis accepts zero-based row and column and returns an Excel location.
//Note: Column offset is limited to the range of columns for this app --
//one alpha digit.
func Axis(r, c int) string {
cols := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
s := string(cols[c])
return fmt.Sprintf("%v%v", s, r+1)
}
//Headers decorates the data headers for a spreadsheet.
func (rt *Runtime) Headers(sheet Sheet, row int) int {
rt.Spreadsheet.InsertRow(sheet.Name, row+1)
//Key headers are followed by stat headers on a single row.
for i, t := range sheet.KeyNames {
s := sheet.KeyStyles[i]
rt.Cell(sheet.Name, row, i, t, s)
}
stat := Stat{}
for i := int(AllCount); i < int(StatFieldCount); i++ {
//"-1" because we are skipping ID
col := len(sheet.KeyNames) + i - 1
h := stat.Header(i)
s := stat.Style(rt, i)
rt.Cell(sheet.Name, row, col, h, s)
}
row++
return row
}
//StatHeaders show the topics for stats. Most of the headers
//will be two columns to cover count and amount.
func (rt *Runtime) StatHeaders(sheet Sheet, row int) int {
rt.Spreadsheet.InsertRow(sheet.Name, row+1)
s := Stat{}
s.Headers(rt, sheet.Name, row, len(sheet.KeyNames))
row++
return row
}
//StyleInt converts a style for use in an Excelize spreadsheet.
func (rt *Runtime) StyleInt(s style) int {
b, err := json.Marshal(s)
if err != nil {
log.Panic(err)
}
x, _ := rt.Spreadsheet.NewStyle(string(b))
if err != nil {
log.Panic(err)
}
return x
}
//Titles inserts titles into a sheet and decorates them.
func (rt *Runtime) Titles(sheet Sheet) (row int) {
//Titles go on separate lines
for row, t := range sheet.Titles {
rt.Spreadsheet.InsertRow(sheet.Name, row+1)
rt.Cell(sheet.Name, row, 0, t, rt.TitleStyle)
// Merge cells and put the title in the middle.
// Sorry, "2" is a magic number for now...
w := len(sheet.KeyNames) + int(StatFieldCount) - 2
left := Axis(row, 0)
right := Axis(row, w)
err := rt.Spreadsheet.MergeCell(sheet.Name, left, right)
if err != nil {
panic(err)
}
}
row++
return row
}
//Widths sets the widths in a sheet.
func (rt *Runtime) Widths(sheet Sheet, row int) int {
left := Axis(row, 0)
left = left[0:1]
// Sorry, "2" is a magic number for now...
w := len(sheet.KeyNames) + int(StatFieldCount) - 2
right := Axis(row, w)
right = right[0:1]
err := rt.Spreadsheet.SetColWidth(sheet.Name, left, right, DefaultColumnWidth)
if err != nil {
panic(err)
}
//Kludge! Activity form names are a lot longer than supporter names.
if strings.Contains(sheet.Name, "Activity") {
_ = rt.Spreadsheet.SetColWidth(sheet.Name, "A", "A", ActivityFormWidth)
}
return row
}
//Decorate a sheet by putting it into the spreadsheet as an Excel sheet.
func (rt *Runtime) Decorate(sheet Sheet) (row int) {
_ = rt.Spreadsheet.NewSheet(sheet.Name)
row = rt.Titles(sheet)
row = rt.StatHeaders(sheet, row)
row = rt.Headers(sheet, row)
row = sheet.Filler.Fill(rt, sheet, row, 0)
row = rt.Widths(sheet, row)
return row
}
//NewRuntime creates a runtime object and initializes the rt.
func NewRuntime(e *goengage.Environment, db *gorm.DB, channels []chan goengage.Fundraise, year int, topLimit int, loc string) *Runtime {
w, err := os.Create("eoy.log")
if err != nil {
log.Panic(err)
}
yearStart := time.Date(year, time.Month(1), 1, 0, 0, 0, 0, time.UTC)
yearEnd := time.Date(year, time.Month(12), 31, 23, 59, 59, 999, time.UTC)
orgLocation, err := time.LoadLocation(loc)
rt := Runtime{
Env: e,
DB: db,
Log: log.New(w, "EOY: ", log.LstdFlags),
Channels: channels,
Spreadsheet: excelize.NewFile(),
Year: year,
TopDonorLimit: topLimit,
YearStart: yearStart,
YearEnd: yearEnd,
OrgLocation: orgLocation,
}
f := font{Size: 12}
s := style{
NumberFormat: 3,
Font: f,
}
rt.CountStyle = rt.StyleInt(s)
s = style{
NumberFormat: 3,
Font: f,
}
rt.ValueStyle = rt.StyleInt(s)
s = style{
NumberFormat: 0,
Font: f,
}
rt.KeyStyle = rt.StyleInt(s)
a := alignment{Horizontal: "center"}
s = style{
NumberFormat: 0,
Font: f,
Alignment: a,
}
rt.HeaderStyle = rt.StyleInt(s)
f2 := font{Size: 16, Bold: true}
s = style{
NumberFormat: 0,
Font: f2,
Alignment: a,
}
rt.TitleStyle = rt.StyleInt(s)
return &rt
}
//Cell stores a value in an Excel cell and sets its style.
func (rt *Runtime) Cell(sheetName string, row, col int, v interface{}, s int) {
a := Axis(row, col)
rt.Spreadsheet.SetCellValue(sheetName, a, v)
rt.Spreadsheet.SetCellStyle(sheetName, a, a, s)
}
//GoodYear returns true if the specified time is between Runtime.YearStart and Runtime.YearEnd.
func (rt *Runtime) GoodYear(t *time.Time) bool {
if t.Before(rt.YearStart) || t.After(rt.YearEnd) {
return false
}
return true
}
|
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package aliyun
import (
"fmt"
"regexp"
"strconv"
"strings"
"time"
"yunion.io/x/jsonutils"
"yunion.io/x/log"
"yunion.io/x/pkg/errors"
"yunion.io/x/pkg/utils"
api "yunion.io/x/onecloud/pkg/apis/compute"
"yunion.io/x/onecloud/pkg/cloudprovider"
"yunion.io/x/onecloud/pkg/multicloud"
)
type SMongoDB struct {
region *SRegion
multicloud.AliyunTags
multicloud.SBillingBase
multicloud.SResourceBase
ChargeType TChargeType `json:"ChargeType"`
LockMode string `json:"LockMode"`
DBInstanceClass string `json:"DBInstanceClass"`
ResourceGroupId string `json:"ResourceGroupId"`
DBInstanceId string `json:"DBInstanceId"`
ZoneId string `json:"ZoneId"`
MongosList struct {
MongosAttribute []struct {
NodeId string `json:"NodeId"`
NodeClass string `json:"NodeClass"`
} `json:"MongosAttribute"`
} `json:"MongosList"`
DBInstanceDescription string `json:"DBInstanceDescription"`
Engine string `json:"Engine"`
CreationTime time.Time `json:"CreationTime"`
NetworkType string `json:"NetworkType"`
ExpireTime time.Time `json:"ExpireTime"`
DBInstanceType string `json:"DBInstanceType"`
RegionId string `json:"RegionId"`
ShardList struct {
ShardAttribute []struct {
NodeId string `json:"NodeId"`
NodeClass string `json:"NodeClass"`
NodeStorage int `json:"NodeStorage"`
} `json:"ShardAttribute"`
} `json:"ShardList"`
EngineVersion string `json:"EngineVersion"`
DBInstanceStatus string `json:"DBInstanceStatus"`
DBInstanceStorage int `json:"DBInstanceStorage"`
MaintainStartTime string `json:"MaintainStartTime"`
MaintainEndTime string `json:"MaintainEndTime"`
StorageEngine string `json:"StorageEngine"`
VpcId string `json:"VPCId"`
VSwitchId string `json:"VSwitchId"`
VpcAuthMode string `json:"VpcAuthMode"`
ReplicationFactor string `json:"ReplicationFactor"`
}
var mongoSpec = map[string]struct {
VcpuCount int
VmemSizeGb int
}{}
func (self *SMongoDB) GetName() string {
if len(self.DBInstanceDescription) > 0 {
return self.DBInstanceDescription
}
return self.DBInstanceId
}
func (self *SMongoDB) GetId() string {
return self.DBInstanceId
}
func (self *SMongoDB) GetGlobalId() string {
return self.DBInstanceId
}
func (self *SMongoDB) GetStatus() string {
switch self.DBInstanceStatus {
case "Creating":
return api.MONGO_DB_STATUS_CREATING
case "DBInstanceClassChanging":
return api.MONGO_DB_STATUS_CHANGE_CONFIG
case "DBInstanceNetTypeChanging", "EngineVersionUpgrading", "GuardSwitching", "HASwitching", "Importing", "ImportingFromOthers", "LinkSwitching", "MinorVersionUpgrading", "NET_CREATING", "NET_DELETING", "NodeCreating", "NodeDeleting", "Restoring", "SSLModifying", "TempDBInstanceCreating", "Transing", "TransingToOthers":
return api.MONGO_DB_STATUS_DEPLOY
case "Deleting":
return api.MONGO_DB_STATUS_DELETING
case "Rebooting":
return api.MONGO_DB_STATUS_REBOOTING
case "Running":
return api.MONGO_DB_STATUS_RUNNING
default:
return strings.ToLower(self.DBInstanceStatus)
}
}
func (self *SMongoDB) GetProjectId() string {
return self.ResourceGroupId
}
func (self *SMongoDB) Refresh() error {
db, err := self.region.GetMongoDB(self.DBInstanceId)
if err != nil {
return errors.Wrapf(err, "GetMongoDB")
}
return jsonutils.Update(self, db)
}
func (self *SMongoDB) GetCreatedAt() time.Time {
return self.CreationTime
}
func (self *SMongoDB) GetExpiredAt() time.Time {
return self.ExpireTime
}
func (self *SMongoDB) GetIpAddr() string {
return ""
}
func (self *SMongoDB) GetEngine() string {
if len(self.StorageEngine) == 0 {
self.Refresh()
}
return self.StorageEngine
}
func (self *SMongoDB) GetEngineVersion() string {
return self.EngineVersion
}
func (self *SMongoDB) GetVpcId() string {
if self.NetworkType != "VPC" {
return ""
}
if len(self.VpcId) == 0 {
self.Refresh()
}
return self.VpcId
}
func (self *SMongoDB) GetNetworkId() string {
if self.NetworkType != "VPC" {
return ""
}
if len(self.VSwitchId) == 0 {
self.Refresh()
}
return self.VSwitchId
}
func (self *SMongoDB) GetZoneId() string {
if strings.Contains(self.ZoneId, ",") {
return self.ZoneId
}
if info := strings.Split(self.ZoneId, "-"); len(info) == 3 {
return strings.Join([]string{info[0], info[1], string(info[2][strings.Index(info[2], ",")-1])}, "-")
}
return ""
}
func (self *SMongoDB) Delete() error {
return self.region.DeleteMongoDB(self.DBInstanceId)
}
func (self *SMongoDB) GetBillingType() string {
return convertChargeType(self.ChargeType)
}
func (self *SMongoDB) GetCategory() string {
return self.DBInstanceType
}
func (self *SMongoDB) GetDiskSizeMb() int {
if self.DBInstanceStorage == 0 {
self.Refresh()
}
return self.DBInstanceStorage * 1024
}
func (self *SMongoDB) GetInstanceType() string {
return self.DBInstanceClass
}
func (self *SMongoDB) GetMaintainTime() string {
return fmt.Sprintf("%s-%s", self.MaintainStartTime, self.MaintainEndTime)
}
func (self *SMongoDB) GetPort() int {
return 3717
}
func (self *SMongoDB) GetReplicationNum() int {
if len(self.ReplicationFactor) == 0 {
self.Refresh()
}
num, _ := strconv.Atoi(self.ReplicationFactor)
return int(num)
}
func (self *SMongoDB) GetVcpuCount() int {
self.region.GetchMongoSkus()
sku, ok := self.region.mongoSkus[self.DBInstanceClass]
if ok {
return sku.CpuCount
}
return 0
}
func (self *SMongoDB) GetVmemSizeMb() int {
self.region.GetchMongoSkus()
sku, ok := self.region.mongoSkus[self.DBInstanceClass]
if ok {
return sku.MemSizeGb * 1024
}
return 0
}
func (self *SRegion) GetICloudMongoDBs() ([]cloudprovider.ICloudMongoDB, error) {
dbs := []SMongoDB{}
for {
part, total, err := self.GetMongoDBs(100, len(dbs)/100)
if err != nil {
return nil, errors.Wrapf(err, "GetMongoDB")
}
dbs = append(dbs, part...)
if len(dbs) >= total {
break
}
}
ret := []cloudprovider.ICloudMongoDB{}
for i := range dbs {
dbs[i].region = self
ret = append(ret, &dbs[i])
}
return ret, nil
}
func (self *SRegion) GetMongoDBs(pageSize int, pageNum int) ([]SMongoDB, int, error) {
if pageSize < 1 || pageSize > 100 {
pageSize = 100
}
if pageNum < 1 {
pageNum = 1
}
params := map[string]string{
"PageSize": fmt.Sprintf("%d", pageSize),
"PageNumber": fmt.Sprintf("%d", pageNum),
}
resp, err := self.mongodbRequest("DescribeDBInstances", params)
if err != nil {
return nil, 0, errors.Wrapf(err, "DescribeDBInstances")
}
ret := []SMongoDB{}
err = resp.Unmarshal(&ret, "DBInstances", "DBInstance")
if err != nil {
return nil, 0, errors.Wrapf(err, "resp.Unmarshal")
}
totalCount, _ := resp.Int("TotalCount")
return ret, int(totalCount), nil
}
func (self *SRegion) GetMongoDB(id string) (*SMongoDB, error) {
params := map[string]string{
"DBInstanceId": id,
}
resp, err := self.mongodbRequest("DescribeDBInstanceAttribute", params)
if err != nil {
return nil, errors.Wrapf(err, "DescribeDBInstanceAttribute")
}
ret := []SMongoDB{}
err = resp.Unmarshal(&ret, "DBInstances", "DBInstance")
if err != nil {
return nil, errors.Wrapf(err, "resp.Unmarshal")
}
if len(ret) == 1 {
ret[0].region = self
return &ret[0], nil
}
return nil, errors.Wrapf(cloudprovider.ErrNotFound, id)
}
func (self *SRegion) DeleteMongoDB(id string) error {
params := map[string]string{
"DBInstanceId": id,
"ClientToken": utils.GenRequestId(20),
}
_, err := self.mongodbRequest("DeleteDBInstance", params)
return errors.Wrapf(err, "DeleteDBInstance")
}
type SMongoDBAvaibaleResource struct {
SupportedDBTypes struct {
SupportedDBType []struct {
DbType string
AvailableZones struct {
AvailableZone []struct {
ZoneId string
RegionId string
SupportedEngineVersions struct {
SupportedEngineVersion []struct {
Version string
SupportedEngines struct {
SupportedEngine []struct {
SupportedNodeTypes struct {
SupportedNodeType []struct {
NetworkTypes string
NodeType string
AvailableResources struct {
AvailableResource []struct {
InstanceClassRemark string
InstanceClass string
}
}
}
}
}
}
}
}
}
}
}
}
}
func (self *SRegion) GetchMongoSkus() (map[string]struct {
CpuCount int
MemSizeGb int
}, error) {
if len(self.mongoSkus) > 0 {
return self.mongoSkus, nil
}
self.mongoSkus = map[string]struct {
CpuCount int
MemSizeGb int
}{}
res, err := self.GetMongoDBAvailableResource()
if err != nil {
return nil, err
}
for _, dbType := range res.SupportedDBTypes.SupportedDBType {
for _, zone := range dbType.AvailableZones.AvailableZone {
for _, version := range zone.SupportedEngineVersions.SupportedEngineVersion {
for _, engine := range version.SupportedEngines.SupportedEngine {
for _, nodeType := range engine.SupportedNodeTypes.SupportedNodeType {
for _, sku := range nodeType.AvailableResources.AvailableResource {
_, ok := self.mongoSkus[sku.InstanceClass]
if !ok {
self.mongoSkus[sku.InstanceClass] = getMongoDBSkuDetails(sku.InstanceClassRemark)
}
}
}
}
}
}
}
return self.mongoSkus, nil
}
func getMongoDBSkuDetails(remark string) struct {
CpuCount int
MemSizeGb int
} {
ret := struct {
CpuCount int
MemSizeGb int
}{}
r, _ := regexp.Compile(`(\d{1,3})核(\d{1,3})G+`)
result := r.FindSubmatch([]byte(remark))
if len(result) > 2 {
cpu, _ := strconv.Atoi(string(result[1]))
ret.CpuCount = int(cpu)
mem, _ := strconv.Atoi(string(result[2]))
ret.MemSizeGb = int(mem)
} else {
log.Warningf("not match sku remark %s", remark)
}
return ret
}
func (self *SRegion) GetMongoDBAvailableResource() (*SMongoDBAvaibaleResource, error) {
params := map[string]string{}
resp, err := self.mongodbRequest("DescribeAvailableResource", params)
if err != nil {
return nil, errors.Wrapf(err, "DescribeAvailableResource")
}
ret := &SMongoDBAvaibaleResource{}
err = resp.Unmarshal(ret)
if err != nil {
return nil, errors.Wrapf(err, "resp.Unmarshal")
}
return ret, nil
}
|
package statik
//This just for fixing the error in importing empty github.com/OCEChain/OCEChain/client/lcd/statik
|
package jsonvalidate
import (
"encoding/json"
"fmt"
"net/url"
"github.com/json-validate/json-pointer-go"
)
type Validator struct {
MaxErrors int
MaxDepth int
Registry Registry
}
type ValidationResult struct {
Errors []ValidationError `json:"errors"`
}
func (r ValidationResult) IsValid() bool {
return len(r.Errors) == 0
}
type ValidationError struct {
InstancePath jsonpointer.Ptr
SchemaPath jsonpointer.Ptr
SchemaURI url.URL
}
func (e *ValidationError) UnmarshalJSON(data []byte) error {
var strings map[string]string
if err := json.Unmarshal(data, &strings); err != nil {
return err
}
if val, ok := strings["instancePath"]; ok {
ptr, err := jsonpointer.New(val)
if err != nil {
return err
}
e.InstancePath = ptr
}
if val, ok := strings["schemaPath"]; ok {
ptr, err := jsonpointer.New(val)
if err != nil {
return err
}
e.SchemaPath = ptr
}
if val, ok := strings["schemaURI"]; ok {
uri, err := url.Parse(val)
if err != nil {
return err
}
e.SchemaURI = *uri
}
return nil
}
func (v Validator) Validate(instance interface{}) (ValidationResult, error) {
return v.ValidateURI(url.URL{}, instance)
}
func (v Validator) ValidateURI(uri url.URL, instance interface{}) (ValidationResult, error) {
schema, ok := v.Registry.Schemas[uri]
if !ok {
return ValidationResult{}, fmt.Errorf("no schema with uri: %s", uri.String())
}
vm := vm{
maxErrors: v.MaxErrors,
maxDepth: v.MaxDepth,
registry: v.Registry,
instanceTokens: []string{},
schemas: []schemaStack{
schemaStack{
uri: &uri,
tokens: []string{},
},
},
errors: []ValidationError{},
}
if err := vm.eval(schema, instance); err != nil {
if err != errMaxErrors {
return ValidationResult{}, err
}
}
return ValidationResult{Errors: vm.errors}, nil
}
|
package anagrams
import "testing"
type testCase struct {
s string
n int32
}
func TestSherlock(t *testing.T) {
testCases := []testCase{
{"abba", 4},
{"abcd", 0},
{"ifailuhkqq", 3},
{"kkkk", 10},
{"cdcd", 5},
}
for _, tc := range testCases {
t.Run(tc.s, func(t *testing.T) {
got := Sherlock(tc.s)
if got != tc.n {
t.Errorf("Sherlock(%q) = %d; wanted %d", tc.s, got, tc.n)
}
})
}
}
func TestSignature(t *testing.T) {
testCases := []testCase{
{"abba", 4},
{"abcd", 0},
{"ifailuhkqq", 3},
{"kkkk", 10},
{"cdcd", 5},
}
for _, tc := range testCases {
t.Run(tc.s, func(t *testing.T) {
got := Signature(tc.s)
if got != tc.n {
t.Errorf("Signature(%q) = %d; wanted %d", tc.s, got, tc.n)
}
})
}
}
var result int32
func BenchmarkSherlock(b *testing.B) {
var res int32
for i := 0; i < b.N; i++ {
res = Sherlock("ifailuhkqq")
}
result = res
}
func BenchmarkSignature(b *testing.B) {
var res int32
for i := 0; i < b.N; i++ {
res = Signature("ifailuhkqq")
}
result = res
}
|
package main
import (
"fmt"
"log"
"net/http"
"os"
"strconv"
"time"
"github.com/baor/telegobot/habr"
"github.com/baor/telegobot/storage"
"github.com/baor/telegobot/telegram"
)
// HandlerStatus handler returns applications status
func status(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "telegabot status is OK")
}
func main() {
token := os.Getenv("TLGB_API_TOKEN")
if token == "" {
log.Panic("Empty TLGB_API_TOKEN")
}
bot := telegram.NewBot(token)
var s storage.PostStorer
redisAddr := os.Getenv("TLGB_REDIS_ADDR")
if len(redisAddr) > 0 {
log.Printf("TLGB_REDIS_ADDR: %s", redisAddr)
s = storage.NewRedisAdapter(redisAddr)
}
gcsBucketName := os.Getenv("TLGB_GCS_BUCKET_NAME")
if len(gcsBucketName) > 0 {
log.Printf("TLGB_GCS_BUCKET_NAME: %s", gcsBucketName)
s = storage.NewGcsAdapter(gcsBucketName)
}
delayMinStr := os.Getenv("TLGB_DELAY_MIN")
log.Printf("TLGB_DELAY_MIN: %s", delayMinStr)
delayMinInt64, err := strconv.ParseInt(delayMinStr, 10, 32)
if err != nil || delayMinInt64 <= 0 {
delayMinInt64 = 30
}
delay := time.Duration(delayMinInt64) * time.Minute
port := os.Getenv("PORT")
if len(port) == 0 {
port = "8080"
}
feed := habr.NewHabrReader()
go updateLoop(context{
tlg: bot,
tlgChannel: "@habrbest",
st: s,
feed: feed,
delay: delay,
})
http.HandleFunc("/", status)
http.ListenAndServe(":"+port, nil)
}
|
package main
import (
jwtack "github.com/gobricks/jwtack/src"
app "github.com/gobricks/jwtack/src/app"
)
func main() {
jwtack.RunServer(app.NewApp())
} |
// +build !windows,!darwin
// 7 july 2014
package ui
import (
"unsafe"
)
// #include "gtk_unix.h"
import "C"
type label struct {
*controlSingleWidget
misc *C.GtkMisc
label *C.GtkLabel
}
func newLabel(text string) Label {
ctext := togstr(text)
defer freegstr(ctext)
widget := C.gtk_label_new(ctext)
l := &label{
controlSingleWidget: newControlSingleWidget(widget),
misc: (*C.GtkMisc)(unsafe.Pointer(widget)),
label: (*C.GtkLabel)(unsafe.Pointer(widget)),
}
return l
}
/*TODO
func newStandaloneLabel(text string) Label {
l := finishNewLabel(text, true)
// standalone labels are always at the top left
C.gtk_misc_set_alignment(l.misc, 0, 0)
return l
}
*/
func (l *label) Text() string {
return fromgstr(C.gtk_label_get_text(l.label))
}
func (l *label) SetText(text string) {
ctext := togstr(text)
defer freegstr(ctext)
C.gtk_label_set_text(l.label, ctext)
}
/*TODO
func (l *label) commitResize(c *allocation, d *sizing) {
if !l.standalone && c.neighbor != nil {
c.neighbor.getAuxResizeInfo(d)
if d.shouldVAlignTop {
// don't bother aligning it to the first line of text in the control; this is harder than it's worth (thanks gregier in irc.gimp.net/#gtk+)
C.gtk_misc_set_alignment(l.misc, 0, 0)
} else {
C.gtk_misc_set_alignment(l.misc, 0, 0.5)
}
}
basecommitResize(l, c, d)
}
*/
|
package main
import (
"JsGo/JsConfig"
"fmt"
)
func main() {
keys := make([]string, 2)
keys[0] = "Hello"
keys[1] = "Meng"
ret, err := JsConfig.GetConfigString(keys)
if err == nil {
fmt.Println(ret)
} else {
fmt.Println(err)
}
keys = make([]string, 3)
keys[0] = "xxx"
keys[1] = "yyy"
keys[2] = "zzz"
rmap, err := JsConfig.GetConfigString(keys)
if err == nil {
fmt.Println(rmap)
} else {
fmt.Println(err)
}
keys[0] = "a"
keys[1] = "yyy"
keys[2] = "zzz"
av, err := JsConfig.GetConfigInteger(keys)
if err == nil {
fmt.Println(av)
} else {
fmt.Println(err)
}
keys[0] = "b"
keys[1] = "yyy"
keys[2] = "zzz"
bv, err := JsConfig.GetConfigFloat(keys)
if err == nil {
fmt.Println(bv)
} else {
fmt.Println(err)
}
keys = make([]string, 2)
keys[0] = "c"
keys[1] = "yyy"
cv, err := JsConfig.GetConfigMap(keys)
if err == nil {
fmt.Printf("cv = %v\n", cv)
} else {
fmt.Println(err)
}
}
|
package AesCtr
import (
"crypto/cipher"
)
type gcmAble interface {
NewGCM(size int) (cipher.AEAD, error)
}
type cbcEncAble interface {
NewCBCEncrypter(iv []byte) cipher.BlockMode
}
type cbcDecAble interface {
NewCBCDecrypter(iv []byte) cipher.BlockMode
}
type ctrAble interface {
NewCTR(iv []byte) cipher.Stream
}
|
package bean
import (
"errors"
"strconv"
"time"
)
type UrlTask struct {
Url string
Keywords []string
Info DataItem
}
type UrlResult struct {
Task UrlTask
Eval []int
}
func (result *UrlResult) Compare(another *UrlResult) (int, error) {
if len(result.Eval) != len(another.Eval) {
return 0, errors.New("length is not match")
}
for i := 0; i < len(result.Eval); i++ {
if result.Eval[i] > another.Eval[i] {
return 1, nil
} else if result.Eval[i] < another.Eval[i] {
return -1, nil
}
}
return 0, nil
}
func (result *UrlResult) ToString() (str string) {
str = result.Task.Info.Title + ", " +result.Task.Url + ":"
str += "["
for _, item := range result.Eval {
str += strconv.Itoa(item) + ","
}
str += "]"
return
}
const (
MONITOR_TASK_LIFE_DEFAULT = 25
)
type MonitorTask struct {
Url string
Keyword string
Keywords []string
RegistrationId string
RespMapKey string
Time time.Time `json:"-"`
Life int
}
func (task *MonitorTask) IsEqual(another *MonitorTask) bool {
if task.Url == another.Url &&
task.Keyword == another.Keyword &&
task.RegistrationId == another.RegistrationId {
return true
} else {
return false
}
}
type MonitorResponse struct {
BaseResponse
Url string
Title string
Keyword string
Task MonitorTask
ResultData []UrlResult
}
type MonitorListResponse struct {
BaseResponse
Tasks []MonitorTask
}
|
package json
import (
"errors"
"fmt"
"strconv"
)
type stateFn func(l *dictgen) stateFn
const (
SPE_NONE = 0x00
SPE_K = 0x01
SPE_C = 0x02
SPE_S = 0x04
)
type Item struct {
id string
t string
scope string
desc string
v string
ri int
}
func NewItem(id, t, scope, desc, v string, ri int) Item {
return Item{id, t, scope, desc, v, ri}
}
type dictgen struct {
ch chan []Item
output string
done chan string
err chan error
ri, ci int
}
func (l *dictgen) String() string {
return l.output
}
func (l *dictgen) Push(items []Item) {
l.ch <- items
}
func (l *dictgen) EndPush() {
l.Push(make([]Item, 0))
}
func (l *dictgen) Done() string {
return <- l.done
}
func (l *dictgen) Error() chan error {
return l.err
}
func (l *dictgen) reset() {
l.output = ""
l.ri = 0
l.ci = 0
}
func (l *dictgen) abort() {
l.reset()
l.done <- ""
}
func (l *dictgen) addItem(item *Item) error {
if item.id == "" || item.v == "" {
return nil
}
key := "\"" + item.id + "\""
val := item.v
if item.t == "int" {
if _, err := strconv.Atoi(val); err != nil {
return errors.New(fmt.Sprintf("unexpected type error, row:[%v] identi:%v define:int val:%v, but not a number. err : %v", item.ri+1, key, item.v, err))
}
} else if item.t == "decimal" {
if _, err := strconv.ParseFloat(val, 32); err != nil {
return errors.New(fmt.Sprintf("unexpected type error, row:[%v] identi:%v define decimal, but not a number. err : %v", item.ri, key, err))
}
} else {
val = "\"" + val + "\""
}
object := key + ":" + val
if l.ci > 0 {
l.output += ","
l.output += "\r\n"
}
l.output += "\t\t"
l.output += object
l.ci++
return nil
}
func genNull(l *dictgen) stateFn {
return nil
}
func genStart(l *dictgen) stateFn {
l.output += "["
l.output += "\r\n"
return genNewRow
}
func genNewRow(l *dictgen) stateFn {
row := <-l.ch
if len(row) <= 0 {
return genEnd
}
if l.ri > 0 {
l.output += ","
l.output += "\r\n"
}
l.output += "\t"
l.output += "{"
l.output += "\r\n"
for _, item := range row {
if err := l.addItem(&item); err != nil {
l.err <- err
fmt.Printf("%v\n", err)
l.abort()
return genNull
}
}
l.output += "\r\n"
l.output += "\t"
l.output += "}"
l.ci = 0
l.ri++
return genNewRow
}
func genEnd(l *dictgen) stateFn {
l.output += "\r\n"
l.output += "]"
l.done <- l.output
return nil
}
func NewGenerator() *dictgen {
g := &dictgen{
ch: make(chan []Item, 1),
done: make(chan string, 1),
err: make(chan error, 1),
}
go func(g *dictgen) {
for state := genStart; state != nil; {
state = state(g)
}
close(g.ch)
close(g.done)
}(g)
return g
}
|
package nfe
import (
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
"net/http"
)
type NfeController struct{
Service INfeService
}
func NewNfeController(service INfeService) NfeController {
return NfeController{Service:service}
}
func (controller NfeController) RetrieveNfe(c *gin.Context) {
accessKey, ok := c.Request.URL.Query()["key"]
if !ok || "" == accessKey[0] {
c.JSON(http.StatusBadRequest, gin.H{"error": "Missing query parameter key"})
return
}
value, err := controller.Service.GetNfe(accessKey[0])
if err != nil {
handleServiceError(err, c)
return
}
c.JSON(http.StatusOK, gin.H{"access_key": value.AccessKey, "xml": value.XmlValue})
}
func handleServiceError(err error, c *gin.Context) {
if gorm.IsRecordNotFoundError(err) {
c.JSON(http.StatusBadRequest, gin.H{"error": "The nfe requested was not found"})
return
} else {
c.JSON(http.StatusInternalServerError, gin.H{"error": "An error occurred while retrieve your NFE, please try again later"})
return
}
} |
package dependencies
import (
goerr "errors"
"io/ioutil"
"os"
"path/filepath"
"strings"
"wio/cmd/wio/commands/run/cmake"
"wio/cmd/wio/errors"
"wio/cmd/wio/log"
"wio/cmd/wio/types"
"wio/cmd/wio/utils"
"wio/cmd/wio/utils/io"
"wio/cmd/wio/constants"
)
var packageVersions = map[string]string{} // Keeps track of versions for the packages
var cmakeTargets = map[string]*cmake.Target{} // CMake Target that will be built
var cmakeTargetsLink []cmake.TargetLink // CMake Target to Link to and from
var cmakeTargetNames = map[string]bool{} // CMake Target Names. Used to check for unique names
// Stores information about every package that is scanned
type DependencyScanStructure struct {
Name string
Directory string
Version string
FromVendor bool
MainTag types.PkgTag
Dependencies types.DependenciesTag
}
// Creates Scan structures for all the scanned packages
func createDependencyScanStructure(name string, depPath string, fromVendor bool) (*DependencyScanStructure, types.DependenciesTag, error) {
configPath := depPath + io.Sep + io.Config
config := types.PkgConfig{}
if err := io.NormalIO.ParseYml(configPath, &config); err != nil {
return nil, nil, err
} else {
if strings.Trim(config.MainTag.Config.WioVersion, " ") == "" {
wioVer := config.MainTag.Config.WioVersion
return nil, nil, errors.UnsupportedWioConfigVersion{PackageName: name, Version: wioVer}
}
pkg := &DependencyScanStructure{
Directory: depPath,
Name: config.GetMainTag().GetName(),
FromVendor: fromVendor,
Version: config.GetMainTag().GetVersion(),
MainTag: config.MainTag,
Dependencies: config.GetDependencies(),
}
packageVersions[pkg.Name] = pkg.Version
return pkg, config.DependenciesTag, nil
}
}
// Go through all the dependency packages and get information about them
func recursiveDependencyScan(queue *log.Queue, currDirectory string,
dependencies map[string]*DependencyScanStructure, packageDependencies types.DependenciesTag) error {
// if directory does not exist, do not do anything
if !utils.PathExists(currDirectory) {
log.Verbln(queue, "% does not exist, skipping", currDirectory)
return nil
}
// list all directories
if dirs, err := ioutil.ReadDir(currDirectory); err != nil {
return err
} else if len(dirs) > 0 {
// directories exist so let's go through each of them
for _, dir := range dirs {
// ignore files
if !dir.IsDir() {
continue
}
// only worry about dependencies in wio.yml file
if _, exists := packageDependencies[dir.Name()]; !exists {
continue
}
dirPath := currDirectory + io.Sep + dir.Name()
if !utils.PathExists(dirPath + io.Sep + io.Config) {
return goerr.New("wio.yml file missing")
}
var fromVendor = false
// check if the current directory is for remote or vendor
if filepath.Base(currDirectory) == io.Vendor {
fromVendor = true
}
// create DependencyScanStructure
if dependencyPackage, packageDeps, err := createDependencyScanStructure(dir.Name(), dirPath, fromVendor); err != nil {
return err
} else {
dependencyName := dependencyPackage.Name + "__vendor"
if !dependencyPackage.FromVendor {
dependencyName = dependencyPackage.Name + "__" + dependencyPackage.Version
}
dependencies[dependencyName] = dependencyPackage
log.Verbln(queue, "%s package stored as dependency named: %s", dirPath, dependencyName)
packageDependencies = packageDeps
}
modulePath := io.Path(dirPath, io.Modules)
vendorPath := io.Path(dirPath, io.Vendor)
if utils.PathExists(modulePath) {
// if remote directory exists
if err := recursiveDependencyScan(queue, modulePath, dependencies, packageDependencies); err != nil {
return err
}
} else if utils.PathExists(vendorPath) {
// if vendor directory exists
if err := recursiveDependencyScan(queue, vendorPath, dependencies, packageDependencies); err != nil {
return err
}
}
}
} else {
log.Verbln(queue, "% does not have any package, skipping", currDirectory)
}
return nil
}
// When we are building for pkg type, we will copy the files into the remote directory
// This will be picked up while scanning and hence the rest of build process stays the same
func convertPkgToDependency(pkgPath string, projectName string, projectDir string) error {
if !utils.PathExists(pkgPath) {
if err := os.MkdirAll(pkgPath, os.ModePerm); err != nil {
return err
}
}
pkgDir := pkgPath + io.Sep + projectName
if utils.PathExists(pkgDir) {
if err := os.RemoveAll(pkgDir); err != nil {
return err
}
}
// Copy project files
projectDir += io.Sep
pkgDir += io.Sep
for _, file := range []string{"src", "include", io.Config} {
if err := utils.Copy(projectDir+file, pkgDir+file); err != nil {
return err
}
}
return nil
}
func CreateCMakeDependencyTargets(
config types.IConfig,
target *types.Target,
projectPath string,
queue *log.Queue) error {
projectName := config.GetMainTag().GetName()
projectType := config.GetType()
projectDependencies := config.GetDependencies()
pkgVersion := config.GetMainTag().GetVersion()
projectFlags := (*target).GetFlags()
projectDefinitions := (*target).GetDefinitions()
remotePackagesPath := io.Path(projectPath, io.Folder, ``)
vendorPackagesPath := io.Path(projectPath, io.Vendor)
scannedDependencies := map[string]*DependencyScanStructure{}
if projectType == constants.PKG {
if projectDependencies == nil {
projectDependencies = types.DependenciesTag{}
}
// convert pkg project into tests dependency
projectDependencies[projectName] = &types.DependencyTag{
Version: pkgVersion,
Flags: projectFlags.GetPkgFlags(),
Definitions: projectDefinitions.GetPkgDefinitions(),
LinkVisibility: "PRIVATE",
}
packageDependencyPath := io.Path(projectPath, io.Folder, io.Package)
log.Verb(queue, "converting project to a dependency to be used in tests ... ")
if err := convertPkgToDependency(packageDependencyPath, projectName, projectPath); err != nil {
log.WriteFailure(queue, log.VERB)
return err
}
log.WriteSuccess(queue, log.VERB)
log.Verb(queue, "recursively scanning package dependency at path "+"%s ...", packageDependencyPath)
subQueue := log.GetQueue()
if err := recursiveDependencyScan(subQueue, packageDependencyPath, scannedDependencies, projectDependencies); err != nil {
log.WriteFailure(queue, log.VERB)
log.CopyQueue(subQueue, queue, log.TWO_SPACES)
return err
} else {
log.WriteSuccess(queue, log.VERB)
log.CopyQueue(subQueue, queue, log.TWO_SPACES)
}
}
log.Verb(queue, log.VERB, nil, "recursively scanning remote dependencies at path: %s ... ", remotePackagesPath)
subQueue := log.GetQueue()
if err := recursiveDependencyScan(subQueue, remotePackagesPath, scannedDependencies, projectDependencies); err != nil {
log.WriteFailure(queue, log.VERB)
log.CopyQueue(subQueue, queue, log.TWO_SPACES)
return err
}
log.WriteSuccess(queue, log.VERB)
log.CopyQueue(subQueue, queue, log.TWO_SPACES)
log.Verb(queue, "recursively scanning vendor dependencies at path: %s ... ", vendorPackagesPath)
subQueue = log.GetQueue()
if err := recursiveDependencyScan(subQueue, vendorPackagesPath, scannedDependencies, projectDependencies); err != nil {
log.WriteFailure(queue, log.VERB)
log.CopyQueue(subQueue, queue, log.TWO_SPACES)
return err
}
log.WriteSuccess(queue, log.VERB)
log.CopyQueue(subQueue, queue, log.TWO_SPACES)
parentTarget := `${TARGET_NAME}`
// go through all the direct dependencies and create a cmake targets
for dependencyName, projectDependency := range projectDependencies {
var dependencyTargetName string
var dependencyTarget *DependencyScanStructure
fullName := dependencyName + "@" + packageVersions[dependencyName]
if projectDependency.Vendor {
dependencyTargetName = dependencyName + "__vendor"
} else {
dependencyTargetName = dependencyName + "__" + packageVersions[dependencyName]
}
if dependencyTarget = scannedDependencies[dependencyTargetName]; dependencyTarget == nil {
return errors.DependencyDoesNotExistError{
DependencyName: fullName,
Vendor: projectDependency.Vendor,
}
}
log.Verb(queue, "creating cmake target for %s ... ", fullName)
subQueue := log.GetQueue()
requiredFlags, requiredDefinitions, err := CreateCMakeTargets(subQueue, parentTarget, false,
fullName, dependencyTargetName, dependencyTarget, projectFlags.GetGlobalFlags(),
projectDefinitions.GetGlobalDefinitions(), projectDependency, projectDependency)
if err != nil {
log.WriteFailure(queue, log.VERB)
log.CopyQueue(subQueue, queue, log.TWO_SPACES)
return err
}
log.WriteSuccess(queue, log.VERB)
log.CopyQueue(subQueue, queue, log.TWO_SPACES)
log.Verb(queue, "recursively creating cmake targets for %s dependencies ... ", fullName)
subQueue = log.GetQueue()
if err := traverseDependencies(subQueue, dependencyTargetName,
dependencyTarget.MainTag.GetCompileOptions().IsHeaderOnly(), scannedDependencies,
dependencyTarget.Dependencies, projectFlags.GetGlobalFlags(), requiredFlags,
projectDefinitions.GetGlobalDefinitions(), requiredDefinitions,
projectDependency); err != nil {
log.WriteFailure(queue, log.VERB)
log.CopyQueue(subQueue, queue, log.TWO_SPACES)
return err
}
log.WriteSuccess(queue, log.VERB)
log.CopyQueue(subQueue, queue, log.TWO_SPACES)
}
cmakePath := cmake.BuildPath(projectPath) + io.Sep + (*target).GetName()
cmakePath += io.Sep + "dependencies.cmake"
platform := (*target).GetPlatform()
avrCmake := cmake.GenerateDependencies(platform, cmakeTargets, cmakeTargetsLink)
return io.NormalIO.WriteFile(cmakePath, []byte(strings.Join(avrCmake, "\n")))
}
|
package ymdRedisServer
import (
"testing"
"reflect"
"github.com/orestonce/ymd/ymdAssert"
"github.com/orestonce/ymd/ymdRedis/ymdRedisProtocol"
)
func TestRedisCore_LIndex(t *testing.T) {
core := newDebugRedisCore()
core.RPush(`key`, `a`, `b`, `c`, `d`, `e`)
reply, errMsg := core.LIndex(`key`, 2)
ymdAssert.True(errMsg == `` && string(reply.Value) == `c`)
reply, errMsg = core.LIndex(`k`, 2)
ymdAssert.True(errMsg == `` && reply.Value == nil)
reply, errMsg = core.LIndex(`key`, 100)
ymdAssert.True(errMsg == `` && reply.Value == nil)
}
func TestRedisCore_LInsert(t *testing.T) {
core := newDebugRedisCore()
core.RPush(`list`, `1`, `2`, `4`)
after, errMsg := core.LInsert(`list`, `before`, `4`, `3`)
ymdAssert.True(errMsg == `` && after == 4, errMsg, after)
listEqual(core, `list`, `1`, `2`, `3`, `4`, )
after, errMsg = core.LInsert(`list`, `before`, `18929`, `s`)
ymdAssert.True(errMsg == `` && after == -1)
after, errMsg = core.LInsert(`list`, `after`, `1`, `v`)
ymdAssert.True(errMsg == `` && after == 5, errMsg, after)
listEqual(core, `list`, `1`, `v`, `2`, `3`, `4`)
_, errMsg = core.LInsert(`list`, `none`, `1`, `1`)
ymdAssert.True(errMsg == ymdRedisProtocol.EMSyntax)
after, errMsg = core.LInsert(`list2`, `after`, `1`, `1`)
ymdAssert.True(errMsg == `` && after == 0)
core.Set(`key`, `value`)
_, errMsg = core.LInsert(`key`, `before`, `1`, `1`)
ymdAssert.True(errMsg == ymdRedisProtocol.EMInvalidType)
}
func TestRedisCore_LLen(t *testing.T) {
core := newDebugRedisCore()
core.RPush(`list`, `1`, `2`, `3`)
iLen, errMsg := core.LLen(`list`)
ymdAssert.True(errMsg == `` && iLen == 3)
core.Set(`key`, `value`)
_, errMsg = core.LLen(`key`)
ymdAssert.True(errMsg == ymdRedisProtocol.EMInvalidType)
iLen, errMsg = core.LLen(`key-3`)
ymdAssert.True(errMsg == `` && iLen == 0)
}
func TestRedisCore_LPop(t *testing.T) {
core := newDebugRedisCore()
core.RPush(`list`, `d`)
core.RPush(`list`, `a`, `b`, `c`)
listEqual(core, `list`, `d`, `a`, `b`, `c`)
reply, errMsg := core.LPop(`list`)
ymdAssert.True(errMsg == ``)
ymdAssert.True(string(reply.Value) == `d`)
reply, errMsg = core.LPop(`list`)
ymdAssert.True(errMsg == ``)
ymdAssert.True(string(reply.Value) == `a`)
reply, errMsg = core.LPop(`list2`)
ymdAssert.True(errMsg == `` && reply.Value == nil)
core.Set(`key`, `value`)
_, errMsg = core.LPop(`key`)
ymdAssert.True(errMsg == ymdRedisProtocol.EMInvalidType)
core.LPop(`list`)
reply, errMsg = core.LPop(`list`)
ymdAssert.True(errMsg == `` && string(reply.Value) == `c`)
ymdAssert.True(core.data[`list`] == nil)
}
func TestRedisCore_LPush(t *testing.T) {
core := newDebugRedisCore()
iLen, errMsg := core.LPush(`list`, `a`, `b`)
ymdAssert.True(errMsg == `` && iLen == 2)
listEqual(core, `list`, `b`, `a`)
}
func TestRedisCore_LPushX(t *testing.T) {
core := newDebugRedisCore()
core.LPush(`list`, `a`, `b`)
listEqual(core, `list`, `b`, `a`)
iLen, errMsg := core.LPushX(`list`, `c`)
listEqual(core, `list`, `c`, `b`, `a`)
ymdAssert.True(iLen == 3 && errMsg == ``)
iLen, errMsg = core.LPushX(`list`, `d`)
ymdAssert.True(iLen == 4 && errMsg == ``)
listEqual(core, `list`, `d`, `c`, `b`, `a`)
iLen, errMsg = core.LPushX(`list1`, `x`)
ymdAssert.True(iLen == 0 && errMsg == ``)
core.Set(`key`, `value`)
iLen, errMsg = core.LPushX(`key`, `v`)
ymdAssert.True(errMsg == ymdRedisProtocol.EMInvalidType)
}
func TestRedisCore_LRange(t *testing.T) {
core := newDebugRedisCore()
core.RPush(`list`, `a`, `b`, `c`)
reply, errMsg := core.LRange(`list`, 0, -1)
ymdAssert.True(errMsg == ``)
strList := reply.ToStringList()
ymdAssert.True(reflect.DeepEqual(strList, []string{`a`, `b`, `c`,}))
reply, errMsg = core.LRange(`list`, -10, -2)
ymdAssert.True(errMsg == ``)
strList = reply.ToStringList()
ymdAssert.True(reflect.DeepEqual(strList, []string{`a`, `b`}))
}
func TestRedisCore_LRem(t *testing.T) {
core := newDebugRedisCore()
core.RPush(`list`, `a`, `b`, `c`, `b`, `d`, `b`)
cnt, errMsg := core.LRem(`list`, 2, `b`)
ymdAssert.True(cnt == 2 && errMsg == ``)
listEqual(core, `list`, `a`, `c`, `d`, `b`)
core.RPush(`list`, `d`, `c`, `d`, `b`, `b`)
cnt, errMsg = core.LRem(`list`, 0, `b`)
ymdAssert.True(cnt == 3 && errMsg == ``)
listEqual(core, `list`, `a`, `c`, `d`, `d`, `c`, `d`)
cnt, errMsg = core.LRem(`list`, -2, `d`)
ymdAssert.True(cnt == 2 && errMsg == ``)
listEqual(core, `list`, `a`, `c`, `d`, `c`)
cnt, errMsg = core.LRem(`list`, -5, `c`)
ymdAssert.True(cnt == 2 && errMsg == ``)
listEqual(core, `list`, `a`, `d`)
core.Del(`list`)
cnt, errMsg = core.LRem(`list`, 0, `a`)
ymdAssert.True(cnt == 0 && errMsg == ``)
core.Set(`key`, `value`)
cnt, errMsg = core.LRem(`key`, 10, `a`)
ymdAssert.True(errMsg == ymdRedisProtocol.EMInvalidType)
}
func TestRedisCore_RPop(t *testing.T) {
core := newDebugRedisCore()
core.RPush(`list`, `a`, `b`, `c`)
reply, errMsg := core.RPop(`list`)
ymdAssert.True(errMsg == `` && string(reply.Value) == `c`)
listEqual(core, `list`, `a`, `b`)
reply, errMsg = core.RPop(`list2`)
ymdAssert.True(errMsg == `` && reply.Value == nil)
core.Set(`key`, `value`)
_, errMsg = core.RPop(`key`)
ymdAssert.True(errMsg == ymdRedisProtocol.EMInvalidType)
core.RPush(`test`, `a`)
reply, errMsg = core.RPop(`test`)
ymdAssert.True(errMsg == `` && string(reply.Value) == `a`)
_, ok := core.data[`test`]
ymdAssert.True(!ok)
}
func TestRedisCore_RPopLPush(t *testing.T) {
core := newDebugRedisCore()
core.RPush(`source`, `a`, `b`, `c`, `d`)
for _, one := range []string{`d`, `c`} {
reply, errMsg := core.RPopLPush(`source`, `dest`)
ymdAssert.True(errMsg == `` && string(reply.Value) == one)
}
listEqual(core, `source`, `a`, `b`)
listEqual(core, `dest`, `c`, `d`)
for _, one := range []string{`b`, `a`} {
reply, errMsg := core.RPopLPush(`source`, `dest`)
ymdAssert.True(errMsg == `` && string(reply.Value) == one)
}
_, ok := core.data[`source`]
ymdAssert.True(!ok)
listEqual(core, `dest`, `a`, `b`, `c`, `d`)
}
func TestRedisCore_RPopLPush2(t *testing.T) {
core := newDebugRedisCore()
reply, errMsg := core.RPopLPush(`source`, `dest`)
ymdAssert.True(errMsg == `` && reply.Value == nil)
core.Set(`source`, `a`)
_, errMsg = core.RPopLPush(`source`, `dest`)
ymdAssert.True(errMsg == ymdRedisProtocol.EMInvalidType)
core.Del(`source`)
core.RPush(`source`, `a`)
core.Set(`dest`, `b`)
_, errMsg = core.RPopLPush(`source`, `dest`)
ymdAssert.True(errMsg == ymdRedisProtocol.EMInvalidType)
}
func TestRedisCore_RPush(t *testing.T) {
core := newDebugRedisCore()
iLen, errMsg := core.RPush(`list`, `a`, `b`, `c`)
ymdAssert.True(iLen == 3 && errMsg == ``)
listEqual(core, `list`, `a`, `b`, `c`)
core.Set(`key`, `value`)
_, errMsg = core.RPush(`key`, `a`)
ymdAssert.True(errMsg == ymdRedisProtocol.EMInvalidType)
}
func TestRedisCore_RPush2(t *testing.T) {
core := newDebugRedisCore()
core.Set(`list`, `v`)
_, errMsg := core.RPush(`list`, `a`, `b`)
ymdAssert.True(errMsg == ymdRedisProtocol.EMInvalidType)
}
func TestRedisCore_RPushX(t *testing.T) {
core := newDebugRedisCore()
core.RPush(`list`, `a`, `b`)
iLen, errMsg := core.RPushX(`list`, `d`)
ymdAssert.True(iLen == 3 && errMsg == ``)
listEqual(core, `list`, `a`, `b`, `d`)
core.Set(`key`, `value`)
_, errMsg = core.RPushX(`key`, `x`)
ymdAssert.True(errMsg == ymdRedisProtocol.EMInvalidType)
iLen, errMsg = core.RPushX(`key2`, `x`)
ymdAssert.True(iLen == 0 && errMsg == ``)
}
func listEqual(core *RedisCore, key string, list ...string) {
reply, errMsg := core.LRange(key, 0, -1)
ymdAssert.True(errMsg == ``)
strList := reply.ToStringList()
ymdAssert.True(reflect.DeepEqual(strList, list), list, strList)
}
|
package routes
import (
"to_do_list/module/todo/handlers"
"to_do_list/module/todo/repositories"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
)
var todoRepo repositories.Todo
//SetupRouter untuk setup routernya bro
func SetupRouter(db *gorm.DB) *gin.Engine {
todoRepo = repositories.NewTodoRepositories(db)
TodoHandler := handlers.TodoHandler(todoRepo)
r := gin.Default()
v1 := r.Group("/v1")
{
v1.GET("todo", TodoHandler.GetTodos)
v1.GET("todo/:id", TodoHandler.GetATodo)
v1.POST("todo", TodoHandler.CreateTodo)
v1.PUT("todo/:id", TodoHandler.EditTodo)
v1.DELETE("todo/:id", TodoHandler.DeleteTodo)
}
return r
}
|
package epg
import (
"github.com/stretchr/testify/assert"
"github.com/yosisa/arec/reserve"
"os"
"testing"
"time"
)
func TestDeocdeJson(t *testing.T) {
f, err := os.Open("testdata/gr99.json")
if err != nil {
t.Fatal(err)
}
defer f.Close()
channels, err := DecodeJson(f)
ch := channels[0]
assert.Nil(t, err)
assert.Equal(t, ch.Id, "GR0_9")
assert.Equal(t, ch.Name, "Test TV1")
assert.Equal(t, ch.Programs[0], Program{100, "GR0_9", "番組1", "description here",
nil, 1.3886532e+13, 1.3886541e+13, 900, []category{
category{categoryItem{"アニメ/特撮", "anime"},
categoryItem{"国内アニメ", "Japanese animation"}}}})
}
func TestChannelToDocument(t *testing.T) {
f, err := os.Open("testdata/gr99.json")
if err != nil {
t.Fatal(err)
}
defer f.Close()
channels, err := DecodeJson(f)
channel := channels[0]
ch := channel.toDocument("1")
assert.Equal(t, ch, &reserve.Channel{
Id: "GR0_9",
Name: "Test TV1",
Type: "GR",
Ch: "1",
Sid: 9,
})
}
func TestProgramToDocument(t *testing.T) {
f, err := os.Open("testdata/gr99.json")
if err != nil {
t.Fatal(err)
}
defer f.Close()
channels, err := DecodeJson(f)
now := time.Now().Unix()
assert.Equal(t, channels[0].Programs[0].toDocument(now), &reserve.Program{
Channel: "GR0_9",
EventId: "epg:GR0_9:100",
Title: "番組1",
Detail: "description here",
Category: []string{"アニメ/特撮", "anime", "国内アニメ", "Japanese animation"},
Start: 1388653200,
End: 1388654100,
Duration: 900,
Flag: nil,
UpdatedAt: int(now),
})
assert.Equal(t, channels[0].Programs[1].toDocument(now), &reserve.Program{
Channel: "GR0_9",
EventId: "epg:GR0_9:101",
Title: "番組1",
Detail: "description here",
Category: []string{"アニメ/特撮", "anime", "国内アニメ", "Japanese animation"},
Start: 1388654100,
End: 1388655000,
Duration: 900,
Flag: []string{"rerun"},
UpdatedAt: int(now),
})
assert.Equal(t, channels[0].Programs[2].toDocument(now), &reserve.Program{
Channel: "GR0_9",
EventId: "epg:GR0_9:102",
Title: "番組1",
Detail: "description here",
Category: []string{"アニメ/特撮", "anime", "国内アニメ", "Japanese animation"},
Start: 1388655000,
End: 1388655900,
Duration: 900,
Flag: []string{"new", "rerun"},
UpdatedAt: int(now),
})
assert.Equal(t, channels[0].Programs[3].toDocument(now), &reserve.Program{
Channel: "GR0_9",
EventId: "epg:GR0_9:103",
Title: "番組1",
Detail: "description here",
Category: []string{"アニメ/特撮", "anime", "国内アニメ", "Japanese animation"},
Start: 1388655900,
End: 1388656800,
Duration: 900,
Flag: []string{"final"},
UpdatedAt: int(now),
})
}
|
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package filewatch
import (
"context"
"fmt"
"sync"
"time"
"github.com/jonboulle/clockwork"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
ctrlclient "sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/handler"
"github.com/tilt-dev/fsnotify"
"github.com/tilt-dev/tilt/internal/controllers/apicmp"
"github.com/tilt-dev/tilt/internal/controllers/apis/configmap"
"github.com/tilt-dev/tilt/internal/controllers/core/filewatch/fsevent"
"github.com/tilt-dev/tilt/internal/controllers/indexer"
"github.com/tilt-dev/tilt/internal/ignore"
"github.com/tilt-dev/tilt/internal/store"
"github.com/tilt-dev/tilt/internal/store/filewatches"
"github.com/tilt-dev/tilt/internal/watch"
"github.com/tilt-dev/tilt/pkg/apis"
"github.com/tilt-dev/tilt/pkg/apis/core/v1alpha1"
"github.com/tilt-dev/tilt/pkg/logger"
)
// Controller reconciles a FileWatch object
type Controller struct {
ctrlclient.Client
Store store.RStore
targetWatches map[types.NamespacedName]*watcher
fsWatcherMaker fsevent.WatcherMaker
timerMaker fsevent.TimerMaker
mu sync.Mutex
clock clockwork.Clock
indexer *indexer.Indexer
requeuer *indexer.Requeuer
}
func NewController(client ctrlclient.Client, store store.RStore, fsWatcherMaker fsevent.WatcherMaker, timerMaker fsevent.TimerMaker, scheme *runtime.Scheme, clock clockwork.Clock) *Controller {
return &Controller{
Client: client,
Store: store,
targetWatches: make(map[types.NamespacedName]*watcher),
fsWatcherMaker: fsWatcherMaker,
timerMaker: timerMaker,
indexer: indexer.NewIndexer(scheme, indexFw),
requeuer: indexer.NewRequeuer(),
clock: clock,
}
}
func (c *Controller) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
c.mu.Lock()
defer c.mu.Unlock()
existing, hasExisting := c.targetWatches[req.NamespacedName]
var fw v1alpha1.FileWatch
err := c.Client.Get(ctx, req.NamespacedName, &fw)
c.indexer.OnReconcile(req.NamespacedName, &fw)
if err != nil && !apierrors.IsNotFound(err) {
return ctrl.Result{}, err
}
if apierrors.IsNotFound(err) || !fw.ObjectMeta.DeletionTimestamp.IsZero() {
if hasExisting {
existing.cleanupWatch(ctx)
c.removeWatch(existing)
}
c.Store.Dispatch(filewatches.NewFileWatchDeleteAction(req.NamespacedName.Name))
return ctrl.Result{}, nil
}
// The apiserver is the source of truth, and will ensure the engine state is up to date.
c.Store.Dispatch(filewatches.NewFileWatchUpsertAction(&fw))
ctx = store.MustObjectLogHandler(ctx, c.Store, &fw)
// Get configmap's disable status
disableStatus, err := configmap.MaybeNewDisableStatus(ctx, c.Client, fw.Spec.DisableSource, fw.Status.DisableStatus)
if err != nil {
return ctrl.Result{}, err
}
// Clean up existing filewatches if it's disabled
result := ctrl.Result{}
if disableStatus.State == v1alpha1.DisableStateDisabled {
if hasExisting {
existing.cleanupWatch(ctx)
c.removeWatch(existing)
}
} else {
// Determine if we the filewatch needs to be refreshed.
shouldRestart := !hasExisting || !apicmp.DeepEqual(existing.spec, fw.Spec)
if hasExisting && !shouldRestart {
shouldRestart, result = existing.shouldRestart()
}
if shouldRestart {
c.addOrReplace(ctx, req.NamespacedName, &fw)
}
}
watch, ok := c.targetWatches[req.NamespacedName]
status := &v1alpha1.FileWatchStatus{DisableStatus: disableStatus}
if ok {
status = watch.copyStatus()
status.DisableStatus = disableStatus
}
err = c.maybeUpdateObjectStatus(ctx, &fw, status)
if err != nil {
return ctrl.Result{}, err
}
return result, nil
}
func (c *Controller) maybeUpdateObjectStatus(ctx context.Context, fw *v1alpha1.FileWatch, newStatus *v1alpha1.FileWatchStatus) error {
if apicmp.DeepEqual(newStatus, &fw.Status) {
return nil
}
oldError := fw.Status.Error
update := fw.DeepCopy()
update.Status = *newStatus
err := c.Client.Status().Update(ctx, update)
if err != nil {
return err
}
if update.Status.Error != "" && oldError != update.Status.Error {
logger.Get(ctx).Errorf("filewatch %s: %s", fw.Name, update.Status.Error)
}
c.Store.Dispatch(NewFileWatchUpdateStatusAction(update))
return nil
}
func (c *Controller) CreateBuilder(mgr ctrl.Manager) (*builder.Builder, error) {
b := ctrl.NewControllerManagedBy(mgr).
For(&v1alpha1.FileWatch{}).
Watches(&v1alpha1.ConfigMap{},
handler.EnqueueRequestsFromMapFunc((c.indexer.Enqueue))).
WatchesRawSource(c.requeuer, handler.Funcs{})
return b, nil
}
// removeWatch removes a watch from the map. It does NOT stop the watcher or free up resources.
//
// mu must be held before calling.
func (c *Controller) removeWatch(tw *watcher) {
if entry, ok := c.targetWatches[tw.name]; ok && tw == entry {
delete(c.targetWatches, tw.name)
}
}
func (c *Controller) addOrReplace(ctx context.Context, name types.NamespacedName, fw *v1alpha1.FileWatch) {
existing, hasExisting := c.targetWatches[name]
status := &v1alpha1.FileWatchStatus{}
w := &watcher{
name: name,
spec: *fw.Spec.DeepCopy(),
clock: c.clock,
restartBackoff: time.Second,
}
if hasExisting && apicmp.DeepEqual(existing.spec, w.spec) {
w.restartBackoff = existing.restartBackoff
status.Error = existing.status.Error
}
ignoreMatcher := ignore.CreateFileChangeFilter(fw.Spec.Ignores)
startFileChangeLoop := false
notify, err := c.fsWatcherMaker(
append([]string{}, fw.Spec.WatchedPaths...),
ignoreMatcher,
logger.Get(ctx))
if err != nil {
status.Error = fmt.Sprintf("filewatch init: %v", err)
} else if err := notify.Start(); err != nil {
status.Error = fmt.Sprintf("filewatch init: %v", err)
// Close the notify immediately, but don't add it to the watcher object. The
// watcher object is still needed to handle backoff.
_ = notify.Close()
} else {
startFileChangeLoop = true
}
if hasExisting {
// Clean up the existing watch AFTER the new watch has been started.
existing.cleanupWatch(ctx)
}
ctx, cancel := context.WithCancel(ctx)
w.cancel = cancel
if startFileChangeLoop {
w.notify = notify
status.MonitorStartTime = apis.NowMicro()
go c.dispatchFileChangesLoop(ctx, w)
}
w.status = status
c.targetWatches[name] = w
}
func (c *Controller) dispatchFileChangesLoop(ctx context.Context, w *watcher) {
eventsCh := fsevent.Coalesce(c.timerMaker, w.notify.Events())
defer func() {
c.mu.Lock()
defer c.mu.Unlock()
w.cleanupWatch(ctx)
c.requeuer.Add(w.name)
}()
for {
select {
case err, ok := <-w.notify.Errors():
if !ok {
return
}
if watch.IsWindowsShortReadError(err) {
w.recordError(fmt.Errorf("Windows I/O overflow.\n"+
"You may be able to fix this by setting the env var %s.\n"+
"Current buffer size: %d\n"+
"More details: https://github.com/tilt-dev/tilt/issues/3556\n"+
"Caused by: %v",
watch.WindowsBufferSizeEnvVar,
watch.DesiredWindowsBufferSize(),
err))
} else if err.Error() == fsnotify.ErrEventOverflow.Error() {
w.recordError(fmt.Errorf("%s\nerror: %v", DetectedOverflowErrMsg, err))
} else {
w.recordError(err)
}
c.requeuer.Add(w.name)
case <-ctx.Done():
return
case fsEvents, ok := <-eventsCh:
if !ok {
return
}
w.recordEvent(fsEvents)
c.requeuer.Add(w.name)
}
}
}
// Find all the objects to watch based on the Filewatch model
func indexFw(obj ctrlclient.Object) []indexer.Key {
fw := obj.(*v1alpha1.FileWatch)
result := []indexer.Key{}
if fw.Spec.DisableSource != nil {
cm := fw.Spec.DisableSource.ConfigMap
if cm != nil {
gvk := v1alpha1.SchemeGroupVersion.WithKind("ConfigMap")
result = append(result, indexer.Key{
Name: types.NamespacedName{Name: cm.Name},
GVK: gvk,
})
}
}
return result
}
|
package main
import (
"flag"
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/sirupsen/logrus"
)
var (
listenAddress = flag.String("web.listen-address", ":8080", "Address to listen on for web interface and telemetry")
metricPath = flag.String("web.telemetry-path", "/metrics", "Path under which to expose metrics")
configFile = flag.String("config", "/etc/birthday_exporter/config.yaml", "Path to configuration file")
isDebug = flag.Bool("debug", false, "Output verbose debug information")
logFormat = flag.String("log-format", "txt", "Log format, valid options are txt and json")
)
func main() {
flag.Parse()
switch *logFormat {
case "json":
logrus.SetFormatter(&logrus.JSONFormatter{})
default:
logrus.SetFormatter(&logrus.TextFormatter{})
}
logrus.Info("Starting Birthday Exporter...")
if *isDebug {
logrus.SetLevel(logrus.DebugLevel)
}
config, err := ConfigFromFile(*configFile)
if err != nil {
logrus.Fatal(err)
}
err = prometheus.Register(NewExporter(config))
if err != nil {
logrus.Fatal(err)
}
http.Handle(*metricPath, promhttp.Handler())
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
_, err := w.Write([]byte(`
<html>
<head><title>Birthday Exporter</title></head>
<body>
<h1>Birthday Exporter</h1>
<p><a href='` + *metricPath + `'>Metrics</a></p>
</body>
</html>
`))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
logrus.Printf("Providing metrics at %s%s", *listenAddress, *metricPath)
logrus.Fatal(http.ListenAndServe(*listenAddress, nil))
}
|
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"strconv"
"strings"
"time"
)
var debug = false
var dumpDir string
type UrbanAirship struct {
AppKey string
MasterSecret string
TokensLimitPerRequest int // Optional. A maximum value of only 10000 is accepted.
StartingTokenId string // Optional. UA Token Id is not the same as device_token.
}
type PushWoosh struct {
ApiKey string
AppCode string
DefaultDeviceType PWDeviceType
DefaultLanguage string
DefaultTimezone float64
}
var config = struct {
UrbanAirship
PushWoosh
}{
UrbanAirship{
"URBANAIRSHIP_APP_KEY",
"URBANAIRSHIP_MASTER_SECRET",
1000,
"",
},
PushWoosh{
"PUSHWOOSH_API_KEY",
"PUSHWOOSH_APP_CODE",
PWDeviceType(iOS),
"",
0,
},
}
type UADeviceToken struct {
Active bool `json:"active"`
Alias interface{} `json:"alias"`
Created string `json:"created"`
DeviceToken string `json:"device_token"`
Tags []interface{} `json:"tags"`
}
type UADeviceTokensResponse struct {
ActiveDeviceTokensCount float64 `json:"active_device_tokens_count"`
DeviceTokensCount float64 `json:"device_tokens_count"`
DeviceTokens []UADeviceToken `json:"device_tokens"`
NextPage string `json:"next_page,omitempty"`
}
type PWDeviceType int
const (
iOS PWDeviceType = 1 + iota
BB
Android
Nokia_ASHA
Windows_Phone
// There is no device type 6.
OS_X = 2 + iota
Windows_8
Amazon
Safari
)
type PWRegisterDevice struct {
Request PWRegisterDeviceRequest `json:"request"`
}
type PWRegisterDeviceRequest struct {
Auth string `json:"auth"`
Application string `json:"application"`
DeviceType PWDeviceType `json:"device_type"`
Hwid string `json:"hwid"`
PushToken string `json:"push_token"`
Language string `json:"language,omitempty"`
Timezone float64 `json:"timezone,omitempty"`
}
type PWDeviceRegisterResponse struct {
StatusCode int `json:"status_code"`
StatusMessage string `json:"status_message"`
Response interface{} `json:"response",omitempty`
}
type State struct {
Status string `json:"status"`
DeviceToken string `json:"device_token"`
}
var activeTokensCount float64 = 0
var tokensCount float64 = 0
var downloadedTokensCount float64 = 0
func GetDeviceTokensFromUrbanAirship(pending chan<- UADeviceToken, done chan bool) {
GetDeviceTokensFromUrbanAirshipWithURL := func(url string, deviceTokenResp *UADeviceTokensResponse) {
req, _ := http.NewRequest("GET", url, nil)
req.SetBasicAuth(config.UrbanAirship.AppKey, config.UrbanAirship.MasterSecret)
req.Header.Add("Content-type", "application/json")
req.Header.Add("Accept", "application/vnd.urbanairship+json; version=3;")
client := &http.Client{}
resp, _ := client.Do(req)
respBody, _ := ioutil.ReadAll(resp.Body)
json.Unmarshal(respBody, &deviceTokenResp)
}
nextPage := "https://go.urbanairship.com/api/device_tokens/?"
if config.UrbanAirship.TokensLimitPerRequest > 0 {
nextPage += "&limit=" + strconv.Itoa(config.UrbanAirship.TokensLimitPerRequest)
}
if len(config.UrbanAirship.StartingTokenId) > 0 {
nextPage += "&start=" + config.UrbanAirship.StartingTokenId
}
var allDeviceTokens = []UADeviceToken{}
for len(nextPage) > 0 {
var deviceTokens = []UADeviceToken{}
var deviceTokenResp UADeviceTokensResponse
GetDeviceTokensFromUrbanAirshipWithURL(nextPage, &deviceTokenResp)
if activeTokensCount == 0 {
activeTokensCount = deviceTokenResp.ActiveDeviceTokensCount
}
if tokensCount == 0 {
tokensCount = deviceTokenResp.DeviceTokensCount
}
deviceTokens = append(deviceTokens, deviceTokenResp.DeviceTokens...)
dir := dumpDir + "/urbanairship/" + strconv.Itoa(len(allDeviceTokens))
os.MkdirAll(dir, 0744)
txt, _ := json.MarshalIndent(deviceTokenResp, "", "\t")
ioutil.WriteFile(dir+"/device_tokens.json", txt, 0644)
if len(deviceTokenResp.NextPage) > 0 {
nextPage = deviceTokenResp.NextPage
} else {
nextPage = ""
}
allDeviceTokens = append(allDeviceTokens, deviceTokens...)
downloadedTokensCount = float64(len(allDeviceTokens))
for _, deviceToken := range deviceTokens {
pending <- deviceToken
}
}
txt, _ := json.MarshalIndent(allDeviceTokens, "", "\t")
ioutil.WriteFile(dumpDir+"/urbanairship.json", txt, 0644)
pending <- UADeviceToken{}
done <- true
}
func PostDeviceTokensToPushWoosh(pending chan UADeviceToken, done chan bool, status chan<- State) {
for deviceToken := range pending {
if len(deviceToken.DeviceToken) == 0 {
close(pending)
break
}
if debug {
fmt.Println("Attempting to register device with token: " + deviceToken.DeviceToken)
}
PostDeviceTokenToPushWoosh := func(registerDevice PWRegisterDevice, deviceRegisterResp *PWDeviceRegisterResponse) {
jsonBody, _ := json.Marshal(registerDevice)
maxRetries := 10
for i := 0; i < maxRetries; i++ {
body := strings.NewReader(string(jsonBody))
req, _ := http.NewRequest("POST", "https://cp.pushwoosh.com/json/1.3/registerDevice", body)
req.Header.Add("Content-type", "application/json")
req.Header.Add("Accept", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("\nHTTP error:", err)
} else if resp != nil && resp.StatusCode == 200 {
defer resp.Body.Close()
respBody, _ := ioutil.ReadAll(resp.Body)
json.Unmarshal(respBody, &deviceRegisterResp)
break
}
fmt.Println("Retrying HTTP request...")
time.Sleep(10 * time.Second)
}
}
if deviceToken.Active {
registerDevice := PWRegisterDevice{
Request: PWRegisterDeviceRequest{
Auth: config.PushWoosh.ApiKey,
Application: config.PushWoosh.AppCode,
DeviceType: config.PushWoosh.DefaultDeviceType,
Language: config.PushWoosh.DefaultLanguage,
Timezone: config.PushWoosh.DefaultTimezone,
Hwid: deviceToken.DeviceToken, // UrbanAirship does not provide UDID. Use the token instead.
PushToken: deviceToken.DeviceToken,
},
}
var deviceRegisterResp PWDeviceRegisterResponse
PostDeviceTokenToPushWoosh(registerDevice, &deviceRegisterResp)
if deviceRegisterResp.StatusCode != 200 || deviceRegisterResp.StatusMessage != "OK" {
r, _ := json.MarshalIndent(deviceRegisterResp, "", "\t")
fmt.Println("\nFailed to register device with token:")
fmt.Println("\n\t" + registerDevice.Request.PushToken)
fmt.Println("\nResponse from PushWoosh:\n")
os.Stdout.Write(r)
close(done)
} else {
if debug {
r, _ := json.MarshalIndent(deviceRegisterResp, "", "\t")
os.Stdout.Write(r)
fmt.Println()
}
}
status <- State{"SENT", deviceToken.DeviceToken}
} else {
status <- State{"INACTIVE", deviceToken.DeviceToken}
}
if debug {
fmt.Println("Device registration complete.")
}
}
done <- true
}
func StateMonitor(updateInterval time.Duration) chan<- State {
updates := make(chan State)
tokenStatus := make(map[string][]string)
ticker := time.NewTicker(updateInterval)
go func() {
for {
select {
case <-ticker.C:
fmt.Print("\r")
var downloadProgress float64 = 0
if downloadedTokensCount > 0 {
downloadProgress = downloadedTokensCount / tokensCount * 100
}
fmt.Printf("%.1f%% imported (%g of %g total tokens)", downloadProgress, downloadedTokensCount, tokensCount)
var uploadProgress float64 = 0
if len(tokenStatus["SENT"]) > 0 {
uploadProgress = float64(len(tokenStatus["SENT"])) / activeTokensCount * 100
}
fmt.Print(" --- ")
fmt.Printf("%.1f%% exported (%d of %g active tokens) ", uploadProgress, len(tokenStatus["SENT"]), activeTokensCount)
case t := <-updates:
tokenStatus[t.Status] = append(tokenStatus[t.Status], t.DeviceToken)
file, _ := os.OpenFile(dumpDir+"/pushwoosh.json", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
defer file.Close()
jsonStr, _ := json.MarshalIndent(t, "", "\t")
file.WriteString(string(jsonStr) + ", ")
}
}
}()
return updates
}
func main() {
dumpDir = "./dump/" + strconv.FormatInt(time.Now().Unix(), 10)
pending := make(chan UADeviceToken)
status := StateMonitor(1 * time.Millisecond)
done := make(chan bool)
go GetDeviceTokensFromUrbanAirship(pending, done)
go PostDeviceTokensToPushWoosh(pending, done, status)
go PostDeviceTokensToPushWoosh(pending, done, status)
go PostDeviceTokensToPushWoosh(pending, done, status)
<-done
<-done
<-done
<-done
fmt.Println("All done. Bye.")
}
|
package ecdsatools
import (
"crypto/sha256"
"github.com/stretchr/testify/assert"
"testing"
)
func TestSignAndRecoverSignature(t *testing.T) {
privateKey, err := GenerateKey()
assert.True(t, err == nil)
println("privateKey: ", BytesToHex(PrivateKeyToBytes(privateKey)))
publicKeyBytes := CompactPubKeyToBytes(PubKeyFromPrivateKey(privateKey))
privateKeyFromHex, err := PrivateKeyFromHex(BytesToHexWithoutPrefix(PrivateKeyToBytes(privateKey)))
assert.True(t, BytesToHex(PrivateKeyToBytes(privateKeyFromHex)) == BytesToHex(PrivateKeyToBytes(privateKey)))
println("publicKey: ", BytesToHex(publicKeyBytes[:]))
println("publicKey size: ", len(publicKeyBytes))
content := []byte("hello world")
contentHash := sha256.Sum256(content)
println("contentHash: ", BytesToHex(contentHash[:]))
println("contentHash size: ", len(contentHash))
sig, err := SignSignatureRecoverable(privateKey, contentHash)
println("sig: ", BytesToHex(sig[:]))
println("sig size after all: ", len(sig))
recovered, err := RecoverCompactSignature(sig, contentHash)
println("recovered: ", BytesToHex(recovered[:]))
println("recovered size: ", len(recovered))
assert.True(t, BytesToHex(recovered[:]) == BytesToHex(publicKeyBytes[:]))
verified := VerifySignature(ToPubKey(recovered[:]), contentHash, sig)
println("verified: ", verified)
assert.True(t, verified)
} |
package main
import (
"io/ioutil"
"os"
"os/exec"
"github.com/sdwolfe32/anirip/anirip"
)
// Trims the first couple seconds off of the video to remove any logos
func trimMKV(adLength int, tempDir string) error {
// Removes a stale temp files to avoid conflcts in func
os.Remove(tempDir + string(os.PathSeparator) + "untrimmed.episode.mkv")
os.Remove(tempDir + string(os.PathSeparator) + "split.episode-001.mkv")
os.Remove(tempDir + string(os.PathSeparator) + "prefix.episode.mkv")
os.Remove(tempDir + string(os.PathSeparator) + "split.episode-002.mkv")
os.Remove(tempDir + string(os.PathSeparator) + "list.episode.txt")
// Rename to temp filename before execution
if err := anirip.Rename(tempDir+string(os.PathSeparator)+"episode.mkv", tempDir+string(os.PathSeparator)+"untrimmed.episode.mkv", 10); err != nil {
return err
}
// Executes the command too split the meat of the video from the first ad chunk
cmd := exec.Command(anirip.FindAbsoluteBinary("mkvmerge"),
"--split", "timecodes:"+anirip.MStoTimecode(adLength),
"-o", "split.episode.mkv",
"untrimmed.episode.mkv")
cmd.Dir = tempDir
if err := cmd.Run(); err != nil {
return anirip.Error{Message: "There was an error while splitting the episode", Err: err}
}
// Executes the fine intro trim and waits for the command to finish
cmd = exec.Command(anirip.FindAbsoluteBinary("ffmpeg"),
"-i", "split.episode-001.mkv",
"-ss", anirip.MStoTimecode(adLength), // Exact timestamp of the ad endings
"-c:v", "h264",
"-crf", "15",
"-preset", "slow",
"-c:a", "copy", "-y", // Use AAC as audio codec to match video.mkv
"prefix.episode.mkv")
cmd.Dir = tempDir
if err := cmd.Run(); err != nil {
return anirip.Error{Message: "There was an error while creating the prefix clip", Err: err}
}
// Creates a text file containing the file names of the 2 files created above
fileListBytes := []byte("file 'prefix.episode.mkv'\r\nfile 'split.episode-002.mkv'")
if err := ioutil.WriteFile(tempDir+string(os.PathSeparator)+"list.episode.txt", fileListBytes, 0644); err != nil {
return anirip.Error{Message: "There was an error while creating list.episode.txt", Err: err}
}
// Executes the merge of our two temporary files
cmd = exec.Command(anirip.FindAbsoluteBinary("ffmpeg"),
"-f", "concat",
"-i", "list.episode.txt",
"-c", "copy", "-y",
"episode.mkv")
cmd.Dir = tempDir
if err := cmd.Run(); err != nil {
return anirip.Error{Message: "There was an error while merging video and prefix", Err: err}
}
// Removes the temporary files we created as they are no longer needed
os.Remove(tempDir + string(os.PathSeparator) + "untrimmed.episode.mkv")
os.Remove(tempDir + string(os.PathSeparator) + "split.episode-001.mkv")
os.Remove(tempDir + string(os.PathSeparator) + "prefix.episode.mkv")
os.Remove(tempDir + string(os.PathSeparator) + "split.episode-002.mkv")
os.Remove(tempDir + string(os.PathSeparator) + "list.episode.txt")
return nil
}
// Cleans the MKVs metadata for better reading by clients
func cleanMKV(tempDir string) error {
// Rename to temp filename before execution
if err := anirip.Rename(tempDir+string(os.PathSeparator)+"episode.mkv", tempDir+string(os.PathSeparator)+"dirty.episode.mkv", 10); err != nil {
return err
}
// Executes the clean of our temporary dirty mkv
cmd := exec.Command(anirip.FindAbsoluteBinary("mkclean"),
"dirty.episode.mkv",
"episode.mkv")
cmd.Dir = tempDir
if err := cmd.Run(); err != nil {
return anirip.Error{Message: "There was an error while cleaning video", Err: err}
}
// Removes the temporary files we created as they are no longer needed
os.Remove(tempDir + string(os.PathSeparator) + "dirty.episode.mkv")
return nil
}
// Merges a VIDEO.mkv and a VIDEO.ass
func mergeSubtitles(audioLang, subtitleLang, tempDir string) error {
// Removes a stale temp files to avoid conflcts in func
os.Remove(tempDir + string(os.PathSeparator) + "unmerged.episode.mkv")
// Rename to temp filename before execution
if err := anirip.Rename(tempDir+string(os.PathSeparator)+"episode.mkv", tempDir+string(os.PathSeparator)+"unmerged.episode.mkv", 10); err != nil {
return err
}
// Creates the command which we will use to merge our subtitles and video
cmd := new(exec.Cmd)
if subtitleLang == "" {
cmd = exec.Command(anirip.FindAbsoluteBinary("ffmpeg"),
"-i", "unmerged.episode.mkv",
"-c:v", "copy",
"-c:a", "copy",
"-metadata:s:a:0", "language="+audioLang, // sets audio language to passed audioLang
"-y", "episode.mkv")
} else {
cmd = exec.Command(anirip.FindAbsoluteBinary("ffmpeg"),
"-i", "unmerged.episode.mkv",
"-f", "ass",
"-i", "subtitles.episode.ass",
"-c:v", "copy",
"-c:a", "copy",
"-metadata:s:a:0", "language="+audioLang, // sets audio language to passed audioLang
"-metadata:s:s:0", "language="+subtitleLang, // sets subtitle language to subtitleLang
"-disposition:s:0", "default",
"-y", "episode.mkv")
}
cmd.Dir = tempDir
// Executes the command
if err := cmd.Run(); err != nil {
return anirip.Error{Message: "There was an error while merging subtitles", Err: err}
}
// Removes old temp files
os.Remove(tempDir + string(os.PathSeparator) + "subtitles.episode.ass")
os.Remove(tempDir + string(os.PathSeparator) + "unmerged.episode.mkv")
return nil
}
|
package template
import (
"bytes"
"fmt"
"html/template"
"syscall/js"
"github.com/factorapp/structure/dom"
)
type Renderer struct {
elt *dom.Element
}
func NewRenderer(elt *dom.Element) Renderer {
return Renderer{
elt: elt,
}
}
func (p Renderer) Render(tplName string, data map[string]interface{}) (string, error) {
tplElt := p.elt.Call("querySelector", "#"+tplName)
//tplElt := p.elt.QuerySelector("#" + tplName)
if tplElt == js.Null() {
return "", fmt.Errorf("no template %s found", tplName)
}
tplStrVal := tplElt.Get("innerHTML") //InnerHTML()
if tplStrVal == js.Null() {
return "", fmt.Errorf("no inner HTML in %s", tplName)
}
tplStr := tplStrVal.String()
tpl, err := template.New(tplStr).Parse(tplStr)
if err != nil {
return "", err
}
buf := new(bytes.Buffer)
if err := tpl.Execute(buf, data); err != nil {
return "", err
}
return string(buf.Bytes()), nil
}
|
package main
const esbuildVersion = "0.5.9"
|
package main
import (
"testing"
)
func TestCode(t *testing.T) {
var tests = []struct {
input []int
output int
}{
{
input: []int{1, 1, 2, 2, 3},
output: 1,
},
{
input: []int{1, 4, 4, 4, 5, 3},
output: 4,
},
}
for _, test := range tests {
if got := migratoryBirds(test.input); got != test.output {
t.Errorf(
"Input Array of Birds %v; Expected %v; Got %v",
test.input, test.output, got,
)
}
}
}
|
package ravendb
type FieldIndexing string
const (
FieldIndexingNo = "No"
FieldIndexingSearch = "Search"
FieldIndexingExact = "Exact"
FieldIndexingDefault = "Default"
)
|
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
var line, out string
initmaps()
out = ""
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line = scanner.Text()
out = convgost(line)
fmt.Print(out, "\n")
}
}
|
package lib
import (
"fmt"
"io"
"net/http"
"os"
"time"
)
func GetToken() (token string) {
Info.Println("Trying to load TOKEN.")
token = os.Getenv("GH_TOKEN")
if token != "" {
return token
}
Warning.Println("Can't load GH_TOKEN env variable")
Info.Println("Trying to extract TOKEN.")
token, err := GetKey(GitHubToken)
if err != nil {
Error.Println(err)
os.Exit(5)
}
return token
}
func GHPublisher(token string, publish *string, branch string, author Committer) error {
fname := fmt.Sprintf("%s.md", *publish)
if err := GitHubConnector(RspMDPath, fname, token, branch, author); err != nil {
return fmt.Errorf("GitHub connection Markdown (%s) error: %s\n", fname, err)
}
fname = fmt.Sprintf("%s.json", *publish)
if err := GitHubConnector(RspJSONPath, fname, token, branch, author); err != nil {
return fmt.Errorf("GitHub connection JSON (%s) error: %s\n", fname, err)
}
return nil
}
func GitHubConnector(fmtpath string, target string, token string, branch string, author Committer) error {
encoded, err := F2Base64(fmtpath)
if err != nil {
return err
}
url := fmt.Sprintf("%s%s", GHApiURL, "/git/trees/dev")
Trace.Printf("Tree url: %s\n", url)
folder := false
repo := new(Repo)
err = StreamHTTP(url, repo, false)
if err != nil {
return err
}
for _, file := range repo.Tree {
if file.Path == "data" {
url = file.URL
folder = true
break
}
}
if !folder {
return fmt.Errorf("Cant't get data folder url")
}
Trace.Printf("target: %s\n", target)
err = StreamHTTP(url, repo, false)
if err != nil {
return err
}
sha := ""
for _, file := range repo.Tree {
if file.Path == target {
sha = file.Sha
break
}
}
url = fmt.Sprintf("%s/contents/data/%s", GHApiURL, target)
Trace.Println(url)
c := fmt.Sprintf("%s [%s]", target, time.Now().Format(time.RFC3339))
var buf io.ReadWriter
if sha == "" {
Info.Println("Update not detected.")
data := Create{
Path: fmtpath,
Message: fmt.Sprintf("Create: %s", c),
Content: encoded,
Branch: branch,
Committer: author}
buf, err = JSONEncoder(data)
} else {
Info.Printf("Update SHA: %s", sha)
data := Update{
Path: fmtpath,
Message: fmt.Sprintf("Update: %s", c),
Content: encoded,
Sha: sha,
Branch: branch,
Committer: author}
buf, err = JSONEncoder(data)
}
if err != nil {
return err
}
req, err := http.NewRequest("PUT", url, buf)
if err != nil {
return err
}
Trace.Println("Sending header.")
req.Header.Set("Authorization", fmt.Sprintf("token %s", token))
response, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
Trace.Println("Response.")
defer response.Body.Close()
up := new(GHReqError)
err = JSONDecoder(response.Body, up)
if err != nil {
return err
}
Trace.Println(up)
return nil
}
|
package wallet
func run() {
//startd qitmeer
//current keys,hd wallet
//current addresses 1-10
//for blocks and check in out,,start blocks 0
//update block for index address in out balance
}
|
package logging
// checkLevel ログレベルをチェックします.
func checkLevel(level, configLevel Level) bool {
if level < configLevel {
return false
}
return true
}
// getLevelStr ログレベルを文字列として取得します.
func getLevelStr(level Level) string {
switch level {
case DEBUG:
return "DEBUG"
case INFO:
return "INFO"
case WARN:
return "WARN"
case ERROR:
return "ERROR"
default:
return ""
}
}
// isNotLoggerFuncPath ロガー関数のパスではないことを確認します.
func isNotLoggerFuncPath(funcName string) bool {
common := "github.com/takauma/logging.(*Logger)."
switch funcName {
case common + "Debug":
fallthrough
case common + "Info":
fallthrough
case common + "Warn":
fallthrough
case common + "Error":
return false
default:
return true
}
}
|
package turingapi
type Body struct {
ReqType int `json:"reqType"`
Perception *Query `json:"perception"`
UserInfo *UserInfo `json:"userInfo"`
}
type Query struct {
// 文本信息
InputText struct{ Text string `json:"text"` } `json:"inputText"`
// 图片信息
InputImage struct{ Url string `json:"url"` } `json:"inputImage"`
// 音频信息
InputMedia struct{ Url string `json:"url"` } `json:"inputMedia"`
SelfInfo struct {
Location *Location `json:"location"`
} `json:"selfInfo"`
}
type Location struct {
City string `json:"city"`
Province string `json:"province"`
Street string `json:"street"`
}
type UserInfo struct {
ApiKey string `json:"apiKey"`
UserId string `json:"userId"`
}
|
/*
* @Author: tr3e
* @Date: 2019-11-26 20:50:43
* @Last Modified by: tr3e
* @Last Modified time: 2019-11-26 20:56:38
*/
package main
import "errors"
type Cipher interface {
Encrypt([]byte) []byte
Decrypt([]byte) []byte
Copy() Cipher
Reset()
}
var cipherMethod = map[string]func(string) (Cipher, error){
"plain": NewPlainCipher,
"xor": NewXorCipher,
}
func NewCipher(method, password string) (Cipher, error) {
cipher, ok := cipherMethod[method]
if !ok {
return nil, errors.New("Unsupported cipher method")
}
return cipher(password)
}
type PlainCipher struct {
}
func NewPlainCipher(string) (Cipher, error) {
return &PlainCipher{}, nil
}
func (c *PlainCipher) Encrypt(p []byte) []byte {
return p
}
func (c *PlainCipher) Decrypt(p []byte) []byte {
return p
}
func (c *PlainCipher) Copy() Cipher {
return c
}
func (c *PlainCipher) Reset() {
}
type XorCipher struct {
encInd int
decInd int
secret string
}
func NewXorCipher(secret string) (Cipher, error) {
return &XorCipher{secret: secret}, nil
}
func (c *XorCipher) Encrypt(p []byte) []byte {
for i := 0; i < len(p); i++ {
c.encInd %= len(c.secret)
p[i] ^= c.secret[c.encInd]
c.encInd++
}
return p
}
func (c *XorCipher) Decrypt(p []byte) []byte {
for i := 0; i < len(p); i++ {
c.decInd %= len(c.secret)
p[i] ^= c.secret[c.decInd]
c.decInd++
}
return p
}
func (c *XorCipher) Copy() Cipher {
return &XorCipher{secret: c.secret}
}
func (c *XorCipher) Reset() {
c.encInd = 0
c.decInd = 0
}
|
package lc
// Time: O(n)
// Benchmark: 8ms 6.4mb | 89% 69%
func getConcatenation(nums []int) []int {
return append(nums, nums...)
}
|
package queryme
import (
"fmt"
"errors"
"net/url"
"strconv"
"strings"
"time"
"unicode/utf8"
)
/*
predicates = predicate *("," predicate)
predicate = (not / and / or / eq / lt / le / gt / ge)
not = "not" "(" predicate ")"
and = "and" "(" predicates ")"
or = "or" "(" predicates ")"
eq = "eq" "(" field "," values ")"
lt = "lt" "(" field "," value ")"
le = "le" "(" field "," value ")"
gt = "gt" "(" field "," value ")"
ge = "ge" "(" field "," value ")"
fts = "fts" "(" field "," string ")"
values = value *("," value)
value = (null / boolean / number / string / date)
null = "null"
boolean = "true" / "false"
number = 1*(DIGIT / "." / "e" / "E" / "+" / "-")
string = "$" *(unreserved / pct-encoded)
date = 4DIGIT "-" 2DIGIT "-" 2DIGIT *1("T" 2DIGIT ":" 2DIGIT ":" 2DIGIT *1("." 3DIGIT) "Z")
fieldorders = *1(fieldorder *("," fieldorder))
fieldorder = *1"!" field
field = *(unreserved / pct-encoded)
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
pct-encoded = "%" HEXDIG HEXDIG
sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
query = *( pchar / "/" / "?" )
*/
var (
SortOrderSeparatorExpected error = errors.New("Expected seperator ',' after sorted order.")
IdentifierExpected error = errors.New("Expected identifier.")
ValueExpected error = errors.New("Expected value.")
EndOfStringExpected error = errors.New("Expected end of string.")
StringExpected error = errors.New("Expected string.")
OperatorExpected error = errors.New("Expected operator.")
UnexpectedEndOfPredicate error = errors.New("Unexpected end of predicate.")
UnexpectedEndOfSortOrders error = errors.New("Unexpected end of sort orders.")
characters []byte
)
func init() {
characters = make([]byte, 128)
characters[int('=')] = 1
characters[int('&')] = 1
characters[int('!')] = 2
characters[int('\'')] = 2
characters[int('(')] = 2
characters[int(')')] = 2
characters[int('*')] = 2
characters[int(',')] = 2
characters[int(';')] = 2
characters[int('/')] = 2
characters[int('?')] = 2
characters[int('@')] = 2
characters[int('$')] = 3
characters[int('+')] = 3
characters[int(':')] = 3
// 'pct-encoded' characters
characters[int('%')] = 4
// 'unreserved' characters
characters[int('-')] = 5
characters[int('.')] = 5
characters[int('_')] = 5
characters[int('~')] = 5
for i := int('0'); i <= int('9'); i++ {
characters[i] = 5
}
for i := int('a'); i <= int('z'); i++ {
characters[i] = 5
}
for i := int('A'); i <= int('Z'); i++ {
characters[i] = 5
}
}
func firstCharClass(s string) byte {
r, _ := utf8.DecodeRuneInString(s)
if r > 127 {
return 0
} else {
return characters[r]
}
}
func charClassDetector(min byte, max byte) func(r rune) bool {
return func(r rune) bool {
i := int(r)
if i > 127 {
return false
}
c := characters[i]
return c >= min && c <= max
}
}
// QueryString is a parsed query part of a URL.
type QueryString struct {
fields map[string]string
}
// NewFromRawQuery creates a new QueryString from a raw query string.
func NewFromRawQuery(rawQuery string) *QueryString {
qs := new(QueryString)
qs.fields = make(map[string]string)
for {
i := strings.IndexRune(rawQuery, '=')
if i == -1 {
break
}
name := rawQuery[:i]
rawQuery = rawQuery[i+1:]
i = strings.IndexFunc(rawQuery, charClassDetector(1, 1))
var value string
if i == -1 {
value = rawQuery
} else {
value = rawQuery[:i]
rawQuery = rawQuery[i+1:]
}
qs.fields[name] = value
if i == -1 {
break
}
}
return qs
}
// NewFromRawQuery creates a new QueryString from an existing URL object.
func NewFromURL(url *url.URL) *QueryString {
return NewFromRawQuery(url.RawQuery)
}
// Tests if specified name has been found in query string.
func (q *QueryString) Contains(name string) bool {
_, ok := q.fields[name]
return ok
}
// Returns raw query string value.
func (q *QueryString) Raw(name string) (string, bool) {
v, ok := q.fields[name]
return v, ok
}
// Predicate parses the given component of the query as a predicate, then returns it.
func (q *QueryString) Predicate(name string) (p Predicate, err error) {
defer func() {
if rec := recover(); rec != nil {
err = rec.(error)
}
}()
raw, ok := q.fields[name]
if !ok {
return nil, fmt.Errorf("field not found: %q", name)
}
p, raw = parsePredicate(raw)
if len(raw) != 0 {
p = nil
err = UnexpectedEndOfPredicate
}
return
}
// Predicate parses the given component of the query as a sort order, then returns it.
func (q *QueryString) SortOrder(name string) (os []*SortOrder, err error) {
defer func() {
if rec := recover(); rec != nil {
err = rec.(error)
}
}()
raw, ok := q.fields[name]
if !ok {
return nil, fmt.Errorf("field not found: %q", name)
}
os, raw = parseSortOrders(raw)
if len(raw) != 0 {
os = nil
err = UnexpectedEndOfSortOrders
}
return
}
func parsePredicate(s string) (p Predicate, n string) {
if len(s) == 0 {
panic(OperatorExpected)
}
var op string
op, n = parseIdentifier(s)
n = parseLiteral(n, "(")
var f string
var ps []Predicate
var vs []Value
var v Value
switch op {
case "not":
var operand Predicate
operand, n = parsePredicate(n)
p = Not{operand}
case "and":
ps, n = parsePredicates(n)
p = And(ps)
case "or":
ps, n = parsePredicates(n)
p = Or(ps)
case "eq":
f, n = parseIdentifier(n)
n = parseLiteral(n, ",")
vs, n = parseValues(n)
p = Eq{Field(f), vs}
case "gt":
f, n = parseIdentifier(n)
n = parseLiteral(n, ",")
v, n = parseValue(n)
p = Gt{Field(f), v}
case "ge":
f, n = parseIdentifier(n)
n = parseLiteral(n, ",")
v, n = parseValue(n)
p = Ge{Field(f), v}
case "lt":
f, n = parseIdentifier(n)
n = parseLiteral(n, ",")
v, n = parseValue(n)
p = Lt{Field(f), v}
case "le":
f, n = parseIdentifier(n)
n = parseLiteral(n, ",")
v, n = parseValue(n)
p = Le{Field(f), v}
case "fts":
f, n = parseIdentifier(n)
n = parseLiteral(n, ",")
s, n = parseString(n)
p = Fts{Field(f), s}
default:
panic(fmt.Errorf("Invalid operator: %q", op))
}
n = parseLiteral(n, ")")
return
}
func parsePredicates(s string) (ps []Predicate, n string) {
ps = make([]Predicate, 0, 4)
if len(s) > 0 && firstCharClass(s) > 2 {
n = s
for {
var operand Predicate
operand, n = parsePredicate(n)
ps = append(ps, operand)
if len(n) > 0 && n[0] == ',' {
n = n[1:]
} else {
break
}
}
}
return
}
func ParseValues(s string) ([]Value, error) {
vs, n := parseValues(s)
if n != "" {
return vs, EndOfStringExpected
}
return vs, nil
}
func parseValues(s string) (vs []Value, n string) {
vs = make([]Value, 0, 4)
if len(s) > 0 && firstCharClass(s) > 2 {
n = s
for {
var operand interface{}
operand, n = parseValue(n)
vs = append(vs, operand)
if len(n) > 0 && n[0] == ',' {
n = n[1:]
} else {
break
}
}
}
return
}
func parseString(s string) (v string, n string) {
if len(s) == 0 || s[0] != '$' {
panic(StringExpected)
}
s = s[1:]
l := strings.IndexFunc(s, charClassDetector(1, 2))
if l == -1 {
l = len(s)
}
var err error
if v, err = url.QueryUnescape(s[:l]); err != nil {
panic(err)
}
n = s[l:]
return
}
func ParseValue(s string) (Value, error) {
v, n := parseValue(s)
if n != "" {
return v, EndOfStringExpected
}
return v, nil
}
func parseValue(s string) (v Value, n string) {
if len(s) == 0 {
panic(ValueExpected)
}
r, l := utf8.DecodeRuneInString(s)
switch(r) {
case 'n':
n = parseLiteral(s, "null")
v = nil
case 't':
n = parseLiteral(s, "true")
v = true
case 'f':
n = parseLiteral(s, "false")
v = false
case '$':
v, n = parseString(s)
default:
if l = strings.IndexFunc(s, charClassDetector(1, 2)); l == -1 {
l = len(s)
}
if (l == 10 || ((l == 20 || (l == 24 && s[19] == '.')) && s[10] == 'T' && s[13] == ':' && s[16] == ':' && s[l-1] == 'Z')) && s[4] == '-' && s[7] == '-' {
var err error
var yr, mo, dy, hr, mn, sc, ms int64 = 0, 0, 0, 0, 0, 0, 0
if yr, err = strconv.ParseInt(s[0:4], 10, 32); err != nil {
panic(err)
}
if mo, err = strconv.ParseInt(s[5:7], 10, 32); err != nil {
panic(err)
}
if dy, err = strconv.ParseInt(s[8:10], 10, 32); err != nil {
panic(err)
}
if l >= 20 {
if hr, err = strconv.ParseInt(s[11:13], 10, 32); err != nil {
panic(err)
}
if mn, err = strconv.ParseInt(s[14:16], 10, 32); err != nil {
panic(err)
}
if sc, err = strconv.ParseInt(s[17:19], 10, 32); err != nil {
panic(err)
}
if l == 24 {
if ms, err = strconv.ParseInt(s[20:23], 10, 32); err != nil {
panic(err)
}
}
}
v = time.Date(int(yr), time.Month(mo), int(dy), int(hr), int(mn), int(sc), int(ms) * 1000000, time.UTC)
} else {
if f, err := strconv.ParseFloat(s[:l], 64); err != nil {
panic(err)
} else {
v = f
}
}
n = s[l:]
}
return
}
func parseLiteral(s string, expected string) (n string) {
if len(s) < len(expected) || s[:len(expected)] != expected {
panic(fmt.Errorf("expected: %q", expected))
}
return s[len(expected):]
}
func parseSortOrders(s string) (os []*SortOrder, n string) {
os = make([]*SortOrder, 0, 4)
if len(s) > 0 {
for {
var o *SortOrder
o, s = parseSortOrder(s)
os = append(os, o)
if len(s) == 0 {
break
}
if r, l := utf8.DecodeRuneInString(s); r != ',' {
panic(SortOrderSeparatorExpected)
} else {
s = s[l:]
}
}
}
n = s
return
}
func parseSortOrder(s string) (o *SortOrder, n string) {
o = new(SortOrder)
if r, _ := utf8.DecodeRuneInString(s); r == '!' {
s = s[1:]
} else {
o.Ascending = true
}
f, n := parseIdentifier(s)
o.Field = Field(f)
return
}
func ParseIdentifier(s string) (Value, error) {
v, n := parseIdentifier(s)
if n != "" {
return v, EndOfStringExpected
}
return v, nil
}
func parseIdentifier(s string) (id string, n string) {
if len(s) == 0 {
panic(IdentifierExpected)
}
i := strings.IndexFunc(s, charClassDetector(1, 3))
if i == 0 {
panic(IdentifierExpected)
}
if i == -1 {
n = ""
} else {
n = s[i:]
s = s[:i]
}
var err error
if id, err = url.QueryUnescape(s); err != nil {
panic(err)
}
return
}
|
// Copyright (C) 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 writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package record
import (
"context"
"encoding/json"
"os"
"reflect"
"github.com/google/gapid/core/event"
"github.com/google/gapid/core/log"
)
// jsonFileType is an implementation of fileType that stores it's records in json format.
type jsonFileType struct{}
type jsonHandler struct {
f *os.File
encoder *json.Encoder
null reflect.Type
}
type jsonReader struct {
decoder *json.Decoder
null reflect.Type
}
func (jsonFileType) Ext() string { return ".json" }
func (jsonFileType) Open(ctx context.Context, f *os.File, null interface{}) (LedgerInstance, error) {
t := reflect.TypeOf(null).Elem()
if _, err := json.Marshal(reflect.New(t)); err != nil {
return nil, log.Err(ctx, nil, "Cannot create json ledger with non marshalable type")
}
return &jsonHandler{f: f, encoder: json.NewEncoder(f), null: t}, nil
}
func (h *jsonHandler) Write(ctx context.Context, record interface{}) error {
return h.encoder.Encode(record)
}
func (h *jsonHandler) Reader(ctx context.Context) event.Source {
return &jsonReader{decoder: json.NewDecoder(&readAt{f: h.f}), null: h.null}
}
func (h *jsonHandler) Close(ctx context.Context) {
h.f.Close()
}
func (h *jsonHandler) New(ctx context.Context) interface{} {
return reflect.New(h.null)
}
func (r *jsonReader) Next(ctx context.Context) interface{} {
message := reflect.New(r.null)
err := r.decoder.Decode(message)
log.E(ctx, "Corrupt record file. Error: %v", err)
return message
}
func (h *jsonReader) Close(ctx context.Context) {}
|
package manager
import (
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
)
// 全部,包括子路径下文件
type Name struct {
Num int
Name string
IsDir bool
}
type Lists struct {
Num int
Href string
Name string
IsDir bool
}
type Img struct{
Num int
Name string
}
func ListSingle(pwd string)(result []Name,errs error) {
var Names []Name
//获取文件或目录相关信息
fileInfoList,_ := ioutil.ReadDir(pwd)
//fmt.Println(len(fileInfoList))
for i := range fileInfoList {
Names = append(Names,Name{
Num: i,
Name: fileInfoList[i].Name(),
IsDir: fileInfoList[i].IsDir(),
})//打印当前文件或目录下的文件或目录名
}
//fmt.Println(fileInfoList[0].Name())
return Names,nil
}
func FileInfo(pwd string)(modTime string ,size int64,mode os.FileMode) {
fileInfo,err:=os.Stat(pwd)
if err!=nil {
return
}
modTime = fileInfo.ModTime().Format("2006-01-02 15:04:05")
size = fileInfo.Size()
mode = fileInfo.Mode() //权限
return modTime,size,mode
}
//判断文件(夹)是否存在
func IsExistFileOrDir (path string)(types bool,exist bool) {
s, err := os.Stat(path)
if err != nil {
return false,false
}else {
return s.IsDir(),true
}
}
func ImgInSameDir(pwd string)[]Img{
var Imgs []Img
fileInfoList,err := ioutil.ReadDir(pwd)
if err!=nil {
fmt.Println(err)
}
for i := range fileInfoList {
h:=pwd+"/"+fileInfoList[i].Name()
//fmt.Println(h)
types,exist:=IsExistFileOrDir(h)
//fmt.Println(exist,types)
if exist&&!types {
var a =strings.ToLower(path.Ext(h))
//fmt.Println(a)
if a==".jpg"||a==".png"||a==".gif" {
Imgs = append(Imgs,Img{
Num: i,
Name: fileInfoList[i].Name(),
})
}
}
}
fmt.Println(Imgs)
return Imgs
}
func List(dirpath ,query string) ([]Lists, error) {
var list []Lists
err := filepath.Walk(dirpath,
func(ppath string, f os.FileInfo, err error) error { //ppath=path,区分path包
if f == nil {
return err
} else {
var name = path.Base(f.Name())
if strings.Contains(name, query) {
list =append(list,Lists{
Num: len(list),
Name: name,
Href: ppath,
IsDir: f.IsDir(),
})
return nil
}
return nil
}
})
return list,err
} |
package internal
// ContextKey is just an empty struct. It exists so context values can be
// an immutable public variable with a unique type. It's immutable
// because nobody else can create a ContextKey, being unexported.
type ContextKey struct{}
|
package main
import "fmt"
func main() {
ch := make(chan int, 2)
ch <- 1
ch <- 2
//ch <- 3 // fatal error: all goroutines are asleep - deadlock!
fmt.Println(<-ch)
fmt.Println(<-ch)
//fmt.Println(<-ch)
/*
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
main.main()
/Users/kazuhirosera/github/oss/a-tour-of-go/concurrency/bufferred-channels.go:11 +0x272
Process finished with exit code 0
*/
}
|
/*
Copyright © 2021 Damien Coraboeuf <damien.coraboeuf@nemerosa.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package cmd
import (
"errors"
"regexp"
"strconv"
"strings"
"github.com/spf13/cobra"
client "ontrack-cli/client"
config "ontrack-cli/config"
)
// validateMetricsCmd represents the validateMetrics command
var validateMetricsCmd = &cobra.Command{
Use: "metrics",
Short: "Validation with metrics data",
Long: `Validation with metrics data.
For example:
ontrack-cli validate -p PROJECT -b BRANCH -n BUILD -v VALIDATION metrics --metric name1=value1 --metric name2=value2
An alternative syntax is:
ontrack-cli validate -p PROJECT -b BRANCH -n BUILD -v VALIDATION metrics --metrics name1=value1,name2=value2
`,
RunE: func(cmd *cobra.Command, args []string) error {
project, err := cmd.Flags().GetString("project")
if err != nil {
return err
}
branch, err := cmd.Flags().GetString("branch")
if err != nil {
return err
}
branch = NormalizeBranchName(branch)
build, err := cmd.Flags().GetString("build")
if err != nil {
return err
}
validation, err := cmd.Flags().GetString("validation")
if err != nil {
return err
}
description, err := cmd.Flags().GetString("description")
if err != nil {
return err
}
runInfo, err := GetRunInfo(cmd)
if err != nil {
return err
}
// List of metrics
var metricList = []metric{}
// Adding from the `metric` flags
metricArgs, err := cmd.Flags().GetStringSlice("metric")
for _, value := range metricArgs {
name, metricValue, err := parseMetric(value)
if err != nil {
return err
}
metricList = append(metricList, metric{
Name: name,
Value: metricValue,
})
}
// Adding from the `metrics` flag
metricsArg, err := cmd.Flags().GetString("metrics")
if err != nil {
return err
}
if metricsArg != "" {
metricsArgTokens := strings.Split(metricsArg, ",")
for _, value := range metricsArgTokens {
name, metricValue, err := parseMetric(value)
if err != nil {
return err
}
metricList = append(metricList, metric{
Name: name,
Value: metricValue,
})
}
}
// Get the configuration
cfg, err := config.GetSelectedConfiguration()
if err != nil {
return err
}
// Mutation payload
var payload struct {
ValidateBuildWithMetrics struct {
Errors []struct {
Message string
}
}
}
// Runs the mutation
if err := client.GraphQLCall(cfg, `
mutation ValidateBuildWithMetrics(
$project: String!,
$branch: String!,
$build: String!,
$validationStamp: String!,
$description: String!,
$runInfo: RunInfoInput,
$metrics: [MetricsEntryInput!]!
) {
validateBuildWithMetrics(input: {
project: $project,
branch: $branch,
build: $build,
validation: $validationStamp,
description: $description,
runInfo: $runInfo,
metrics: $metrics
}) {
errors {
message
}
}
}
`, map[string]interface{}{
"project": project,
"branch": branch,
"build": build,
"validationStamp": validation,
"description": description,
"runInfo": runInfo,
"metrics": metricList,
}, &payload); err != nil {
return err
}
// Checks for errors
if err := client.CheckDataErrors(payload.ValidateBuildWithMetrics.Errors); err != nil {
return err
}
// OK
return nil
},
}
func parseMetric(value string) (string, float64, error) {
re := regexp.MustCompile(`^(.+)=(\d+(\.\d+)?)$`)
match := re.FindStringSubmatch(value)
if match == nil {
return "", 0, errors.New("Metric " + value + " must match name=number[.number]")
}
name := match[1]
metric, err := strconv.ParseFloat(match[2], 64)
if err != nil {
return "", 0, err
}
return name, metric, nil
}
func init() {
validateCmd.AddCommand(validateMetricsCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// validateMetricsCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// validateMetricsCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
validateMetricsCmd.Flags().StringSliceP("metric", "m", []string{}, "List of metric, each value being provided like 'name=value'")
validateMetricsCmd.Flags().String("metrics", "", "Comma-separated list of metric, each value being provided like 'name=value'")
// Run info arguments
InitRunInfoCommandFlags(validateMetricsCmd)
}
type metric struct {
Name string `json:"name"`
Value float64 `json:"value"`
}
|
package dao
import (
"github.com/jinzhu/gorm"
"github.com/luxingwen/secret-game/conf"
"github.com/luxingwen/secret-game/model"
"context"
"github.com/BurntSushi/toml"
_ "github.com/jinzhu/gorm/dialects/mysql"
log "github.com/sirupsen/logrus"
"io/ioutil"
"time"
)
const (
TableTeam = "teams"
TableTeamUser = "team_user_maps"
TableTeamTest = "team_tests"
TableTeamTestLog = "team_test_logs"
TableSubject = "subjects"
TableWxUser = "wx_users"
TableWxCode = "wx_codes"
HEADER_URL = "https://sustech.osidea.tech/api/"
)
var dao *Dao
func init() {
var conf conf.Conf
b, err := ioutil.ReadFile("conf/app.conf")
if err != nil {
panic(err)
}
if _, err := toml.Decode(string(b), &conf); err != nil {
// handle error
panic(err)
}
dao = NewDao(&conf)
dao.DB.LogMode(true)
dao.DB.AutoMigrate(&model.Team{}, &model.TeamUserMap{}, &model.Subject{}, &model.TeamTest{}, &model.TeamTestLog{}, &model.WxUser{}, &model.WxCode{})
}
func GetDao() *Dao {
return dao
}
// Dao dao
type Dao struct {
c *conf.Conf
DB *gorm.DB
}
func NewDao(c *conf.Conf) *Dao {
return &Dao{
c: c,
DB: NewMySQL(c.DB),
}
}
// Ping verify server is ok.
func (d *Dao) Ping(c context.Context) (err error) {
if err = d.DB.DB().Ping(); err != nil {
log.Error("dao.cloudDB.Ping() error(%v)", err)
return
}
return
}
// Close close the resource.
func (d *Dao) Close() {
d.DB.Close()
}
func NewMySQL(c *conf.DBConfig) (db *gorm.DB) {
db, err := gorm.Open("mysql", c.DSN)
if err != nil {
log.Error("db dsn(%s) error: %v", c.DSN, err)
panic(err)
}
db.DB().SetMaxIdleConns(c.Idle)
db.DB().SetMaxOpenConns(c.Active)
db.DB().SetConnMaxLifetime(time.Duration(c.IdleTimeout) / time.Second)
return
}
|
package gotification_test
import (
"github.com/mikegw/gotification/pkg/notification"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"net/http/httptest"
"strings"
"io/ioutil"
"encoding/json"
)
type savedNotification struct {
Payload string
ID string
}
type errorResponse struct {
Message string
}
type mockPersistor struct {
Persisted bool
}
func (m *mockPersistor) Persist(notification.Model) (string, error) {
m.Persisted = true
return "some id", nil
}
type creationResult struct {
ResponseBody []byte
ResponseCode int
Persisted bool
CreationError error
}
func createNotification(notificationString string) (creationResult) {
/*--- Setup ---*/
body := strings.NewReader(notificationString)
mockRequest := httptest.NewRequest("POST", "http://example.com/foo", body)
responseRecorder := httptest.NewRecorder()
persistor := mockPersistor{}
/*--- Run Code ---*/
_, err := notification.Create(responseRecorder, mockRequest, &persistor)
/*--- Build Result ---*/
result := creationResult{
Persisted: persistor.Persisted,
CreationError: err,
}
if err == nil {
response := responseRecorder.Result()
result.ResponseBody, _ = ioutil.ReadAll(response.Body)
result.ResponseCode = response.StatusCode
}
return result
}
var _ = Describe("CreateNotification", func() {
Context("with valid input", func() {
var result creationResult
var responseNotification savedNotification
BeforeEach(func() {
result = createNotification("{\"payload\":\"Hi\"}")
json.Unmarshal(result.ResponseBody, &responseNotification)
})
It("persists the data", func() {
Expect(result.Persisted).To(BeTrue())
})
It("returns a 200 response", func() {
Expect(result.ResponseCode).To(Equal(200))
})
It("returns the notification", func() {
Expect(responseNotification.Payload).To(Equal("Hi"))
})
It("adds an ID to the notification", func() {
Expect(responseNotification.ID).NotTo(BeNil())
})
})
Context("with invalid json", func() {
var result creationResult
var jsonResponse errorResponse
BeforeEach(func() {
result = createNotification("totally a notification")
json.Unmarshal(result.ResponseBody, &jsonResponse)
})
It("returns an error", func() {
Expect(jsonResponse.Message).To(Equal("Invalid JSON"))
})
})
Context("with invalid notification", func() {
var result creationResult
var jsonResponse errorResponse
BeforeEach(func() {
result = createNotification("{\"key\":\"value\"}")
json.Unmarshal(result.ResponseBody, &jsonResponse)
})
It("returns an error", func() {
Expect(jsonResponse.Message).To(Equal("Missing JSON parameter: payload"))
})
})
})
|
package main
import (
"flag"
"fmt"
"github.com/tarm/serial"
"os"
"time"
)
func main() {
flag.Parse()
if flag.NArg() < 2 {
fmt.Fprintf(os.Stderr, "usage: %s <port> <filename.hex>\n", os.Args[0])
os.Exit(2)
}
portConfig := &serial.Config{
Name: flag.Arg(0),
Baud: 9600,
ReadTimeout: time.Second,
}
port, err := serial.OpenPort(portConfig)
if err != nil {
fmt.Fprintf(os.Stderr, "error: %s\n", err.Error())
os.Exit(1)
}
defer port.Close()
t := Transport{port}
err = t.Sync()
if err != nil {
fmt.Fprintf(os.Stderr, "error: %s\n", err.Error())
os.Exit(1)
}
err = LoadFile(t, flag.Arg(1))
if err != nil {
fmt.Fprintf(os.Stderr, "error: %s\n", err.Error())
os.Exit(1)
}
}
|
// Copyright © 2016 NAME HERE <EMAIL ADDRESS>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"fmt"
"sync"
"github.com/chanwit/belt/ssh"
"github.com/chanwit/belt/util"
"github.com/spf13/cobra"
)
// hostnameCmd represents the hostname command
var hostnameCmd = &cobra.Command{
Use: "hostname",
Short: "correct hostnames",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: func(cmd *cobra.Command, args []string) {
ips := CacheIP()
nodes := []string{}
for i := 0; i < len(args); i++ {
nodes = append(nodes, util.Generate(args[i])...)
}
MAX := 30
num := len(nodes)
loop := num / MAX
rem := num % MAX
if rem != 0 {
loop++
}
for i := 1; i <= loop; i++ {
var wg sync.WaitGroup
for j := 0; j < MAX; j++ {
offset := (i-1)*MAX + j
if offset < len(nodes) {
node := nodes[offset]
wg.Add(1)
go func(node string) {
defer wg.Done()
ip := ips[node]
sshcli, err := ssh.NewNativeClient(
util.DegitalOcean.SSHUser(), ip, util.DegitalOcean.SSHPort(),
&ssh.Auth{Keys: util.DefaultSSHPrivateKeys()})
if err != nil {
fmt.Println(err.Error())
return
}
sshcli.Output("hostname " + node)
sshcli.Output("service docker restart")
fmt.Println(node)
}(node)
}
}
wg.Wait()
}
},
}
func init() {
RootCmd.AddCommand(hostnameCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// hostnameCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// hostnameCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
|
package controller
import (
"context"
"database/sql"
"log"
"github.com/tonouchi510/goa2-sample/gen/admin"
)
// Admin service example implementation.
// The example methods log the requests and return zero values.
type adminsrvc struct {
logger *log.Logger
DB *sql.DB
}
// NewAdmin returns the Admin service implementation.
func NewAdmin(logger *log.Logger, db *sql.DB) admin.Service {
return &adminsrvc{logger, db}
}
// Statistic of users
func (s *adminsrvc) UserNumber(ctx context.Context) (res *admin.Goa2SampleAdminUserNumber, err error) {
res = &admin.Goa2SampleAdminUserNumber{}
s.logger.Print("admin.user_stats")
st1 := "2018/11"
st2 := "2018/12"
st3 := "2019/01"
c := "key"
size := "value"
// StatsPlanetController_Bar: end_implement
res = &admin.Goa2SampleAdminUserNumber{
Data: []*admin.Data{
&admin.Data{Key:&st1, Value:1},
&admin.Data{Key:&st2, Value:2},
&admin.Data{Key:&st3, Value:5},
},
X: "key",
Y: "value",
Color: &c,
Size: &size,
Guide: &admin.StatsGuideType{
X: &admin.StatsLabelType{Label: "年月"},
Y: &admin.StatsLabelType{Label: "人数"},
},
}
return
}
// List all stored users
func (s *adminsrvc) AdminListUser(ctx context.Context) (res admin.Goa2SampleAdminUserCollection, err error) {
res = admin.Goa2SampleAdminUserCollection{}
s.logger.Print("admin.Admin list user")
rows, err := s.DB.Query("SELECT * FROM users")
defer rows.Close()
if err != nil {
return
}
for rows.Next() {
var id, name, email string
var createdAt, updatedAt string
var deletedAt *string
err = rows.Scan(&id, &name, &email, &createdAt, &updatedAt, &deletedAt)
if err != nil {
return
}
user := &admin.Goa2SampleAdminUser{
ID: id,
Name: name,
Email: email,
CreatedAt: createdAt,
UpdatedAt: updatedAt,
DeletedAt: deletedAt,
}
res = append(res, user)
}
return
}
// Show user by ID
func (s *adminsrvc) AdminGetUser(ctx context.Context, p *admin.GetUserPayload) (res *admin.Goa2SampleAdminUser, err error) {
res = &admin.Goa2SampleAdminUser{}
s.logger.Print("admin.Admin get user")
var id, name, email string
var createdAt, updatedAt string
var deletedAt *string
err = s.DB.QueryRow("SELECT * FROM users WHERE id=?", p.ID).Scan(&id, &name, &email, &createdAt, &updatedAt, &deletedAt)
if err != nil {
return
}
res = &admin.Goa2SampleAdminUser{
ID: id,
Name: name,
Email: email,
CreatedAt: createdAt,
UpdatedAt: updatedAt,
DeletedAt: deletedAt,
}
return
}
// Add new user and return its ID.
func (s *adminsrvc) AdminCreateUser(ctx context.Context, p *admin.CreateUserPayload) (res string, err error) {
s.logger.Print("admin.Admin create user")
stmt, err := s.DB.Prepare("INSERT INTO users(id, name, email) VALUES(?,?,?)")
defer stmt.Close()
if err != nil {
return
}
_, err = stmt.Exec(p.ID, p.Name, p.Email)
if err != nil {
return
}
s.logger.Printf("INSERT: ID: %s | Name: %s | Email: %s", p.ID, p.Name, p.Email)
res = p.ID
return
}
// Update user item.
func (s *adminsrvc) AdminUpdateUser(ctx context.Context, p *admin.UpdateUserPayload) (res *admin.Goa2SampleAdminUser, err error) {
res = &admin.Goa2SampleAdminUser{}
s.logger.Print("admin.Admin update user")
var stmt *sql.Stmt
if p.Name != nil && p.Email != nil {
stmt, err = s.DB.Prepare("UPDATE users SET name=?, email=? WHERE id=?")
_, err = stmt.Exec(p.Name, p.Email, p.ID)
} else if p.Name != nil {
stmt, err = s.DB.Prepare("UPDATE users SET name=? WHERE id=?")
_, err = stmt.Exec(p.Name, p.ID)
} else if p.Email != nil {
stmt, err = s.DB.Prepare("UPDATE users SET email=? WHERE id=?")
_, err = stmt.Exec(p.Email, p.ID)
}
if err != nil {
return
}
defer stmt.Close()
var id, name, email string
var createdAt, updatedAt string
var deletedAt *string
err = s.DB.QueryRow("SELECT * FROM users WHERE id=?", p.ID).Scan(&id, &name, &email, &createdAt, &updatedAt, &deletedAt)
if err != nil {
return
}
res = &admin.Goa2SampleAdminUser{
ID: id,
Name: name,
Email: email,
CreatedAt: createdAt,
UpdatedAt: updatedAt,
DeletedAt: deletedAt,
}
s.logger.Printf("UPDATE: ID: %s | Name: %s | Email: %s", id, name, email)
return
}
// Delete user by id.
func (s *adminsrvc) AdminDeleteUser(ctx context.Context, p *admin.DeleteUserPayload) (err error) {
s.logger.Print("admin.Admin delete user")
stmt, err := s.DB.Prepare("DELETE FROM users WHERE id=?")
defer stmt.Close()
if err != nil {
return
}
_, err = stmt.Exec(p.ID)
if err != nil {
return
}
s.logger.Printf("DELETE: Id: %s", p.ID)
return
}
|
package main
import (
"fmt"
"github.com/todostreaming/fifo"
)
type Segment struct {
Name string
Dur float64
}
func main() {
ts_queue := fifo.NewQueue()
ts_queue.Add(&Segment{"stream1.ts", 10.56})
ts_queue.Add(&Segment{"stream2.ts", 9.02})
ts_queue.Add(&Segment{"stream3.ts", 11.00})
for q := ts_queue.Next(); q != nil; q = ts_queue.Next() {
p := q.(*Segment)
fmt.Printf("Name: %s \t Dur: %.2f\n", p.Name, p.Dur)
}
/*
fmt.Printf("1)Len=%d\n",ts_queue.Len())
ts_queue.Add("segment1.ts")
ts_queue.Add("segment2.ts")
ts_queue.Add("segment3.ts")
for q := ts_queue.Next(); q != nil; q = ts_queue.Next() {
fmt.Println(q)
}
*/
// total := ts_queue.Len()
// for q:=0; q < total; q++ {
// fmt.Println(ts_queue.Next())
// }
}
|
package solutions
func twoSum(nums []int, target int) []int {
lookupMap := make(map[int]int)
for i, value := range nums {
j, complement := lookupMap[-value]
if complement {
return []int{j, i}
}
lookupMap[value - target] = i
}
return []int{}
} |
package moxings
type Yinpinshanchuxins struct {
Id int
Xuliehao string `gorm:"not null;DEFAULT:0"`
Yishanchu int64 `gorm:"not null;DEFAULT:0"`
Shanchubiaoji int64 `gorm:"not null;DEFAULT:0"`
}
func (Yinpinshanchuxins) TableName() string {
return "Yinpinshanchuxins"
}
|
package main
//944. 删列造序
//给你由 n 个小写字母字符串组成的数组 strs,其中每个字符串长度相等。
//
//这些字符串可以每个一行,排成一个网格。例如,strs = ["abc", "bce", "cae"] 可以排列为:
//
//abc
//bce
//cae
//你需要找出并删除 不是按字典序升序排列的 列。在上面的例子(下标从 0 开始)中,列 0('a', 'b', 'c')和列 2('c', 'e', 'e')都是按升序排列的,而列 1('b', 'c', 'a')不是,所以要删除列 1 。
//
//返回你需要删除的列数。
//
//
//示例 1:
//
//输入:strs = ["cba","daf","ghi"]
//输出:1
//解释:网格示意如下:
//cba
//daf
//ghi
//列 0 和列 2 按升序排列,但列 1 不是,所以只需要删除列 1 。
//示例 2:
//
//输入:strs = ["a","b"]
//输出:0
//解释:网格示意如下:
//a
//b
//只有列 0 这一列,且已经按升序排列,所以不用删除任何列。
//示例 3:
//
//输入:strs = ["zyx","wvu","tsr"]
//输出:3
//解释:网格示意如下:
//zyx
//wvu
//tsr
//所有 3 列都是非升序排列的,所以都要删除。
//
//
//提示:
//
//n == strs.length
//1 <= n <= 100
//1 <= strs[i].length <= 1000
//strs[i] 由小写英文字母组成
func minDeletionSize(strs []string) int {
n := len(strs)
m := len(strs[0])
var result int
for i := 0; i < m; i++ {
for j := 0; j < n-1; j++ {
if strs[j+1][i] < strs[j][i] {
result++
break
}
}
}
return result
}
func main() {
println(minDeletionSize([]string{"rrjk", "furt", "guzm"}))
}
|
package Sieve
import "math"
func Sieve(n int) (result []int) {
var start []int
for i := 2; i <= n; i++ {
start = append(start, i)
}
p := int(math.Floor(math.Sqrt(float64(n))))
for i := 2; i <= p; i++ {
if start[i-2] != 0 {
j := start[i-2] * start[i-2]
for j <= n {
start[j-2] = 0
j += i
}
}
}
for i := 2; i <= n; i++ {
if start[i-2] != 0 {
result = append(result, start[i-2])
}
}
return
}
|
// Copyright 2018-present The Yumcoder Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
// Author: yumcoder (omid.jn@gmail.com)
//
package one
import (
"sync"
"testing"
)
type onceFunCall int
func (o *onceFunCall) Increment() {
*o++
}
func Test_once(t *testing.T) {
var incFn onceFunCall
once := &sync.Once{}
once.Do(incFn.Increment)
once.Do(incFn.Increment)
once.Do(incFn.Increment)
t.Log(incFn)
}
|
package main
import (
"flag"
"os"
"net/http"
"fmt"
"log"
"strings"
)
var (
listenPort int
redirectCode int
)
func init() {
flagset := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
flagset.IntVar(&listenPort, "port", 8080, "The port to listen on")
flagset.IntVar(&redirectCode, "status", 301, "The HTTP status code to send")
flagset.Parse(os.Args[1:])
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
host := strings.Split(r.Host, ":")[0]
path := r.URL.Path
query := ""
if len(r.URL.RawQuery) > 0 {
query = fmt.Sprint("?", r.URL.RawQuery)
}
redirectURI := fmt.Sprint("https://", host, path, query)
http.Redirect(w, r, redirectURI, redirectCode)
})
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", listenPort), nil))
}
|
package svr
import (
"github.com/gin-gonic/gin"
"go4eat-api/pkg/svr"
"go4eat-api/svc"
"go4eat-api/svr/ctx"
"go4eat-api/svr/domain"
"go4eat-api/svr/domain/orders"
"go4eat-api/svr/domain/places"
"go4eat-api/svr/domain/users"
)
func router(container *svc.Container) svr.Router {
return func(engine *gin.Engine) {
engine.Use(cors)
engine.Use(ctx.ContextData(container))
engine.Use(auth)
engine.GET("/Ping", domain.Ping)
engine.POST("/Users/GetAuthenticationStatus", users.GetAuthenticationStatus)
engine.POST("/Users/GetUsernameAvailability", users.GetUsernameAvailability)
engine.POST("/Users/CreateUser", users.CreateUser)
engine.POST("/Users/AuthenticateUser", users.AuthenticateUser)
engine.POST("/Places/GetPlaces", places.GetPlaces)
engine.POST("/Orders/CreateOrder", orders.CreateOrder)
engine.POST("/Orders/GetOrder", orders.GetOrder)
engine.POST("/Orders/AddCustomer", orders.AddCustomer)
}
}
|
package db
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/gomodule/redigo/redis"
)
const (
testConfigName = "/tmp/config.example.json"
testDbIndex = 1 // forced overwrite db index for tests
)
var (
cipherKey = []byte{
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
}
)
type testCfg struct {
Redis *Cfg `json:"redis"`
}
func readCfg() (*redis.Pool, error) {
jsonData, err := ioutil.ReadFile(testConfigName)
if err != nil {
return nil, err
}
c := &testCfg{}
err = json.Unmarshal(jsonData, c)
if err != nil {
return nil, err
}
c.Redis.Db = testDbIndex
c.Redis.MaxCon = 255
pool, err := GetDbPool(c.Redis)
if err != nil {
return nil, err
}
return pool, nil
}
func TestGetDbPool(t *testing.T) {
jsonData, err := ioutil.ReadFile(testConfigName)
if err != nil {
t.Fatal(err)
}
c := &testCfg{}
err = json.Unmarshal(jsonData, c)
if err != nil {
t.Fatal(err)
}
c.Redis.Db = testDbIndex
c.Redis.Timeout = -1
_, err = GetDbPool(c.Redis)
if err == nil {
t.Errorf("expected error")
}
c.Redis.Timeout = 10
c.Redis.IndleCon = 0
_, err = GetDbPool(c.Redis)
if err == nil {
t.Errorf("expected error")
}
c.Redis.IndleCon = 1
c.Redis.Db = -1
_, err = GetDbPool(c.Redis)
if err == nil {
t.Errorf("expected error")
}
// success case
pool, err := readCfg()
if err != nil {
t.Fatal(err)
}
conn := pool.Get()
if !IsOk(conn) {
t.Error("db check is not ok")
}
err = conn.Close()
if err != nil {
t.Errorf("close connection errror: %v", err)
}
err = pool.Close()
if err != nil {
t.Errorf("close pool errror: %v", err)
}
}
func TestItem_New(t *testing.T) {
const (
maxTTL = 300
maxTimes = 10
)
cases := [][4]string{
// content, ttl, times, ok
{"test", "100", "1", "1"},
{"test", "300", "1", "1"},
{"test", "330", "1", "0"},
{"test", "0", "1", "0"},
{"test", "100", "0", "0"},
{"test", "100", "11", "0"},
{"test", "100", "10", "1"},
{"", "100", "10", "0"},
{"test", "bad", "10", "0"},
{"test", "10", "bad", "0"},
{"test", "", "10", "0"},
{"test", "10", "", "0"},
{"", "", "", "0"},
}
for i, v := range cases {
values := url.Values{}
values.Set("content", v[0])
values.Set("ttl", v[1])
values.Set("times", v[2])
r := httptest.NewRequest("POST", "/", strings.NewReader(values.Encode()))
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
item, err := New(r, maxTTL, maxTimes)
if v[3] == "1" {
if err != nil {
t.Errorf("unexpected error for case=%v: %v", i, err)
} else {
if item.Content != v[0] {
t.Errorf("failed case=%v, content=%v", i, item.Content)
}
}
} else {
if err == nil {
t.Errorf("expected error for case=%v", i)
}
}
}
}
func TestItem_GetURL(t *testing.T) {
key := "abc"
uri := "http://example.com"
r := httptest.NewRequest("POST", uri, nil)
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
item := &Item{Content: "test", TTL: 60, Times: 1, Key: key}
expected := fmt.Sprintf("%v/%v", uri, key)
if u := item.GetURL(r, false); u.String() != expected {
t.Error("failed non-secure check", u.String())
}
uri = "https://example.com"
expected = fmt.Sprintf("%v/%v", uri, key)
if u := item.GetURL(r, true); u.String() != expected {
t.Error("failed secure check", u.String())
}
}
func TestItem_Save(t *testing.T) {
pool, err := readCfg()
if err != nil {
t.Fatal(err)
}
conn := pool.Get()
defer func() {
err = conn.Close()
if err != nil {
t.Errorf("close connection errror: %v", err)
}
err = pool.Close()
if err != nil {
t.Errorf("close pool errror: %v", err)
}
}()
cases := []struct {
item *Item
skey []byte
ok bool
}{
{item: &Item{Content: "test", TTL: 60, Times: 1}, ok: false},
{item: &Item{Content: "test", TTL: 60, Times: 1}, skey: cipherKey, ok: true},
{item: &Item{Content: "test", TTL: 60, Times: 1, Password: "abc"}, skey: cipherKey, ok: true},
}
for i, v := range cases {
err = v.item.Save(conn, v.skey)
if v.ok {
if err != nil {
t.Errorf("unexpected error case=%v: %v", i, err)
}
ok, err := v.item.delete(conn)
if err != nil {
t.Errorf("failed delete item, case=%v: %v", i, err)
}
if !ok {
t.Error("item was not deleted")
}
} else {
if err == nil {
t.Errorf("expected error case=%v", i)
}
}
}
}
func TestItem_Exists(t *testing.T) {
pool, err := readCfg()
if err != nil {
t.Fatal(err)
}
conn := pool.Get()
defer func() {
err = conn.Close()
if err != nil {
t.Errorf("close connection errror: %v", err)
}
err = pool.Close()
if err != nil {
t.Errorf("close pool errror: %v", err)
}
}()
item := &Item{Content: "test", TTL: 60, Times: 1}
err = item.Save(conn, cipherKey)
if err != nil {
t.Fatal(err)
}
defer func() {
ok, err := item.delete(conn)
if err != nil {
t.Error("failed delete item")
}
if !ok {
t.Error("item was not deleted")
}
}()
exists, err := item.Exists(conn)
if err != nil {
t.Error(err)
}
if !exists {
t.Error("item does not exist")
}
key := item.Key
item.Key = "abc"
exists, err = item.Exists(conn)
if err != nil {
t.Error(err)
}
if exists {
t.Error("item exists")
}
item.Key = key
}
func TestItem_CheckPassword(t *testing.T) {
const password = "abc"
pool, err := readCfg()
if err != nil {
t.Fatal(err)
}
conn := pool.Get()
defer func() {
err = conn.Close()
if err != nil {
t.Errorf("close connection errror: %v", err)
}
err = pool.Close()
if err != nil {
t.Errorf("close pool errror: %v", err)
}
}()
item := &Item{Content: "test", TTL: 60, Times: 1, Password: password}
err = item.Save(conn, cipherKey)
if err != nil {
t.Fatal(err)
}
defer func() {
ok, err := item.delete(conn)
if err != nil {
t.Error("failed delete item")
}
if !ok {
t.Error("item was not deleted")
}
}()
ok, err := item.CheckPassword(conn)
if err != nil {
t.Fatal(err)
}
if !ok {
t.Error("failed password check")
}
item.Password, item.hPassword = "bad", ""
ok, err = item.CheckPassword(conn)
if err != nil {
t.Fatal(err)
}
if ok {
t.Error("unexpected success password check")
}
}
func TestItem_Read(t *testing.T) {
pool, err := readCfg()
if err != nil {
t.Fatal(err)
}
conn := pool.Get()
defer func() {
err = conn.Close()
if err != nil {
t.Errorf("close connection errror: %v", err)
}
err = pool.Close()
if err != nil {
t.Errorf("close pool errror: %v", err)
}
}()
item := &Item{Content: "test", TTL: 60, Times: 2}
err = item.Save(conn, cipherKey)
if err != nil {
t.Fatal(err)
}
key := item.Key
// read with failed key
item.Key = "abc"
exists, err := item.Read(conn, cipherKey)
if exists {
t.Error("unexpected success read")
}
item.Key = key
// success read
exists, err = item.Read(conn, cipherKey)
if !exists || (err != nil) {
t.Errorf("failed read; %v", err)
}
if times := item.Times; times != 1 {
t.Errorf("invalid times value: %v", times)
}
ok, err := item.Exists(conn)
if err != nil {
t.Error("failed check existing")
}
if !ok {
t.Errorf("item doesn't exist")
}
// read and delete
exists, err = item.Read(conn, cipherKey)
if !exists || (err != nil) {
t.Errorf("failed read; %v", err)
}
if times := item.Times; times != 0 {
t.Errorf("invalid times value: %v", times)
}
ok, err = item.Exists(conn)
if err != nil {
t.Error("failed check existing")
}
if ok {
t.Errorf("item still exist")
}
}
func TestItem_ReadConcurrent(t *testing.T) {
const (
times = 128
workers = 8
)
pool, err := readCfg()
if err != nil {
t.Fatal(err)
}
conn := pool.Get()
defer func() {
err = conn.Close()
if err != nil {
t.Errorf("close connection errror: %v", err)
}
err = pool.Close()
if err != nil {
t.Errorf("close pool errror: %v", err)
}
}()
item := &Item{Content: "test", TTL: 60, Times: times}
err = item.Save(conn, cipherKey)
if err != nil {
t.Fatal(err)
}
key, content := item.Key, item.Content
ch := make(chan int)
for i := 0; i < workers; i++ {
go func(n int) {
x := &Item{Key: key, Content: content}
for j := 0; j < times; j++ {
c := pool.Get()
exists, err := x.Read(c, cipherKey)
if err != nil {
t.Errorf("unexpected error read, worker=%v: %v", n, err)
}
if exists {
ch <- 1
} else {
ch <- 0
}
err = c.Close()
if err != nil {
t.Errorf("close connection errror, worker=%v, attempt=%v: %v", n, j, err)
}
}
}(i)
}
s := 0
for i := 0; i < workers*times; i++ {
s += <-ch
}
close(ch)
if s != times {
t.Errorf("failed sum=%v", s)
}
}
func BenchmarkItem_Save(b *testing.B) {
pool, err := readCfg()
if err != nil {
b.Fatal(err)
}
conn := pool.Get()
defer func() {
err = conn.Close()
if err != nil {
b.Errorf("close connection errror: %v", err)
}
err = pool.Close()
if err != nil {
b.Errorf("close pool errror: %v", err)
}
}()
b.ResetTimer()
for n := 0; n < b.N; n++ {
item := Item{Content: "test", TTL: 10, Times: 1}
err = item.Save(conn, cipherKey)
if err != nil {
b.Errorf("failed save: %v", err)
}
ok, err := item.delete(conn)
if err != nil {
b.Errorf("failed delete: %v", err)
}
if !ok {
b.Error("item was not deleted")
}
}
}
func BenchmarkItem_Read(b *testing.B) {
pool, err := readCfg()
if err != nil {
b.Fatal(err)
}
conn := pool.Get()
defer func() {
err = conn.Close()
if err != nil {
b.Errorf("close connection errror: %v", err)
}
err = pool.Close()
if err != nil {
b.Errorf("close pool errror: %v", err)
}
}()
item := Item{Content: "test", TTL: 10, Times: 1000000}
err = item.Save(conn, cipherKey)
if err != nil {
b.Fatal(err)
}
defer func() {
ok, err := item.delete(conn)
if err != nil {
b.Errorf("failed delete: %v", err)
}
if !ok {
b.Error("item was not deleted")
}
}()
b.ResetTimer()
for n := 0; n < b.N; n++ {
item.eContent, item.hPassword = "", ""
exists, err := item.Read(conn, cipherKey)
if !exists || (err != nil) {
b.Errorf("failed read: %v", err)
}
}
}
|
package spider
import (
"strings"
"net/url"
"github.com/PuerkitoBio/goquery"
. "DesertEagleSite/bean"
)
func GetBingData(keyword string) ([]DataItem, string, error) {
resp, err := goquery.NewDocument("http://cn.bing.com/search?q=" + keyword)
if err != nil {
return nil, "", err
}
return ParseBingHTML(resp)
}
func ParseBingUrl(url string) ([]DataItem, string, error) {
resp, err := goquery.NewDocument(url)
if err != nil {
return nil, "", err
}
return ParseBingHTML(resp)
}
func ParseBingHTML(resp *goquery.Document) ([]DataItem, string, error) {
resItems := make([]DataItem, 0)
resp.Find("#b_results li.b_algo, #b_results li.b_ans").Each(func(i int, s *goquery.Selection) {
resItem := DataItem{}
if len(s.Find("h2 a").Nodes) > 0 {
resItem.Title = strings.Replace(strings.Trim(
s.Find("h2 a").First().Text(), " \n"), "\n", " ", -1)
resItem.Link = s.Find("h2 a").First().AttrOr("href", "")
} else if len(s.Find("h5 a").Nodes) > 0 {
resItem.Title = strings.Replace(strings.Trim(
s.Find("h5 a").First().Text(), " \n"), "\n", " ", -1)
resItem.Link = s.Find("h5 a").First().AttrOr("href", "")
} else {
return
}
if tmp, err := url.QueryUnescape(resItem.Title); err == nil {
resItem.Title = tmp
}
if len(s.Find(".b_rich p").Nodes) > 0 {
resItem.Abstract = strings.Replace(strings.Trim(
s.Find(".b_rich p").Text(), " \n"), "\n", " ", -1)
} else if len(s.Find(".b_caption p").Nodes) > 0 {
resItem.Abstract = strings.Replace(strings.Trim(
s.Find(".b_caption p").Text(), " \n"), "\n", " ", -1)
} else if len(s.Find(".b_overflow p").Nodes) > 0 {
resItem.Abstract = strings.Replace(strings.Trim(
s.Find(".b_overflow p").Text(), " \n"), "\n", " ", -1)
} else if len(s.Find("p.b_snippet").Nodes) > 0 {
resItem.Abstract = strings.Replace(strings.Trim(
s.Find("p.b_snippet").Text(), " \n"), "\n", " ", -1)
} else if len(s.Find(".bm_ctn").Nodes) > 0 {
resItem.Abstract = strings.Replace(strings.Trim(
s.Find(".bm_ctn").Text(), " \n"), "\n", " ", -1)
}
if tmp, err := url.QueryUnescape(resItem.Abstract); err == nil {
resItem.Abstract = tmp
}
resItem.ImageUrl = s.Find("img").AttrOr("src", "")
resItems = append(resItems, resItem)
})
nextPage := ""
nextHtml := resp.Find("a.sb_pagN")
if len(nextHtml.Nodes) > 0 {
nextPage = "http://cn.bing.com" + nextHtml.Last().AttrOr("href", "")
}
return resItems, nextPage, nil
}
|
package example
import (
"context"
"github.com/qhenkart/gosqs"
)
func initWorker(c gosqs.Config) {
// create the connection to AWS or the emulator
consumer, err := gosqs.NewConsumer(c, "post-worker")
if err != nil {
panic(err)
}
h := Consumer{
consumer,
}
// add any adapters and middleware, you can also create your own adapters following gosqs.Handler function composition.
// These will be run before the final message handler
a := []gosqs.Adapter{gosqs.WithMiddleware(func(ctx context.Context, m gosqs.Message) error {
// add middleware functionality or authorization middleware etc
return nil
})}
// register the event listeners
h.RegisterHandlers(a...)
// begin message consumption
go h.Consume()
}
// Consumer a wrapper for the gosqs consumer
type Consumer struct {
gosqs.Consumer
}
// RegisterHandlers listens to the specific event types from the queue
func (c *Consumer) RegisterHandlers(adapters ...gosqs.Adapter) {
c.RegisterHandler("post_created", c.CreatePost, adapters...)
c.RegisterHandler("some_new_message", c.Test, adapters...)
}
// Test example event handler
func (c *Consumer) Test(ctx context.Context, m gosqs.Message) error {
out := map[string]interface{}{}
if err := m.Decode(&out); err != nil {
// returning an error will cause the message to try again until it is sent to the Dead-Letter-Queue
return err
}
// returning nil means the message was successfully processed and it will be deleted from the queue
return nil
}
// CreatePost an example of what an event listener looks like
func (c *Consumer) CreatePost(ctx context.Context, m gosqs.Message) error {
var p Post
if err := m.Decode(&p); err != nil {
return err
}
// send a message to the same queue
c.MessageSelf(ctx, "some_new_message", &p)
//forward the message to another queue
c.Message(ctx, "notification-worker", "some_new_message", &p)
return nil
}
|
package doc
import (
"text/template"
)
var (
attributeTmpl *template.Template
attributeFmt = " + {{.Name.Quote}}: {{.Value.Quote}} ({{.Type.String}}, {{with .IsRequired}}required{{else}}optional{{end}}){{with .Description}} - {{.}}{{end}}{{with .DefaultValue}}\n + Default: {{.}}{{end}}"
)
func init() {
attributeTmpl = template.Must(template.New("attribute").Parse(attributeFmt))
}
type Attribute Parameter
func (p *Attribute) Render() string {
return render(attributeTmpl, p)
}
|
package main
import (
"github.com/valyala/fasthttp"
"fmt"
)
type MyHandler struct {
foobar string
l int
}
// request handler in net/http style, i.e. method bound to MyHandler struct.
func (h *MyHandler) HandleFastHTTP(ctx *fasthttp.RequestCtx) {
// notice that we may access MyHandler properties here - see h.foobar.
fmt.Fprintf(ctx, "hello %+v",h)
}
// request handler in fasthttp style, i.e. just plain function.
func fastHTTPHandler(ctx *fasthttp.RequestCtx) {
fmt.Fprintf(ctx, "Hi there! RequestURI is %q", ctx.RequestURI())
}
// pass bound struct method to fasthttp
func main() {
myHandler := &MyHandler{
foobar: "foobar",
l:5,
}
fasthttp.ListenAndServe(":8080", myHandler.HandleFastHTTP)
// pass plain function to fasthttp
fasthttp.ListenAndServe(":8081", fastHTTPHandler)
}
|
package config
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"github.com/cloudflare/cfssl/cli"
"github.com/cloudflare/cfssl/log"
)
// Config is COP config structure
type Config struct {
Debug bool `json:"debug,omitempty"`
Authentication bool `json:"authentication,omitempty"`
Users map[string]*User `jon:"users,omitempty"`
}
// User information
type User struct {
Pass string `json:"pass"` // enrollment secret
}
// Constructor for COP config
func newConfig() *Config {
c := new(Config)
c.Authentication = true
return c
}
// CFG is the COP-specific config
var CFG *Config
// Init initializes the COP config given the CFSSL config
func Init(cfg *cli.Config) {
CFG = newConfig()
if cfg.ConfigFile != "" {
body, err := ioutil.ReadFile(cfg.ConfigFile)
if err != nil {
panic(err.Error())
}
err = json.Unmarshal(body, CFG)
if err != nil {
panic(fmt.Sprintf("error parsing %s: %s", cfg.ConfigFile, err.Error()))
}
}
dbg := os.Getenv("COP_DEBUG")
if dbg != "" {
CFG.Debug = dbg == "true"
}
if CFG.Debug {
log.Level = log.LevelDebug
}
}
|
package iputil
import (
"net"
"testing"
"github.com/stretchr/testify/assert"
)
func TestParseIP(t *testing.T) {
testCases := []struct {
input string
expectedVer IPVersion
expectedIP net.IP
}{
{"", IPvUnknown, nil},
{"1.1.1.1", IPv4, net.IPv4(1, 1, 1, 1)},
{"-1.-1.-1.-1", IPvUnknown, nil},
{"256.256.256.256", IPvUnknown, nil},
{"::ffff:1.1.1.1", IPv6, net.IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 1, 1, 1, 1}},
{"0101::", IPv6, net.IP{1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
{"zzzz::", IPvUnknown, nil},
}
for _, test := range testCases {
ip, ver := ParseIP(test.input)
assert.Equal(t, test.expectedVer, ver)
assert.Equal(t, test.expectedIP, ip)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.