text
stringlengths 11
4.05M
|
|---|
package p2pv1
import (
"errors"
"sync"
"github.com/patrickmn/go-cache"
xctx "github.com/xuperchain/xupercore/kernel/common/xcontext"
"github.com/xuperchain/xupercore/kernel/network/p2p"
pb "github.com/xuperchain/xupercore/protos"
)
func (p *P2PServerV1) GetPeerInfo(addresses []string) ([]*pb.PeerInfo, error) {
if len(addresses) == 0 {
return nil, errors.New("neighbors empty")
}
peerInfo := p.PeerInfo()
p.accounts.Set(peerInfo.GetAccount(), peerInfo.GetAddress(), 0)
var remotePeers []*pb.PeerInfo
var wg sync.WaitGroup
var mutex sync.Mutex
for _, addr := range addresses {
wg.Add(1)
go func(addr string) {
defer wg.Done()
rps := p.GetPeer(peerInfo, addr)
if rps == nil {
return
}
mutex.Lock()
remotePeers = append(remotePeers, rps...)
mutex.Unlock()
}(addr)
}
wg.Wait()
return remotePeers, nil
}
func (p *P2PServerV1) GetPeer(peerInfo pb.PeerInfo, addr string) []*pb.PeerInfo {
var remotePeers []*pb.PeerInfo
msg := p2p.NewMessage(pb.XuperMessage_GET_PEER_INFO, &peerInfo)
response, err := p.SendMessageWithResponse(p.ctx, msg, p2p.WithAddresses([]string{addr}))
if err != nil {
p.log.Error("get peer error", "log_id", msg.GetHeader().GetLogid(), "error", err)
return nil
}
for _, msg := range response {
var peer pb.PeerInfo
err := p2p.Unmarshal(msg, &peer)
if err != nil {
p.log.Warn("unmarshal NewNode response error", "log_id", msg.GetHeader().GetLogid(), "error", err)
continue
}
peer.Address = addr
p.accounts.Set(peer.GetAccount(), peer.GetAddress(), cache.NoExpiration)
remotePeers = append(remotePeers, &peer)
}
return remotePeers
}
func (p *P2PServerV1) registerConnectHandler() error {
err := p.Register(p2p.NewSubscriber(p.ctx, pb.XuperMessage_GET_PEER_INFO, p2p.HandleFunc(p.handleGetPeerInfo)))
if err != nil {
p.log.Error("registerSubscribe error", "error", err)
return err
}
return nil
}
func (p *P2PServerV1) handleGetPeerInfo(ctx xctx.XContext, request *pb.XuperMessage) (*pb.XuperMessage, error) {
output := p.PeerInfo()
opts := []p2p.MessageOption{
p2p.WithBCName(request.GetHeader().GetBcname()),
p2p.WithErrorType(pb.XuperMessage_SUCCESS),
p2p.WithLogId(request.GetHeader().GetLogid()),
}
resp := p2p.NewMessage(pb.XuperMessage_GET_PEER_INFO_RES, &output, opts...)
var peerInfo pb.PeerInfo
err := p2p.Unmarshal(request, &peerInfo)
if err != nil {
p.log.Warn("unmarshal NewNode response error", "error", err)
return resp, nil
}
if !p.pool.staticModeOn {
uniq := make(map[string]struct{}, len(p.dynamicNodes))
for _, address := range p.dynamicNodes {
uniq[address] = struct{}{}
}
if _, ok := uniq[peerInfo.Address]; !ok {
p.dynamicNodes = append(p.dynamicNodes, peerInfo.Address)
}
p.accounts.Set(peerInfo.GetAccount(), peerInfo.GetAddress(), cache.NoExpiration)
}
return resp, nil
}
|
package main
import(
"go_project_ex"
)
func main(){
go_project_ex.Hello()
}
|
package main
import (
"fmt"
"sort"
"strconv"
"strings"
)
/*
A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits
1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order.
The lexicographic permutations of 0, 1 and 2 are: 012 021 102 120 201 210
What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
*/
func main() {
permutations := make([]string, 0, 0)
generate(10, []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, &permutations)
sort.Strings(permutations)
fmt.Println(permutations[999999])
}
// Heap's algorithm to generate permutations
func generate(n int, digits []int, permutations *[]string) {
if n == 1 {
*permutations = append(*permutations, convert(digits))
} else {
for i := 0; i < n-1; i++ {
generate(n-1, digits, permutations)
if n%2 == 0 {
digits[i], digits[n-1] = digits[n-1], digits[i]
} else {
digits[0], digits[n-1] = digits[n-1], digits[0]
}
}
generate(n-1, digits, permutations)
}
}
func convert(digits []int) string {
builder := strings.Builder{}
for _, digit := range digits {
builder.WriteString(strconv.FormatInt(int64(digit), 10))
}
return builder.String()
}
|
package main
import(
"time"
)
type MovimientoInventario struct
{
CodigoMovimiento string `bson:"codigomovimiento"`
TipoMovimiento string `bson:"tipomovimiento"`
CodigoArticulo string `bson:"codigoarticulo"`
Cantidad int32 `bson:"cantidad"`
Fecha time.Time
Unidad string `bson:"unidad"`//lb,caja,etc
}
type ArticuloSuplidor struct{
CodigoArticulo string
CodigoSuplidor string
TiempoEntrega int32
PrecioArticulo float64
}
type Articulo struct{
CodigoArticulo string
Descripcion string
BalanceActual int32
UnidadCompra string
}
type Suplidor struct{
CodigoSuplidor string
NombreSuplidor string
}
type OrdenCompra struct
{
CodigoOrdenCompra string
FechaRequerida time.Time
FechaGenerada time.Time
FechaAOrdenar time.Time
CodigoSuplidor string
CodigoArticulo string
CantidadOrdenada int32
UnidadCompra string
PrecioArticulo float64
MontoTotal float64
}
|
package driver
import (
"finance/models"
models_driver "finance/models/driver"
"finance/validator"
)
type DriverIdBase struct {
DriverId uint `json:"driver_id" form:"driver_id" validate:"required" error_message:"驾驶员编号~required:请填写后重试."`
}
func (form *DriverIdBase) GetDriver() *models_driver.FinanceDriver {
var driver models_driver.FinanceDriver
models.DB.First(&driver, form.DriverId)
return &driver
}
type DriverAddForm struct {
Name string `json:"name" form:"name" validate:"required,max=20" error_message:"驾驶员姓名~required:此字段必须填写;max:最大长度为20"`
NumberPlate string `json:"number_plate" form:"number_plate" validate:"required,max=20" error_message:"驾驶员车牌号~required:此字段必须填写;max:最大长度为20"` //`form:"number_plate" validate:"required,max=20" error_message:"驾驶员车牌号~required:此字段必须填写;max:最大长度为20"`
Phone string `json:"phone" form:"phone" validate:"required,max=12" error_message:"驾驶员手机号~required:此字段必须填写;max:最大长度为12"`
}
type DriverListForm struct {
validator.ListPage
}
func (form *DriverListForm) GetDrivers() []models_driver.FinanceDriver {
var drivers []models_driver.FinanceDriver
models.DB.Model(models_driver.FinanceDriver{}).Count(&form.Total)
models.DB.Offset((form.Page - 1) * form.Limit).Limit(form.Limit).Find(&drivers)
return drivers
}
type DriverInfoForm struct {
DriverIdBase
}
type DriverEditForm struct {
DriverIdBase
DriverAddForm
}
type DriverDeleteForm struct {
DriverIdBase
}
|
package configs
import "os"
func ternaryMap(value string, defaultValue string) string {
return map[bool]string{true: value, false: defaultValue}[len(value) != 0]
}
// Envs has values for environment variables and the defaults for them
var Envs = map[string]string{
"PROXY_DESTINATION": ternaryMap(os.Getenv("PROXY_DESTINATION"), "localhost:8080"),
"SERVER_PORT": ternaryMap(os.Getenv("SERVER_PORT"), "8080"),
"DB_HOST": ternaryMap(os.Getenv("DB_HOST"), "localhost"),
"DB_PORT": ternaryMap(os.Getenv("DB_PORT"), "5432"),
"DB_USERNAME": ternaryMap(os.Getenv("DB_USERNAME"), "postgres"),
"DB_PASSWORD": ternaryMap(os.Getenv("DB_PASSWORD"), "1234"),
"DB_DATABASE": ternaryMap(os.Getenv("DB_DATABASE"), "database"),
"DB_SSLMODE": ternaryMap(os.Getenv("DB_SSLMODE"), "disable"),
}
|
// Copyright (c) 2016-2019 Uber Technologies, 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 scheduler
import (
"testing"
"time"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
"github.com/uber-go/tally"
"github.com/uber/kraken/core"
"github.com/uber/kraken/lib/store"
"github.com/uber/kraken/lib/torrent/networkevent"
"github.com/uber/kraken/lib/torrent/scheduler/announcequeue"
"github.com/uber/kraken/lib/torrent/scheduler/conn"
"github.com/uber/kraken/lib/torrent/scheduler/connstate"
"github.com/uber/kraken/lib/torrent/storage"
"github.com/uber/kraken/lib/torrent/storage/agentstorage"
mockannounceclient "github.com/uber/kraken/mocks/tracker/announceclient"
mockmetainfoclient "github.com/uber/kraken/mocks/tracker/metainfoclient"
"github.com/uber/kraken/tracker/announceclient"
"github.com/uber/kraken/utils/testutil"
)
const _testNamespace = "noexist"
type mockEventLoop struct {
t *testing.T
c chan event
}
func (l *mockEventLoop) expect(e event) {
select {
case result := <-l.c:
require.Equal(l.t, e, result)
case <-time.After(5 * time.Second):
l.t.Fatalf("timed out waiting for %T to occur", e)
}
}
func (l *mockEventLoop) send(e event) bool {
l.c <- e
return true
}
// Unimplemented.
func (l *mockEventLoop) run(*state) {}
func (l *mockEventLoop) stop() {}
func (l *mockEventLoop) sendTimeout(e event, timeout time.Duration) error { panic("unimplemented") }
type stateMocks struct {
metainfoClient *mockmetainfoclient.MockClient
announceClient *mockannounceclient.MockClient
announceQueue announcequeue.Queue
torrentArchive storage.TorrentArchive
eventLoop *mockEventLoop
}
func newStateMocks(t *testing.T) (*stateMocks, func()) {
cleanup := &testutil.Cleanup{}
defer cleanup.Recover()
ctrl := gomock.NewController(t)
cleanup.Add(ctrl.Finish)
metainfoClient := mockmetainfoclient.NewMockClient(ctrl)
announceClient := mockannounceclient.NewMockClient(ctrl)
cads, c := store.CADownloadStoreFixture()
cleanup.Add(c)
mocks := &stateMocks{
metainfoClient: metainfoClient,
announceClient: announceClient,
announceQueue: announcequeue.New(),
torrentArchive: agentstorage.NewTorrentArchive(tally.NoopScope, cads, metainfoClient),
eventLoop: &mockEventLoop{t, make(chan event)},
}
return mocks, cleanup.Run
}
func (m *stateMocks) newState(config Config) *state {
sched, err := newScheduler(
config,
m.torrentArchive,
tally.NoopScope,
core.PeerContextFixture(),
m.announceClient,
networkevent.NewTestProducer(),
withEventLoop(m.eventLoop))
if err != nil {
panic(err)
}
return newState(sched, m.announceQueue)
}
func (m *stateMocks) newTorrent() storage.Torrent {
mi := core.MetaInfoFixture()
m.metainfoClient.EXPECT().
Download(_testNamespace, mi.Digest()).
Return(mi, nil)
t, err := m.torrentArchive.CreateTorrent(_testNamespace, mi.Digest())
if err != nil {
panic(err)
}
return t
}
func TestAnnounceTickEvent(t *testing.T) {
require := require.New(t)
mocks, cleanup := newStateMocks(t)
defer cleanup()
state := mocks.newState(Config{})
var ctrls []*torrentControl
for i := 0; i < 5; i++ {
c, err := state.addTorrent(_testNamespace, mocks.newTorrent(), true)
require.NoError(err)
ctrls = append(ctrls, c)
}
// First torrent should announce.
mocks.announceClient.EXPECT().
Announce(
ctrls[0].dispatcher.Digest(),
ctrls[0].dispatcher.InfoHash(),
false,
announceclient.V2).
Return(nil, time.Second, nil)
announceTickEvent{}.apply(state)
mocks.eventLoop.expect(announceResultEvent{
infoHash: ctrls[0].dispatcher.InfoHash(),
})
}
func TestAnnounceTickEventSkipsFullTorrents(t *testing.T) {
require := require.New(t)
mocks, cleanup := newStateMocks(t)
defer cleanup()
state := mocks.newState(Config{
ConnState: connstate.Config{
MaxOpenConnectionsPerTorrent: 5,
},
})
full, err := state.addTorrent(_testNamespace, mocks.newTorrent(), true)
require.NoError(err)
info := full.dispatcher.Stat()
for i := 0; i < 5; i++ {
_, c, cleanup := conn.PipeFixture(conn.Config{}, info)
defer cleanup()
require.NoError(state.conns.AddPending(c.PeerID(), c.InfoHash(), nil))
require.NoError(state.addOutgoingConn(c, info.Bitfield(), info))
}
empty, err := state.addTorrent(_testNamespace, mocks.newTorrent(), true)
require.NoError(err)
// The first torrent is full and should be skipped, announcing the empty
// torrent.
mocks.announceClient.EXPECT().
Announce(
empty.dispatcher.Digest(),
empty.dispatcher.InfoHash(),
false,
announceclient.V2).
Return(nil, time.Second, nil)
announceTickEvent{}.apply(state)
// Empty torrent announced.
mocks.eventLoop.expect(announceResultEvent{
infoHash: empty.dispatcher.InfoHash(),
})
// The empty torrent is pending, so keep skipping full torrent.
announceTickEvent{}.apply(state)
announceTickEvent{}.apply(state)
announceTickEvent{}.apply(state)
// Remove a connection -- torrent is no longer full.
c := state.conns.ActiveConns()[0]
c.Close()
// TODO(codyg): This is ugly. Conn fixtures aren't connected to our event
// loop, so we have to manually trigger the event.
connClosedEvent{c}.apply(state)
mocks.eventLoop.expect(peerRemovedEvent{
peerID: c.PeerID(),
infoHash: c.InfoHash(),
})
mocks.announceClient.EXPECT().
Announce(
full.dispatcher.Digest(),
full.dispatcher.InfoHash(),
false,
announceclient.V2).
Return(nil, time.Second, nil)
announceTickEvent{}.apply(state)
// Previously full torrent announced.
mocks.eventLoop.expect(announceResultEvent{
infoHash: full.dispatcher.InfoHash(),
})
}
|
package golory
import (
"github.com/1pb-club/golory/log"
)
// Get logger by name
func Logger(name string) *log.Logger {
return gly.components.getLogger(name)
}
|
package app
import (
"github.com/go-telegram-bot-api/telegram-bot-api"
"log"
"os"
"sync"
)
var (
instance *App
iOnce sync.Once
)
type App struct {
Bot *tgbotapi.BotAPI
}
func New() (*App, error) {
bot, err := tgbotapi.NewBotAPI(os.Getenv("T_TOKEN"))
if err != nil {
return nil, err
}
log.Printf("Authorized on account %s", bot.Self.UserName)
//bot.Debug = true
return &App{Bot: bot}, nil
}
func Get() *App {
iOnce.Do(func() {
var err error
instance, err = New()
if err != nil {
panic(err)
}
})
return instance
}
func (a *App) Reply(u *tgbotapi.Update) error {
msg := tgbotapi.NewMessage(u.Message.Chat.ID, "Reply: " + u.Message.Text)
a.Bot.Send(msg)
return nil
}
|
// Copyright 2019 - 2022 The Samply Community
//
// 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 fhir
import "encoding/json"
// THIS FILE IS GENERATED BY https://github.com/samply/golang-fhir-models
// PLEASE DO NOT EDIT BY HAND
// RiskEvidenceSynthesis is documented here http://hl7.org/fhir/StructureDefinition/RiskEvidenceSynthesis
type RiskEvidenceSynthesis struct {
Id *string `bson:"id,omitempty" json:"id,omitempty"`
Meta *Meta `bson:"meta,omitempty" json:"meta,omitempty"`
ImplicitRules *string `bson:"implicitRules,omitempty" json:"implicitRules,omitempty"`
Language *string `bson:"language,omitempty" json:"language,omitempty"`
Text *Narrative `bson:"text,omitempty" json:"text,omitempty"`
Extension []Extension `bson:"extension,omitempty" json:"extension,omitempty"`
ModifierExtension []Extension `bson:"modifierExtension,omitempty" json:"modifierExtension,omitempty"`
Url *string `bson:"url,omitempty" json:"url,omitempty"`
Identifier []Identifier `bson:"identifier,omitempty" json:"identifier,omitempty"`
Version *string `bson:"version,omitempty" json:"version,omitempty"`
Name *string `bson:"name,omitempty" json:"name,omitempty"`
Title *string `bson:"title,omitempty" json:"title,omitempty"`
Status PublicationStatus `bson:"status" json:"status"`
Date *string `bson:"date,omitempty" json:"date,omitempty"`
Publisher *string `bson:"publisher,omitempty" json:"publisher,omitempty"`
Contact []ContactDetail `bson:"contact,omitempty" json:"contact,omitempty"`
Description *string `bson:"description,omitempty" json:"description,omitempty"`
Note []Annotation `bson:"note,omitempty" json:"note,omitempty"`
UseContext []UsageContext `bson:"useContext,omitempty" json:"useContext,omitempty"`
Jurisdiction []CodeableConcept `bson:"jurisdiction,omitempty" json:"jurisdiction,omitempty"`
Copyright *string `bson:"copyright,omitempty" json:"copyright,omitempty"`
ApprovalDate *string `bson:"approvalDate,omitempty" json:"approvalDate,omitempty"`
LastReviewDate *string `bson:"lastReviewDate,omitempty" json:"lastReviewDate,omitempty"`
EffectivePeriod *Period `bson:"effectivePeriod,omitempty" json:"effectivePeriod,omitempty"`
Topic []CodeableConcept `bson:"topic,omitempty" json:"topic,omitempty"`
Author []ContactDetail `bson:"author,omitempty" json:"author,omitempty"`
Editor []ContactDetail `bson:"editor,omitempty" json:"editor,omitempty"`
Reviewer []ContactDetail `bson:"reviewer,omitempty" json:"reviewer,omitempty"`
Endorser []ContactDetail `bson:"endorser,omitempty" json:"endorser,omitempty"`
RelatedArtifact []RelatedArtifact `bson:"relatedArtifact,omitempty" json:"relatedArtifact,omitempty"`
SynthesisType *CodeableConcept `bson:"synthesisType,omitempty" json:"synthesisType,omitempty"`
StudyType *CodeableConcept `bson:"studyType,omitempty" json:"studyType,omitempty"`
Population Reference `bson:"population" json:"population"`
Exposure *Reference `bson:"exposure,omitempty" json:"exposure,omitempty"`
Outcome Reference `bson:"outcome" json:"outcome"`
SampleSize *RiskEvidenceSynthesisSampleSize `bson:"sampleSize,omitempty" json:"sampleSize,omitempty"`
RiskEstimate *RiskEvidenceSynthesisRiskEstimate `bson:"riskEstimate,omitempty" json:"riskEstimate,omitempty"`
Certainty []RiskEvidenceSynthesisCertainty `bson:"certainty,omitempty" json:"certainty,omitempty"`
}
type RiskEvidenceSynthesisSampleSize struct {
Id *string `bson:"id,omitempty" json:"id,omitempty"`
Extension []Extension `bson:"extension,omitempty" json:"extension,omitempty"`
ModifierExtension []Extension `bson:"modifierExtension,omitempty" json:"modifierExtension,omitempty"`
Description *string `bson:"description,omitempty" json:"description,omitempty"`
NumberOfStudies *int `bson:"numberOfStudies,omitempty" json:"numberOfStudies,omitempty"`
NumberOfParticipants *int `bson:"numberOfParticipants,omitempty" json:"numberOfParticipants,omitempty"`
}
type RiskEvidenceSynthesisRiskEstimate struct {
Id *string `bson:"id,omitempty" json:"id,omitempty"`
Extension []Extension `bson:"extension,omitempty" json:"extension,omitempty"`
ModifierExtension []Extension `bson:"modifierExtension,omitempty" json:"modifierExtension,omitempty"`
Description *string `bson:"description,omitempty" json:"description,omitempty"`
Type *CodeableConcept `bson:"type,omitempty" json:"type,omitempty"`
Value *json.Number `bson:"value,omitempty" json:"value,omitempty"`
UnitOfMeasure *CodeableConcept `bson:"unitOfMeasure,omitempty" json:"unitOfMeasure,omitempty"`
DenominatorCount *int `bson:"denominatorCount,omitempty" json:"denominatorCount,omitempty"`
NumeratorCount *int `bson:"numeratorCount,omitempty" json:"numeratorCount,omitempty"`
PrecisionEstimate []RiskEvidenceSynthesisRiskEstimatePrecisionEstimate `bson:"precisionEstimate,omitempty" json:"precisionEstimate,omitempty"`
}
type RiskEvidenceSynthesisRiskEstimatePrecisionEstimate struct {
Id *string `bson:"id,omitempty" json:"id,omitempty"`
Extension []Extension `bson:"extension,omitempty" json:"extension,omitempty"`
ModifierExtension []Extension `bson:"modifierExtension,omitempty" json:"modifierExtension,omitempty"`
Type *CodeableConcept `bson:"type,omitempty" json:"type,omitempty"`
Level *json.Number `bson:"level,omitempty" json:"level,omitempty"`
From *json.Number `bson:"from,omitempty" json:"from,omitempty"`
To *json.Number `bson:"to,omitempty" json:"to,omitempty"`
}
type RiskEvidenceSynthesisCertainty struct {
Id *string `bson:"id,omitempty" json:"id,omitempty"`
Extension []Extension `bson:"extension,omitempty" json:"extension,omitempty"`
ModifierExtension []Extension `bson:"modifierExtension,omitempty" json:"modifierExtension,omitempty"`
Rating []CodeableConcept `bson:"rating,omitempty" json:"rating,omitempty"`
Note []Annotation `bson:"note,omitempty" json:"note,omitempty"`
CertaintySubcomponent []RiskEvidenceSynthesisCertaintyCertaintySubcomponent `bson:"certaintySubcomponent,omitempty" json:"certaintySubcomponent,omitempty"`
}
type RiskEvidenceSynthesisCertaintyCertaintySubcomponent struct {
Id *string `bson:"id,omitempty" json:"id,omitempty"`
Extension []Extension `bson:"extension,omitempty" json:"extension,omitempty"`
ModifierExtension []Extension `bson:"modifierExtension,omitempty" json:"modifierExtension,omitempty"`
Type *CodeableConcept `bson:"type,omitempty" json:"type,omitempty"`
Rating []CodeableConcept `bson:"rating,omitempty" json:"rating,omitempty"`
Note []Annotation `bson:"note,omitempty" json:"note,omitempty"`
}
type OtherRiskEvidenceSynthesis RiskEvidenceSynthesis
// MarshalJSON marshals the given RiskEvidenceSynthesis as JSON into a byte slice
func (r RiskEvidenceSynthesis) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
OtherRiskEvidenceSynthesis
ResourceType string `json:"resourceType"`
}{
OtherRiskEvidenceSynthesis: OtherRiskEvidenceSynthesis(r),
ResourceType: "RiskEvidenceSynthesis",
})
}
// UnmarshalRiskEvidenceSynthesis unmarshals a RiskEvidenceSynthesis.
func UnmarshalRiskEvidenceSynthesis(b []byte) (RiskEvidenceSynthesis, error) {
var riskEvidenceSynthesis RiskEvidenceSynthesis
if err := json.Unmarshal(b, &riskEvidenceSynthesis); err != nil {
return riskEvidenceSynthesis, err
}
return riskEvidenceSynthesis, nil
}
|
package api
import (
"net/http"
"testing"
"github.com/google/go-cmp/cmp"
)
func TestListAlertConditions(t *testing.T) {
c := newTestAPIClient(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`
{
"conditions": [
{
"id": 1234,
"type": "browser_metric",
"name": "End User Apdex (Low)",
"enabled": false,
"entities": ["126408", "127809"],
"metric": "end_user_apdex",
"condition_scope": "application",
"terms": [{
"duration": "120",
"operator": "below",
"priority": "critical",
"threshold": ".9",
"time_function": "all"
}]
}
]
}
`))
}))
terms := []AlertConditionTerm{
{
Duration: 120,
Operator: "below",
Priority: "critical",
Threshold: 0.9,
TimeFunction: "all",
},
}
expected := []AlertCondition{
{
ID: 1234,
Type: "browser_metric",
Name: "End User Apdex (Low)",
Enabled: false,
Entities: []string{"126408", "127809"},
Metric: "end_user_apdex",
Scope: "application",
Terms: terms,
},
}
policyID := 123
alertConditions, err := c.queryAlertConditions(policyID)
if err != nil {
t.Log(err)
t.Fatal("GetAlertCondition error")
}
if alertConditions == nil {
t.Log(err)
t.Fatal("GetAlertCondition error")
}
if diff := cmp.Diff(alertConditions, expected); diff != "" {
t.Fatalf("Alert conditions not parsed correctly: %s", diff)
}
}
|
package alidns
import (
"fmt"
"net/url"
"testing"
"time"
)
func Test_Sig(t *testing.T) {
var p = url.Values{}
p.Add("akid", "test")
fmt.Println(p.Encode())
//uri:=`Format=XML&AccessKeyId=testid&Action=DescribeDomainRecords&SignatureMethod=HMAC-SHA1&DomainName=example.com&SignatureNonce=f59ed6a9-83fc-473b-9cc6-99c95df3856e&SignatureVersion=1.0&Version=2015-01-09&Timestamp=2016-03-24T16:41:54Z`
uri := "/"
fmt.Println(url.QueryEscape(uri))
//time2, _ = time.Parse(time.RFC3339, "2006-01-02T15:04:05Z")
//
//fmt.Println(time2)
timestamp := time.Now().Format("2006-01-02T15:04:05Z")
fmt.Println(timestamp)
}
func Test_url(t *testing.T) {
uri := url.Values{}
uri.Add("AccessKeyId", "testid")
uri.Add("Action", "DescribeDomainRecords")
uri.Add("SignatureMethod", "HMAC-SHA1")
uri.Add("DomainName", "example.com")
uri.Add("SignatureVersion", "1.0")
uri.Add("Version", "2015-01-09")
uri.Add("SignatureNonce", "f59ed6a9-83fc-473b-9cc6-99c95df3856e")
uri.Add("Format", "JSON")
fmt.Println(uri.Encode())
fmt.Println(url.QueryEscape(uri.Encode()))
}
// Signature 签名机制
// https://help.aliyun.com/document_detail/29747.html?spm=a2c4g.11186623.6.619.648d5279NR2Fyp
func Test_Signature(t *testing.T) {
uri := url.Values{}
uri.Add("Format", "XML")
uri.Add("AccessKeyId", "testid")
uri.Add("Action", "DescribeDomainRecords")
uri.Add("SignatureMethod", "HMAC-SHA1")
uri.Add("DomainName", "example.com")
uri.Add("SignatureNonce", "f59ed6a9-83fc-473b-9cc6-99c95df3856e")
uri.Add("SignatureVersion", "1.0")
uri.Add("Version", "2015-01-09")
uri.Add("Timestamp", "2016-03-24T16:41:54Z")
cannoURI := "GET" + "&" + url.QueryEscape("/") + "&" + url.QueryEscape(uri.Encode())
code := ShaHmac1(cannoURI, "testsecret&")
fmt.Println(code)
if code == "uRpHwaSEt3J+6KQD//svCh/x+pI=" {
fmt.Println("success")
}
code2 := Signature("GET", uri, "testsecret&")
fmt.Println(code2)
if code2 == "uRpHwaSEt3J+6KQD//svCh/x+pI=" {
fmt.Println("success")
}
}
func TestNew(t *testing.T) {
//nowtime := time.Now()
//
//fmt.Println(nowtime.Format("2006-01-02T15:04:05Z"))
//fmt.Println(nowtime.Format("2006-01-02T15:04:05Z-0700"))
//fmt.Println(nowtime.Format("2006-01-02T15:04:05Z+0800"))
loc, _ := time.LoadLocation("") //参数就是解压文件的“目录”+“/”+“文件名”。
//fmt.Println(time.Now().In(loc))
timeNow := time.Now().In(loc).Format("2006-01-02T15:04:05Z")
fmt.Println(timeNow)
fmt.Println(url.QueryEscape(timeNow))
fmt.Println(url.QueryEscape("2016-03-24T16:41:54Z"))
}
|
package db
import (
"fmt"
"os"
"path"
"path/filepath"
"github.com/go-xorm/core"
"github.com/go-xorm/xorm"
"github.com/zaaksam/dproxy/go/model"
)
// IModel 模型接口
type IModel interface {
TableName() string
NewItems() interface{}
}
// Engine 数据库引擎
var Engine *xorm.Engine
var tables []xorm.TableName
func init() {
tables = make([]xorm.TableName, 20)
dir := path.Dir(os.Args[0])
dir = filepath.ToSlash(dir) // .../dproxy/go
file := filepath.Join(dir, "dproxy.db")
_, err := os.Stat(file)
if err != nil && os.IsNotExist(err) {
_, err = os.Create(file)
if err != nil {
panic(fmt.Errorf("创建DB文件错误:%s", err))
}
}
Engine, err = xorm.NewEngine("sqlite3", file)
err = Engine.Ping()
if err != nil {
panic(fmt.Sprintf("DB连接不通:%s", err))
}
//结构体命名与数据库一致
Engine.SetMapper(core.NewCacheMapper(new(core.SameMapper)))
err = createTable(
&model.LogModel{},
&model.WhiteListModel{},
&model.PortMapModel{},
)
if err != nil {
os.Remove(file)
panic(err)
}
}
func createTable(beans ...xorm.TableName) (err error) {
// tables, err := Engine.DBMetas()
// if err != nil {
// panic(fmt.Sprintf("获取DB信息错误:%s", err))
// }
for i, l := 0, len(beans); i < l; i++ {
err = Engine.CreateTables(beans[i])
if err != nil {
return fmt.Errorf("创建数据库表[%s]失败:%s", beans[i].TableName(), err)
}
}
return
}
// NewSession 创建新的数据库操作对象
func NewSession() *xorm.Session {
session := Engine.NewSession()
session.IsAutoClose(true)
return session
}
// GetList 获取分页数据
func GetList(session *xorm.Session, md IModel, pageIndex, pageSize int) (list *model.ListModel, err error) {
list = &model.ListModel{
PageIndex: pageIndex,
PageSize: pageSize,
Items: md.NewItems(),
}
//克隆查询对象
sessionCount := session.Clone()
defer sessionCount.Close()
statement := sessionCount.Statement()
//清空Orderby条件,在某些数据库count不能带orderby
statement.OrderStr = ""
if groupBy := statement.GroupByStr; groupBy != "" {
statement.GroupByStr = "" // count不能带groupby
list.Total, err = sessionCount.Select("count(DISTINCT " + groupBy + ")").Count(md)
} else {
sessionCount.Select("") // select置空
list.Total, err = sessionCount.Count(md)
}
if err != nil {
return
}
//计算分页
resetPagination(list)
//没有数据,提前返回
if list.Total <= 0 {
return
}
recordIndex := (list.PageIndex - 1) * list.PageSize
session.Limit(list.PageSize, recordIndex)
err = session.Table(md).Find(list.Items)
return
}
func resetPagination(list *model.ListModel) {
//检查页面长度
if list.PageSize <= 0 {
list.PageSize = 10
} else if list.PageSize > 500 {
list.PageSize = 500
}
//计算总页数
cnt := int(list.Total / int64(list.PageSize))
mod := int(list.Total % int64(list.PageSize))
if mod > 0 {
cnt++
}
//检查页面索引
switch {
case cnt == 0:
list.PageIndex = 1
case list.PageIndex > cnt:
list.PageIndex = cnt
case list.PageIndex <= 0:
list.PageIndex = 1
}
//设置页面总页数
list.PageCount = cnt
}
|
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"github.com/pkg/errors"
"github.com/urfave/cli"
)
type Entity string
const (
Client Entity = ".client"
Project Entity = ".project"
Task Entity = ".task"
)
/*_init ...
Initialize client and project directives
*/
func _init(c *cli.Context) error {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
return errors.Wrap(err, "initialize failed (dirname error)")
}
client := filepath.Join(dir, c.Args().Get(0))
project := filepath.Join(client, c.Args().Get(1))
mode := os.FileMode(0700)
/**
+-----+---+--------------------------+
| rwx | 7 | Read, write and execute |
| rw- | 6 | Read, write |
| r-x | 5 | Read, and execute |
| r-- | 4 | Read, |
| -wx | 3 | Write and execute |
| -w- | 2 | Write |
| --x | 1 | Execute |
| --- | 0 | no permissions |
+------------------------------------+
+------------+------+-------+
| Permission | Octal| Field |
+------------+------+-------+
| rwx------ | 0700 | User |
| ---rwx--- | 0070 | Group |
| ------rwx | 0007 | Other |
+------------+------+-------+
*/
os.Mkdir(client, os.FileMode(mode))
os.OpenFile(filepath.Join(client, string(Client)), os.O_RDONLY|os.O_CREATE, mode)
os.Mkdir(project, os.FileMode(mode))
os.OpenFile(filepath.Join(project, string(Project)), os.O_RDONLY|os.O_CREATE, mode)
fmt.Println("initialize has been done successfully")
return nil
}
func isClient() bool {
_, err := os.Stat(string(Client))
if err != nil {
return false
} else {
return true
}
}
func isProject() bool {
_, err := os.Stat(string(Project))
if err != nil {
return false
} else {
return true
}
}
func isTask() bool {
_, err := os.Stat(string(Task))
if err != nil {
return false
} else {
return true
}
}
// func createEntity() {
// }
// func add(c *cli.Context) {
// dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
// if isClient() {
// name := filepath.Join(dir, c.Args().Get(0))
// } else {
// }
// }
// func remove(entity Entity) {
// }
func main() {
app := cli.NewApp()
app.Name = "tm"
app.Usage = "Minimalistic task management"
// we create our commands
app.Commands = []cli.Command{
{
Name: "init",
Usage: "Initial setup",
Action: _init,
},
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
|
package actions
import (
"errors"
"github.com/LiveSocket/bot/command-service/models"
"github.com/LiveSocket/bot/conv"
"github.com/LiveSocket/bot/service"
"github.com/LiveSocket/bot/service/socket"
"github.com/gammazero/nexus/v3/wamp"
)
// Update Updates a command
//
// public.command.update
// {channel string, name string, response string, enabled bool, restricted bool, cooldown uint64, scheduled uint64, updated_by string}
//
// Returns [Command]
func Update(service *service.Service) func(*socket.Invocation) socket.Result {
return func(invocation *socket.Invocation) socket.Result {
// Get input args from call
command, err := getUpdateInput(invocation.ArgumentsKw)
if err != nil {
return socket.Error(err)
}
// Update command
err = models.UpdateCommand(service, command)
if err != nil {
return socket.Error(err)
}
// Return updated command
return socket.Success(command)
}
}
func getUpdateInput(kwargs wamp.Dict) (*models.Command, error) {
if kwargs["channel"] == nil {
return nil, errors.New("Missing channel")
}
if kwargs["name"] == nil {
return nil, errors.New("Missing name")
}
enabled, err := conv.ToBool(kwargs["enabled"])
if err != nil {
return nil, err
}
restricted, err := conv.ToBool(kwargs["restricted"])
if err != nil {
return nil, err
}
cooldown, err := conv.ToUint64(kwargs["cooldown"])
if err != nil {
return nil, err
}
schedule, err := conv.ToUint64(kwargs["schedule"])
if err != nil {
return nil, err
}
command := &models.Command{
Channel: conv.ToString(kwargs["channel"]),
Name: conv.ToString(kwargs["name"]),
Response: conv.ToString(kwargs["response"]),
Enabled: enabled,
Restricted: restricted,
Cooldown: cooldown,
Schedule: schedule,
UpdatedBy: conv.ToString(kwargs["updated_by"]),
Description: conv.ToString(kwargs["description"]),
}
return command, nil
}
|
package main
import (
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/blend/go-sdk/env"
"github.com/blend/go-sdk/exception"
"github.com/blend/go-sdk/logger"
"github.com/blend/go-sdk/web"
)
func main() {
log := logger.All()
appStart := time.Now()
app := web.NewFromConfig(web.NewConfigFromEnv()).WithLogger(log)
app.GET("/", func(r *web.Ctx) web.Result {
return r.Text().Result("echo")
})
app.GET("/headers", func(r *web.Ctx) web.Result {
contents, err := json.Marshal(r.Request().Header)
if err != nil {
return r.View().InternalError(err)
}
return r.Text().Result(string(contents))
})
app.GET("/env", func(r *web.Ctx) web.Result {
return r.JSON().Result(env.Env().Vars())
})
app.GET("/error", func(r *web.Ctx) web.Result {
return r.JSON().InternalError(exception.New("This is only a test").WithMessagef("this is a message").WithInner(exception.New("inner exception")))
})
app.GET("/proxy/*filepath", func(r *web.Ctx) web.Result {
return r.JSON().Result("OK!")
})
app.GET("/status", func(r *web.Ctx) web.Result {
if time.Since(appStart) > 12*time.Second {
return r.Text().Result("OK!")
}
return r.Text().InternalError(fmt.Errorf("not ready"))
})
app.GET("/long/:seconds", func(r *web.Ctx) web.Result {
seconds, err := web.IntValue(r.RouteParam("seconds"))
if err != nil {
return r.Text().BadRequest(err)
}
r.Response().WriteHeader(http.StatusOK)
timeout := time.After(time.Duration(seconds) * time.Second)
ticker := time.NewTicker(500 * time.Millisecond)
for {
select {
case <-ticker.C:
{
fmt.Fprintf(r.Response(), "tick\n")
r.Response().InnerResponse().(http.Flusher).Flush()
}
case <-timeout:
{
fmt.Fprintf(r.Response(), "timeout\n")
r.Response().InnerResponse().(http.Flusher).Flush()
return nil
}
}
}
})
app.GET("/echo/*filepath", func(r *web.Ctx) web.Result {
body := r.Request().URL.Path
if len(body) == 0 {
return r.RawWithContentType(web.ContentTypeText, []byte("no response."))
}
return r.RawWithContentType(web.ContentTypeText, []byte(body))
})
app.POST("/echo/*filepath", func(r *web.Ctx) web.Result {
body, err := r.PostBody()
if err != nil {
return r.JSON().InternalError(err)
}
if len(body) == 0 {
return r.RawWithContentType(web.ContentTypeText, []byte("nada."))
}
return r.RawWithContentType(web.ContentTypeText, body)
})
app.WithMethodNotAllowedHandler(func(r *web.Ctx) web.Result {
log.Infof("headers: %#v", r.Request().Header)
body, _ := r.PostBodyAsString()
log.Infof("body: %s", body)
return r.JSON().OK()
})
app.WithNotFoundHandler(func(r *web.Ctx) web.Result {
log.Infof("headers: %#v", r.Request().Header)
body, _ := r.PostBodyAsString()
log.Infof("body: %s", body)
return r.JSON().OK()
})
if err := web.StartWithGracefulShutdown(app); err != nil {
log.SyncFatalExit(err)
}
}
|
package camo
import (
"math"
"net"
"sync"
)
// IPPool assigns ip addresses
type IPPool interface {
Get(cid string) (net.IP, net.IPMask, bool)
Use(ip net.IP, cid string) (net.IPMask, bool)
Free(net.IP)
Gateway() net.IP
}
// SubnetIPPool assigns ip addresses in a subnet segment.
// Currently supports up to 256 allocations.
type SubnetIPPool struct {
subnet *net.IPNet
gw net.IP
bitmap []bool
i int
mu sync.Mutex
}
func iptoi(ip net.IP, subnet *net.IPNet) int {
if !subnet.Contains(ip) {
return -1
}
return int(ip[len(ip)-1] - subnet.IP[len(subnet.IP)-1])
}
func itoip(i int, subnet *net.IPNet) net.IP {
ip := make(net.IP, len(subnet.IP))
copy(ip, subnet.IP)
ip[len(ip)-1] += byte(i)
return ip
}
// NewSubnetIPPool ...
func NewSubnetIPPool(subnet *net.IPNet, gw net.IP, limit int) *SubnetIPPool {
ones, bits := subnet.Mask.Size()
x := bits - ones
if x > 8 {
x = 8
}
size := int(math.Exp2(float64(x)))
if limit > 0 && size > limit {
size = limit
}
p := &SubnetIPPool{
subnet: subnet,
gw: gw,
bitmap: make([]bool, size),
}
p.bitmap[0] = true
if subnet.IP.To4() != nil {
last := itoip(size-1, subnet)
if last[len(last)-1] == 255 {
p.bitmap[size-1] = true
}
}
p.Use(gw, "")
return p
}
// Get ...
func (p *SubnetIPPool) Get(_ string) (ip net.IP, mask net.IPMask, ok bool) {
p.mu.Lock()
defer p.mu.Unlock()
size := len(p.bitmap)
for j := 0; j < size; j++ {
p.i = (p.i + 1) % size
if !p.bitmap[p.i] {
p.bitmap[p.i] = true
return itoip(p.i, p.subnet), p.subnet.Mask, true
}
}
return
}
// Use ...
func (p *SubnetIPPool) Use(ip net.IP, _ string) (mask net.IPMask, ok bool) {
i := iptoi(ip, p.subnet)
if i < 0 || i >= len(p.bitmap) {
return
}
p.mu.Lock()
p.bitmap[i] = true
p.mu.Unlock()
return p.subnet.Mask, true
}
// Free ...
func (p *SubnetIPPool) Free(ip net.IP) {
i := iptoi(ip, p.subnet)
if i < 0 || i >= len(p.bitmap) {
return
}
p.mu.Lock()
p.bitmap[i] = false
p.mu.Unlock()
}
// Gateway ...
func (p *SubnetIPPool) Gateway() net.IP {
return p.gw
}
|
package PrintElevator
import (
"fmt"
"strconv"
"github.com/TTK4145-Students-2021/project-gruppe48/Elevator"
"github.com/TTK4145-Students-2021/project-gruppe48/Elevio"
)
func Print(numFloors int, e Elevator.ElevatorStates, o Elevator.ElevatorOrders) {
p := fmt.Printf
p(" +--------------------+\n")
p(" |floor = %-2d |\n", e.Floor)
p(" |dirn = %-12.12s|\n", dirnToString(e.Direction))
p(" |behav = %-12.12s|\n", ebToString(e.Behaviour))
p(" |Stuck = %-12.12s|\n", strconv.FormatBool(e.Stuck))
p(" +--------------------+\n")
p(" | | up | dn | cab |\n")
for f := numFloors - 1; f >= 0; f-- {
p(" | %d", f)
for btn := 0; btn < Elevator.N_BUTTONS; btn++ {
if f == numFloors-1 && Elevio.ButtonType(btn) == Elevio.BT_HallUp || (f == 0 && Elevio.ButtonType(btn) == Elevio.BT_HallDown) {
p("| ")
} else if o[f][btn] {
p("| # ")
} else {
p("| - ")
}
}
p("|\n")
}
p(" +--------------------+\n")
}
func ebToString(eb Elevator.ElevatorBehaviour) string {
switch eb {
case Elevator.EB_Idle:
return "EB_Idle"
case Elevator.EB_DoorOpen:
return "EB_DoorOpen"
case Elevator.EB_Moving:
return "EB_Moving"
default:
return "EB_Undefined"
}
}
func dirnToString(direction Elevator.ElevatorDirection) string {
switch direction {
case Elevator.ED_Down:
return "D_Down"
case Elevator.ED_Up:
return "D_Up"
case Elevator.ED_Stop:
return "D_Stop"
default:
return "D_UNDEFINED"
}
}
|
package util
import (
"fmt"
"sms-sorter/service/mqtt"
"sms-sorter/service/telegram"
"sms-sorter/util/logger"
"sms-sorter/util/uTime"
"time"
)
func SendFailed(location string, err error) {
t := uTime.GetKST(nil)
msg := fmt.Sprintf("[ERROR/%s]\n=> %s", location, err)
telegram.SendFailedMsg(msg, t)
mqtt.SendFailedMessage(msg, t)
logger.L.Error(msg, " ", t.Format(time.RFC822))
}
func SendStarted(hostname, localIP, pubIP string) {
telegram.SendStarted(hostname, localIP, pubIP)
mqtt.SendStarted(hostname, localIP, pubIP)
}
func SendNormalStopped(hostname, localIP, pubIP string) {
telegram.SendStopped(hostname, localIP, pubIP)
mqtt.SendStopped(hostname, localIP, pubIP)
}
|
package eoy
import (
"fmt"
"time"
)
//Year is used to provide a primary key for storing stats by year.
type Year struct {
ID int
CreatedDate *time.Time
}
//YearResult holds a year and a stats record.
type YearResult struct {
ID int
Stat
}
//YOYear is used to provide a primary key for storing stats by year.
type YOYear struct {
Year
}
//YOYearResult holds a year and a stats record.
type YOYearResult struct {
YearResult
}
//KeyValue implements KeyValuer by returning the value of a key for the
//YearResult object.
func (r YearResult) KeyValue(i int) (key interface{}) {
switch i {
case 0:
key = r.ID
default:
fmt.Printf("Error in YearResult\n%+v\n", r)
err := fmt.Errorf("Not a valid YearResult index, %v", i)
panic(err)
}
return key
}
//FillKeys implements KeyFiller by filling Excel cells with keys from the
//year table.
func (r YearResult) FillKeys(rt *Runtime, sheet Sheet, row, col int) int {
for j := 0; j < len(sheet.KeyNames); j++ {
v := r.KeyValue(j)
s := sheet.KeyStyles[j]
rt.Cell(sheet.Name, row, col+j, v, s)
}
return row
}
//Fill implements Filler by filling in a spreadsheet using data from the years table.
func (y Year) Fill(rt *Runtime, sheet Sheet, row, col int) int {
var a []YearResult
rt.DB.Table("years").Select("years.id, stats.*").Where("years.id = ?", rt.Year).Joins("left join stats on stats.id = years.id").Scan(&a)
for _, r := range a {
rt.Spreadsheet.InsertRow(sheet.Name, row+1)
r.FillKeys(rt, sheet, row, 0)
r.Stat.Fill(rt, sheet.Name, row, len(sheet.KeyNames))
row++
}
return row
}
//NewThisYearSheet builds the data used to decorate the "this year" page.
func (rt *Runtime) NewThisYearSheet() Sheet {
filler := Year{}
result := YearResult{}
name := fmt.Sprintf("%v Summary", rt.Year)
sheet := Sheet{
Titles: []string{
fmt.Sprintf("Results for %v", rt.Year),
},
Name: name,
KeyNames: []string{"Year"},
KeyStyles: []int{rt.KeyStyle},
Filler: filler,
KeyFiller: result,
}
return sheet
}
//KeyValue implements KeyValuer by returning the value of a key for the
//YOYearResult object.
func (r YOYearResult) KeyValue(i int) (key interface{}) {
switch i {
case 0:
key = r.ID
default:
fmt.Printf("Error in YOYearResult\n%+v\n", r)
err := fmt.Errorf("Not a valid YOYearResult index, %v", i)
panic(err)
}
return key
}
//FillKeys implements KeyFiller by filling Excel cells with keys from the
//year table.
func (r YOYearResult) FillKeys(rt *Runtime, sheet Sheet, row, col int) int {
for j := 0; j < len(sheet.KeyNames); j++ {
v := r.KeyValue(j)
s := sheet.KeyStyles[j]
rt.Cell(sheet.Name, row, col+j, v, s)
}
return row
}
//Fill implements Filler by filling in a spreadsheet using data from the years table.
func (y YOYear) Fill(rt *Runtime, sheet Sheet, row, col int) int {
var a []YOYearResult
rt.DB.Order("years.id desc").Table("years").Select("years.id, stats.*").Joins("left join stats on stats.id = years.id").Scan(&a)
for _, r := range a {
rt.Spreadsheet.InsertRow(sheet.Name, row+1)
r.FillKeys(rt, sheet, row, 0)
r.Stat.Fill(rt, sheet.Name, row, len(sheet.KeyNames))
row++
}
return row
}
//NewYOYearSheet builds the data used to decorate the "this year" page.
func (rt *Runtime) NewYOYearSheet() Sheet {
filler := YOYear{}
result := YOYearResult{}
sheet := Sheet{
Titles: []string{
"Year over Year results",
},
Name: "Year over year",
KeyNames: []string{"Year"},
KeyStyles: []int{rt.KeyStyle},
Filler: filler,
KeyFiller: result,
}
return sheet
}
|
package main
import "fmt"
type greeting struct {
name string
}
func (g greeting) Greet() {
fmt.Println("你好" + g.name)
}
func Greet() {
fmt.Println("你好")
}
var Greeter greeting
func init() {
Greeter = greeting{
name: "s",
}
}
|
// GENERATED CODE, DO NOT EDIT
package arrowtools
import (
"github.com/apache/arrow/go/arrow"
"github.com/apache/arrow/go/arrow/array"
"github.com/apache/arrow/go/arrow/memory"
)
// ColumnFromUint8Slices returns a pointer to an array.Column value that
// holds the given uint8 data.
func (sh *SliceHelper) Uint8Column(x [][]uint8, valid [][]bool, name string) *array.Column {
mem := memory.DefaultAllocator
var y []array.Interface
fld := arrow.Field{Name: name, Type: arrow.PrimitiveTypes.Uint8}
bld := array.NewUint8Builder(mem)
for i, z := range x {
var v []bool
if valid != nil {
v = valid[i]
}
bld.AppendValues(z, v)
y = append(y, bld.NewArray())
}
chunks := array.NewChunked(fld.Type, y)
return array.NewColumn(fld, chunks)
}
// ColumnFromUint16Slices returns a pointer to an array.Column value that
// holds the given uint16 data.
func (sh *SliceHelper) Uint16Column(x [][]uint16, valid [][]bool, name string) *array.Column {
mem := memory.DefaultAllocator
var y []array.Interface
fld := arrow.Field{Name: name, Type: arrow.PrimitiveTypes.Uint16}
bld := array.NewUint16Builder(mem)
for i, z := range x {
var v []bool
if valid != nil {
v = valid[i]
}
bld.AppendValues(z, v)
y = append(y, bld.NewArray())
}
chunks := array.NewChunked(fld.Type, y)
return array.NewColumn(fld, chunks)
}
// ColumnFromUint32Slices returns a pointer to an array.Column value that
// holds the given uint32 data.
func (sh *SliceHelper) Uint32Column(x [][]uint32, valid [][]bool, name string) *array.Column {
mem := memory.DefaultAllocator
var y []array.Interface
fld := arrow.Field{Name: name, Type: arrow.PrimitiveTypes.Uint32}
bld := array.NewUint32Builder(mem)
for i, z := range x {
var v []bool
if valid != nil {
v = valid[i]
}
bld.AppendValues(z, v)
y = append(y, bld.NewArray())
}
chunks := array.NewChunked(fld.Type, y)
return array.NewColumn(fld, chunks)
}
// ColumnFromUint64Slices returns a pointer to an array.Column value that
// holds the given uint64 data.
func (sh *SliceHelper) Uint64Column(x [][]uint64, valid [][]bool, name string) *array.Column {
mem := memory.DefaultAllocator
var y []array.Interface
fld := arrow.Field{Name: name, Type: arrow.PrimitiveTypes.Uint64}
bld := array.NewUint64Builder(mem)
for i, z := range x {
var v []bool
if valid != nil {
v = valid[i]
}
bld.AppendValues(z, v)
y = append(y, bld.NewArray())
}
chunks := array.NewChunked(fld.Type, y)
return array.NewColumn(fld, chunks)
}
// ColumnFromInt8Slices returns a pointer to an array.Column value that
// holds the given int8 data.
func (sh *SliceHelper) Int8Column(x [][]int8, valid [][]bool, name string) *array.Column {
mem := memory.DefaultAllocator
var y []array.Interface
fld := arrow.Field{Name: name, Type: arrow.PrimitiveTypes.Int8}
bld := array.NewInt8Builder(mem)
for i, z := range x {
var v []bool
if valid != nil {
v = valid[i]
}
bld.AppendValues(z, v)
y = append(y, bld.NewArray())
}
chunks := array.NewChunked(fld.Type, y)
return array.NewColumn(fld, chunks)
}
// ColumnFromInt16Slices returns a pointer to an array.Column value that
// holds the given int16 data.
func (sh *SliceHelper) Int16Column(x [][]int16, valid [][]bool, name string) *array.Column {
mem := memory.DefaultAllocator
var y []array.Interface
fld := arrow.Field{Name: name, Type: arrow.PrimitiveTypes.Int16}
bld := array.NewInt16Builder(mem)
for i, z := range x {
var v []bool
if valid != nil {
v = valid[i]
}
bld.AppendValues(z, v)
y = append(y, bld.NewArray())
}
chunks := array.NewChunked(fld.Type, y)
return array.NewColumn(fld, chunks)
}
// ColumnFromInt32Slices returns a pointer to an array.Column value that
// holds the given int32 data.
func (sh *SliceHelper) Int32Column(x [][]int32, valid [][]bool, name string) *array.Column {
mem := memory.DefaultAllocator
var y []array.Interface
fld := arrow.Field{Name: name, Type: arrow.PrimitiveTypes.Int32}
bld := array.NewInt32Builder(mem)
for i, z := range x {
var v []bool
if valid != nil {
v = valid[i]
}
bld.AppendValues(z, v)
y = append(y, bld.NewArray())
}
chunks := array.NewChunked(fld.Type, y)
return array.NewColumn(fld, chunks)
}
// ColumnFromInt64Slices returns a pointer to an array.Column value that
// holds the given int64 data.
func (sh *SliceHelper) Int64Column(x [][]int64, valid [][]bool, name string) *array.Column {
mem := memory.DefaultAllocator
var y []array.Interface
fld := arrow.Field{Name: name, Type: arrow.PrimitiveTypes.Int64}
bld := array.NewInt64Builder(mem)
for i, z := range x {
var v []bool
if valid != nil {
v = valid[i]
}
bld.AppendValues(z, v)
y = append(y, bld.NewArray())
}
chunks := array.NewChunked(fld.Type, y)
return array.NewColumn(fld, chunks)
}
// ColumnFromFloat32Slices returns a pointer to an array.Column value that
// holds the given float32 data.
func (sh *SliceHelper) Float32Column(x [][]float32, valid [][]bool, name string) *array.Column {
mem := memory.DefaultAllocator
var y []array.Interface
fld := arrow.Field{Name: name, Type: arrow.PrimitiveTypes.Float32}
bld := array.NewFloat32Builder(mem)
for i, z := range x {
var v []bool
if valid != nil {
v = valid[i]
}
bld.AppendValues(z, v)
y = append(y, bld.NewArray())
}
chunks := array.NewChunked(fld.Type, y)
return array.NewColumn(fld, chunks)
}
// ColumnFromFloat64Slices returns a pointer to an array.Column value that
// holds the given float64 data.
func (sh *SliceHelper) Float64Column(x [][]float64, valid [][]bool, name string) *array.Column {
mem := memory.DefaultAllocator
var y []array.Interface
fld := arrow.Field{Name: name, Type: arrow.PrimitiveTypes.Float64}
bld := array.NewFloat64Builder(mem)
for i, z := range x {
var v []bool
if valid != nil {
v = valid[i]
}
bld.AppendValues(z, v)
y = append(y, bld.NewArray())
}
chunks := array.NewChunked(fld.Type, y)
return array.NewColumn(fld, chunks)
}
// Uint8Column returns a slice of slices holding the
// data from the given column.
func (ch *ColumnHelper) Uint8Slices() [][]uint8 {
var x [][]uint8
for _, c := range ch.col.Data().Chunks() {
x = append(x, array.NewUint8Data(c.Data()).Uint8Values())
}
return x
}
// Uint16Column returns a slice of slices holding the
// data from the given column.
func (ch *ColumnHelper) Uint16Slices() [][]uint16 {
var x [][]uint16
for _, c := range ch.col.Data().Chunks() {
x = append(x, array.NewUint16Data(c.Data()).Uint16Values())
}
return x
}
// Uint32Column returns a slice of slices holding the
// data from the given column.
func (ch *ColumnHelper) Uint32Slices() [][]uint32 {
var x [][]uint32
for _, c := range ch.col.Data().Chunks() {
x = append(x, array.NewUint32Data(c.Data()).Uint32Values())
}
return x
}
// Uint64Column returns a slice of slices holding the
// data from the given column.
func (ch *ColumnHelper) Uint64Slices() [][]uint64 {
var x [][]uint64
for _, c := range ch.col.Data().Chunks() {
x = append(x, array.NewUint64Data(c.Data()).Uint64Values())
}
return x
}
// Int8Column returns a slice of slices holding the
// data from the given column.
func (ch *ColumnHelper) Int8Slices() [][]int8 {
var x [][]int8
for _, c := range ch.col.Data().Chunks() {
x = append(x, array.NewInt8Data(c.Data()).Int8Values())
}
return x
}
// Int16Column returns a slice of slices holding the
// data from the given column.
func (ch *ColumnHelper) Int16Slices() [][]int16 {
var x [][]int16
for _, c := range ch.col.Data().Chunks() {
x = append(x, array.NewInt16Data(c.Data()).Int16Values())
}
return x
}
// Int32Column returns a slice of slices holding the
// data from the given column.
func (ch *ColumnHelper) Int32Slices() [][]int32 {
var x [][]int32
for _, c := range ch.col.Data().Chunks() {
x = append(x, array.NewInt32Data(c.Data()).Int32Values())
}
return x
}
// Int64Column returns a slice of slices holding the
// data from the given column.
func (ch *ColumnHelper) Int64Slices() [][]int64 {
var x [][]int64
for _, c := range ch.col.Data().Chunks() {
x = append(x, array.NewInt64Data(c.Data()).Int64Values())
}
return x
}
// Float32Column returns a slice of slices holding the
// data from the given column.
func (ch *ColumnHelper) Float32Slices() [][]float32 {
var x [][]float32
for _, c := range ch.col.Data().Chunks() {
x = append(x, array.NewFloat32Data(c.Data()).Float32Values())
}
return x
}
// Float64Column returns a slice of slices holding the
// data from the given column.
func (ch *ColumnHelper) Float64Slices() [][]float64 {
var x [][]float64
for _, c := range ch.col.Data().Chunks() {
x = append(x, array.NewFloat64Data(c.Data()).Float64Values())
}
return x
}
|
package api
import (
"MCS_Server/global"
"MCS_Server/middleware"
"MCS_Server/model/request"
"MCS_Server/model/response"
"MCS_Server/service"
"MCS_Server/utils/verify"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"time"
)
// @Tags 账户
// @Summary 用户登录
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.Login true "微信小程序 Appid AppSecret code"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"登录成功"}"
// @Router /account/login [post]
func Login(c *gin.Context) {
var loginMsg request.Login
_ = c.ShouldBindJSON(&loginMsg)
if err := verify.Verify(loginMsg, verify.LoginVerify); err != nil {
response.FailWithMsg(err.Error(), c)
return
}
if err, account := service.Login(loginMsg); err != nil {
global.MCS_Log.Error("登陆失败!"+err.Error(), zap.Any("err", err))
response.FailWithMsg(err.Error(), c)
} else {
j := &middleware.JWT{SigningKey: []byte(global.MCS_Config.JWT.SigningKey)}
claims := request.Claims{
UserId: loginMsg.OpenId,
BufferTime: global.MCS_Config.JWT.BufferTime,
StandardClaims: jwt.StandardClaims{
NotBefore: time.Now().Unix() - 1000,
ExpiresAt: time.Now().Unix() + global.MCS_Config.JWT.ExpiresTime,
Issuer: "MCS_admin",
},
}
token, err := j.CreateToken(claims)
if err != nil {
global.MCS_Log.Error("获取Token失败!", zap.Any("err", err))
response.FailWithMsg(err.Error(), c)
}
response.SuccessWithAll(response.AccountWithToken{
BaseAccount: account, Token: token,
}, "登录成功", c)
}
}
// @Tags 账户
// @Summary 管理员登录
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.Login true "微信小程序 Appid AppSecret code"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"登录成功"}"
// @Router /account/admin [post]
func Admin(c *gin.Context){
var loginMsg request.Login
_ = c.ShouldBindJSON(&loginMsg)
if loginMsg.OpenId == loginMsg.Phone && loginMsg.OpenId == "admin" {
j := &middleware.JWT{SigningKey: []byte(global.MCS_Config.JWT.SigningKey)}
claims := request.Claims{
UserId: loginMsg.OpenId,
BufferTime: global.MCS_Config.JWT.BufferTime,
StandardClaims: jwt.StandardClaims{
NotBefore: time.Now().Unix() - 1000,
ExpiresAt: time.Now().Unix() + global.MCS_Config.JWT.ExpiresTime,
Issuer: "MCS_admin",
},
}
token, err := j.CreateToken(claims)
if err != nil {
global.MCS_Log.Error("获取Token失败!", zap.Any("err", err))
response.FailWithMsg(err.Error(), c)
}
response.SuccessWithAll(token, "登录成功", c)
}
}
|
/*
* Copyright 2021 American Express
*
* 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 writers
import (
"bufio"
"fmt"
"log"
"os"
"sort"
"strconv"
"strings"
"github.com/americanexpress/earlybird/pkg/scan"
)
type issue struct {
k string
c int
}
var issues = make(map[string]int)
//WriteConsole streams hits from the result channel to the command line or target file
func WriteConsole(hits <-chan scan.Hit, fileName string, showFullLine bool) error {
// If no filename was passed in, just print to stdout
if fileName == "" {
// Store a record of the number of each threat found
i := 1
for hit := range hits {
fmt.Println(hitToConsole(hit, i, showFullLine))
issues[hit.Caption]++
i++
}
} else {
err := hitsToFile(hits, fileName, showFullLine)
if err != nil {
log.Fatal("Failed to write results to file", err)
}
}
displayIssues()
return nil
}
func hitsToFile(hits <-chan scan.Hit, fileName string, showFullLine bool) error {
// Store a record of the number of each threat found
i := 1
f, createErr := os.Create(fileName)
if createErr != nil {
return createErr
}
writer := bufio.NewWriter(f)
// Close the file after the function ends
defer func() {
writer.Flush()
f.Sync()
f.Close()
}()
for hit := range hits {
_, err := writer.WriteString(hitToConsole(hit, i, showFullLine))
if err != nil {
return err
}
issues[hit.Caption]++
i++
}
//Get actual file stats for file size
fi, err := f.Stat()
if err != nil {
log.Println(err)
return err
}
fmt.Println(fi.Size(), outputBytesWritten, fileName)
return nil
}
func displayIssues() {
//Sort out values
keyvals := make([]issue, 0, len(issues))
for k, v := range issues {
keyvals = append(keyvals, issue{k, v})
}
sort.Slice(keyvals, func(i, j int) bool {
a, b := keyvals[i], keyvals[j]
// we want to sort by count DESCENDING, but
// alphabetically in the case of a tie.
// sort.Slice takes a function "less" that assumes you're sorting in
// ASCENDING order, so we need to greater than for the counts
// to reverse the order
return a.c > b.c || a.c == b.c && a.k < b.k
})
//Print out our findings summary
fmt.Println(outputTotalIssuesFnd)
var total int
for _, issue := range keyvals {
fmt.Printf("\t%5d %s\n", issue.c, issue.k)
total += issue.c
}
fmt.Printf(outputTotalIssues, total)
}
func hitToConsole(hit scan.Hit, progress int, showFullLine bool) string {
var sb strings.Builder
sb.WriteString(columnFinding + " " + strconv.Itoa(progress) + ":")
sb.WriteString(outputIndent + columnCode + ": " + strconv.Itoa(hit.Code))
sb.WriteString(outputIndent + columnFileName + ": " + hit.Filename)
sb.WriteString(outputIndent + columnCaption + ": " + hit.Caption)
sb.WriteString(outputIndent + columnCategory + ": " + hit.Category)
sb.WriteString(outputIndent + columnLine + ": " + strconv.Itoa(hit.Line))
sb.WriteString(outputIndent + columnValue + ": " + printableASCII(hit.MatchValue))
if showFullLine {
sb.WriteString(outputIndent + columnLineValue + ": " + printableASCII(hit.LineValue))
}
sb.WriteString(outputIndent + columnSeverity + ": " + hit.Severity)
sb.WriteString(outputIndent + columnConfidence + ": " + hit.Confidence)
sb.WriteString(outputIndent + columnLabels + ": " + displayCWE(hit.Labels))
sb.WriteString(outputIndent + columnCWE + ": " + displayCWE(hit.CWE))
if hit.Solution != "" {
sb.WriteString(outputIndent + columnSolution + ": " + hit.Solution)
}
sb.WriteString("\n")
return sb.String()
}
func displayCWE(cwe []string) (result string) {
if len(cwe) > 0 {
result = strings.Join(cwe, outputArraySeparator)
} else {
result = outputNone
}
return result
}
// strip control characters, DELETE, and non-ASCII unicode from the string.
func printableASCII(s string) string {
printable := make([]byte, 0, len(s))
for _, b := range []byte(s) {
if b >= 32 && b < 127 {
printable = append(printable, b)
}
}
return string(printable)
}
|
package main
import (
"flag"
"fmt"
"os"
"github.com/unprofession-al/mystrom"
)
func must(err error) {
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func main() {
d := flag.String("d", "", "IP or hostname of the myStrom Switch device")
a := flag.String("a", "toggle", "action to execute, can be [on, off, toggle, report, temp]")
flag.Parse()
s, err := mystrom.NewSwitch(*d)
must(err)
switch *a {
case "toggle":
err := s.Toggle()
must(err)
case "on":
err := s.On()
must(err)
case "off":
err := s.Off()
must(err)
case "report":
r, err := s.Report()
must(err)
if r.Relay {
fmt.Printf("The Switch is turned on, the current power consumption is %f\n", r.Power)
} else {
fmt.Println("The Switch is turned off")
}
case "temp":
t, err := s.Temperature()
must(err)
fmt.Printf("The current Switch temperature is %f°C\n", t.Compensated)
default:
err := fmt.Errorf("Action '%s' is not defined\n", *a)
must(err)
}
}
|
package search
/*
Given a sorted array arr[] of n elements, return the index of a given element x in arr[].
Binary Search: Search a sorted array by repeatedly dividing the search interval in half.
Begin with an interval covering the whole array. If the value of the search key is less
than the item in the middle of the interval, narrow the interval to the lower half.
Otherwise narrow it to the upper half. Repeatedly check until the value is found or the
interval is empty.
time complexity: O(Log n).
*/
// RecursiveBinarySearch as Recursive implementation of Binary Search
// li : left index
// ri : right index
func RecursiveBinarySearch(elements []int, x, li, ri int) int {
if ri >= li {
mid := li + (ri-li)/2
if elements[mid] == x {
return mid
} else if elements[mid] > x {
return RecursiveBinarySearch(elements, x, li, mid-1)
}
return RecursiveBinarySearch(elements, x, mid+1, ri)
}
return -1
}
func IterativeBinarySearch(elements []int, x int) int {
left := 0
right := len(elements) - 1
for left <= right {
mid := left + (right-left)/2
if elements[mid] == x {
return mid
} else if elements[mid] < x {
left = mid + 1
} else {
right = mid - 1
}
}
return -1
}
|
package uiresource
import (
"context"
"fmt"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"sigs.k8s.io/controller-runtime/pkg/cache"
ctrlclient "sigs.k8s.io/controller-runtime/pkg/client"
"github.com/tilt-dev/tilt/internal/controllers/apicmp"
"github.com/tilt-dev/tilt/internal/hud/webview"
"github.com/tilt-dev/tilt/internal/store"
"github.com/tilt-dev/tilt/pkg/apis/core/v1alpha1"
)
// UIResource objects are created/deleted by the Tiltfile controller.
//
// This subscriber only updates their status.
type Subscriber struct {
client ctrlclient.Client
}
func NewSubscriber(client ctrlclient.Client) *Subscriber {
return &Subscriber{
client: client,
}
}
func (s *Subscriber) currentResources(store store.RStore, disableSources map[string][]v1alpha1.DisableSource) ([]*v1alpha1.UIResource, error) {
state := store.RLockState()
defer store.RUnlockState()
return webview.ToUIResourceList(state, disableSources)
}
func (s *Subscriber) OnChange(ctx context.Context, st store.RStore, summary store.ChangeSummary) error {
if summary.IsLogOnly() {
return nil
}
// Collect a list of all the resources to reconcile and their most recent version.
storedList := &v1alpha1.UIResourceList{}
err := s.client.List(ctx, storedList)
if err != nil {
// If the cache hasn't started yet, that's OK.
// We'll get it on the next OnChange()
if _, ok := err.(*cache.ErrCacheNotStarted); ok {
return nil
}
return err
}
storedMap := make(map[string]v1alpha1.UIResource)
disableSources := make(map[string][]v1alpha1.DisableSource)
for _, r := range storedList.Items {
storedMap[r.Name] = r
disableSources[r.Name] = r.Status.DisableStatus.Sources
}
currentResources, err := s.currentResources(st, disableSources)
if err != nil {
st.Dispatch(store.NewErrorAction(fmt.Errorf("cannot convert UIResource: %v", err)))
return nil
}
errs := []error{}
for _, r := range currentResources {
stored, isStored := storedMap[r.Name]
if !isStored {
continue
}
reconcileConditions(r.Status.Conditions, stored.Status.Conditions)
if !apicmp.DeepEqual(r.Status, stored.Status) {
// If the current version is different than what's stored, update it.
update := stored.DeepCopy()
update.Status = r.Status
err = s.client.Status().Update(ctx, update)
if err != nil {
errs = append(errs, err)
}
continue
}
}
return utilerrors.NewAggregate(errs)
}
// Update the LastTransitionTime against the currently stored conditions.
func reconcileConditions(conds []v1alpha1.UIResourceCondition, stored []v1alpha1.UIResourceCondition) {
storedMap := make(map[v1alpha1.UIResourceConditionType]v1alpha1.UIResourceCondition, len(stored))
for _, c := range stored {
storedMap[c.Type] = c
}
for i, c := range conds {
existing, ok := storedMap[c.Type]
if !ok {
continue
}
// If the status hasn't changed, fall back to the previous transition time.
if existing.Status == c.Status {
c.LastTransitionTime = existing.LastTransitionTime
}
conds[i] = c
}
}
var _ store.Subscriber = &Subscriber{}
|
package main
import (
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
)
func helloHandler(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, "Hello, world!\n")
fmt.Println("-----Method:")
fmt.Println(req.Method)
fmt.Println("")
fmt.Println("-----Header:")
fmt.Println(req.Header)
for k, v := range req.Header {
fmt.Printf("key:%v value:%v \n", k, v)
}
fmt.Println("")
fmt.Printf("RemoteAddr is:%s \n", req.RemoteAddr)
s, _ := ioutil.ReadAll(req.Body)
fmt.Println("-----Body:")
fmt.Printf("%s \n", s)
fmt.Println("")
fmt.Fprintf(w, "Hello, World!")
}
func main() {
http.HandleFunc("/hello", helloHandler)
fmt.Println("listening 47.89.43.129:10000")
log.Fatal(http.ListenAndServe(":10000", nil))
}
|
package center
import (
"common"
)
func (self *Center) del(table string, key string) (err error) {
return common.Redis_del(self.maincache, table, key)
}
func (self *Center) setInt(table string, key string, value int) (err error) {
return common.Redis_setInt(self.maincache, table, key, value)
}
func (self *Center) getInt(table string, key string) (value int, err error) {
return common.Redis_getInt(self.maincache, table, key)
}
func (self *Center) setString(table string, key string, value string) (err error) {
return common.Redis_setString(self.maincache, table, key, value)
}
func (self *Center) getString(table string, key string) (value string, err error) {
return common.Redis_getString(self.maincache, table, key)
}
func (self *Center) setexpire(table string, key string, time string) (err error) {
return common.Redis_setexpire(self.maincache, table, key, time)
}
func (self *Center) sadd(table string, key string, value string) (err error) {
return common.Redis_sadd(self.maincache, table, key, value)
}
func (self *Center) srem(table string, key string, value string) (err error) {
return common.Redis_srem(self.maincache, table, key, value)
}
func (self *Center) exists(table string, key string) bool {
return common.Redis_exists(self.maincache, table, key)
}
func (self *Center) scard(table string, key string) (num int) {
return common.Redis_scard(self.maincache, table, key)
}
func (self *Center) srandmember(table string, key string) (value string, err error) {
return common.Redis_srandmember(self.maincache, table, key)
}
func (self *Center) zadd(table string, key string, value string, score uint32) (err error) {
return common.Redis_zadd(self.maincache, table, key, value, score)
}
func (self *Center) zrem(table string, key string, value string) (err error) {
return common.Redis_zrem(self.maincache, table, key, value)
}
func (self *Center) zcard(table string, key string) (uint32, error) {
return common.Redis_zcard(self.maincache, table, key)
}
func (self *Center) zscore(table string, key string, value string) (uint32, error) {
return common.Redis_zscore(self.maincache, table, key, value)
}
func (self *Center) zrevrange(table string, key string, start int, stop int) (rets []string, err error) {
return common.Redis_zrevrange(self.maincache, table, key, start, stop)
}
func (self *Center) zrevrank(table string, key string, value string) (uint32, error) {
return common.Redis_zrevrank(self.maincache, table, key, value)
}
/*func (self *Center) keys(table string, key string) (rets []string, err error) {
return common.Redis_keys(self.maincache, table, key)
}*/
func (self *Center) hset(table string, key string, field string, value string) (err error) {
return common.Redis_hset(self.maincache, table, key, field, value)
}
func (self *Center) hgetall(table string, key string) (rets []string, err error) {
return common.Redis_hgetall(self.maincache, table, key)
}
//add for seach myself
func (self *Center) zrank(table, key, value string) (rank int, err error) {
return common.Redis_zrank(self.maincache, table, key, value)
}
func (self *Center) delData(tableName, keyName string) error {
return common.Redis_del(self.maincache, tableName, keyName)
}
func (self *Center) hgetValue(tableName string, keyName, fieldName string) (number int, err error) {
return common.Redis_hGet(self.maincache, tableName, keyName, fieldName)
}
func (self *Center) hsetValue(table string, key string, field string, value string) error {
return common.Redis_hset(self.maincache, table, key, field, value)
}
func (self *Center) hreName(tableName, oldKeyName, newKeyName string) error {
return common.Redis_hRename(self.maincache, tableName, oldKeyName, newKeyName)
}
|
package api
import "testing"
func TestDefaultStorer(t *testing.T) {
s := &DefaultStorer{}
if _, _, err := s.List(nil, nil, nil); err != ErrNotImplemented {
t.Errorf("List(): expected error ErrNotImplemented, got %v", err)
}
if err := s.Create(nil, nil, nil); err != ErrNotImplemented {
t.Errorf("Create(): expected error ErrNotImplemented, got %v", err)
}
if err := s.Read(nil, nil, nil); err != ErrNotImplemented {
t.Errorf("Read(): expected error ErrNotImplemented, got %v", err)
}
if err := s.Update(nil, nil, nil); err != ErrNotImplemented {
t.Errorf("Update(): expected error ErrNotImplemented, got %v", err)
}
if err := s.Delete(nil, nil, nil); err != ErrNotImplemented {
t.Errorf("Delete(): expected error ErrNotImplemented, got %v", err)
}
}
|
package handler
import (
"net/http"
jwtConfig "github.com/RudyDamara/golang/lib/jwt"
"github.com/RudyDamara/golang/lib/models"
"github.com/RudyDamara/golang/pkg/user_login/structs"
"github.com/labstack/echo"
)
func (h *HTTPHandler) ToLogout(c echo.Context) error {
dataUser := jwtConfig.GetDataUser(c)
model := structs.User{
ID: dataUser.ID,
}
result := <-h.model.Logout(model)
if result.Error != nil {
resp := &models.Response{Code: 400, MessageCode: 0, Message: result.Error.Error()}
return c.JSON(http.StatusBadRequest, resp)
}
return c.JSON(http.StatusOK, result.Data)
}
|
package persistent
import "time"
type DataQuery struct {
StartDate time.Time
EndDate time.Time
MinCount int
MaxCount int
}
type DataQueryRecord struct {
Key string `bson:"key"`
CreatedAt time.Time `bson:"createdAt"`
TotalCount int `bson:"totalCount"`
}
|
package parser
import (
"errors"
"strings"
)
// ParseClass handles the specific parsing of a package class.
func (p *Parser) ParseClass() (err error) {
// Set one time switches
URLSet := false
GitURLSet := false
HomepageSet := false
token := p.scnr.Peak()
if !token.IsClass() {
return errors.New("called ParseClass without the beginning token being a class defintion")
}
_, err = p.scnr.Next()
if err != nil {
return err
}
err = p.ParseClassName()
if err != nil {
return err
}
err = p.scnr.NextLine()
if err != nil {
return err
}
for {
token := p.scnr.Peak()
switch {
// Skip line when comment seen.
case strings.HasPrefix(token.Data, "#"):
err = p.scnr.NextLine()
if err != nil {
break
}
continue
case strings.HasPrefix(token.Data, `"""`):
p.result.Description, err = p.ParseString()
case token.IsBracket():
err = p.ParseBracket()
if err != nil {
return err
}
continue
case token.IsString():
_, err = p.ParseString()
case token.IsHomepage() && !HomepageSet:
p.result.Homepage, err = p.ParseHomepage()
HomepageSet = true
case token.IsURL() && !URLSet:
p.result.URL, err = p.ParseURL()
URLSet = true
case token.IsMaintainers():
p.result.Maintainers, err = p.ParseMaintainers()
case token.IsGitURL() && !GitURLSet:
p.result.GitURL, err = p.ParseGitURL()
GitURLSet = true
case token.IsVersion():
version, err := p.ParseVersion()
if err != nil {
return err
}
p.result.AddVersion(version)
case token.IsDependency():
dependency, err := p.ParseDependency()
if err != nil {
return err
}
p.result.Dependencies = append(p.result.Dependencies, dependency)
case token.IsFunction():
result, err := p.ParseFunction()
p.result.BuildInstructions += result
if err != nil {
return err
}
continue
}
if err != nil {
return err
}
_, err = p.scnr.Next()
if err != nil {
break
}
}
return err
}
// ParseClassName take care of parsing the name of a package.
func (p *Parser) ParseClassName() (err error) {
token := p.scnr.Peak()
data := strings.Split(strings.TrimRight(token.Data, "):"), "(")
if len(data) != 2 {
return errors.New("could not find package name and type")
}
p.result.Name = data[0]
p.result.PackageType = data[1]
return nil
}
|
// Licensed to Comcast Cable Communications Management, LLC under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Comcast Cable Communications Management, LLC licenses this file to you 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 filter
import (
"github.com/xmidt-org/ears/internal/pkg/syncer"
"github.com/xmidt-org/ears/pkg/secret"
"github.com/xmidt-org/ears/pkg/tenant"
"sync"
"github.com/xmidt-org/ears/pkg/event"
)
//go:generate rm -f testing_mock.go
//go:generate moq -out testing_mock.go . Hasher NewFilterer Filterer Chainer
// InvalidConfigError is returned when a configuration parameter
// results in a plugin error
type InvalidConfigError struct {
Err error
}
type InvalidArgumentError struct {
Err error
}
// Hasher defines the hashing interface that a receiver
// needs to implement
type Hasher interface {
// FiltererHash calculates the hash of a filterer based on the
// given configuration
FiltererHash(config interface{}) (string, error)
}
// NewFilterer defines the interface on how to
// to create a new filterer
type NewFilterer interface {
Hasher
// NewFilterer returns an object that implements the Filterer interface
NewFilterer(tid tenant.Id, plugin string, name string, config interface{}, secrets secret.Vault, tableSyncer syncer.DeltaSyncer) (Filterer, error)
}
// Filterer defines the interface that a filterer must implement
type Filterer interface {
Filter(e event.Event) []event.Event
Config() interface{}
Name() string
Plugin() string
Tenant() tenant.Id
EventSuccessCount() int
EventSuccessVelocity() int
EventFilterCount() int
EventFilterVelocity() int
EventErrorCount() int
EventErrorVelocity() int
EventTs() int64
}
// Chainer
type Chainer interface {
Filterer
// Add will add a filterer to the chain
Add(f Filterer) error
Filterers() []Filterer
}
var _ Chainer = (*Chain)(nil)
type Chain struct {
sync.RWMutex
filterers []Filterer
}
|
// Copyright 2018 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 strace
import (
"gvisor.dev/gvisor/pkg/abi"
"gvisor.dev/gvisor/pkg/abi/linux"
)
// OpenMode represents the mode to open(2) a file.
var OpenMode = abi.ValueSet{
linux.O_RDWR: "O_RDWR",
linux.O_WRONLY: "O_WRONLY",
linux.O_RDONLY: "O_RDONLY",
}
// OpenFlagSet is the set of open(2) flags.
var OpenFlagSet = abi.FlagSet{
{
Flag: linux.O_APPEND,
Name: "O_APPEND",
},
{
Flag: linux.O_ASYNC,
Name: "O_ASYNC",
},
{
Flag: linux.O_CLOEXEC,
Name: "O_CLOEXEC",
},
{
Flag: linux.O_CREAT,
Name: "O_CREAT",
},
{
Flag: linux.O_DIRECT,
Name: "O_DIRECT",
},
{
Flag: linux.O_DIRECTORY,
Name: "O_DIRECTORY",
},
{
Flag: linux.O_EXCL,
Name: "O_EXCL",
},
{
Flag: linux.O_NOATIME,
Name: "O_NOATIME",
},
{
Flag: linux.O_NOCTTY,
Name: "O_NOCTTY",
},
{
Flag: linux.O_NOFOLLOW,
Name: "O_NOFOLLOW",
},
{
Flag: linux.O_NONBLOCK,
Name: "O_NONBLOCK",
},
{
Flag: 0x200000, // O_PATH
Name: "O_PATH",
},
{
Flag: linux.O_SYNC,
Name: "O_SYNC",
},
{
Flag: linux.O_TMPFILE,
Name: "O_TMPFILE",
},
{
Flag: linux.O_TRUNC,
Name: "O_TRUNC",
},
}
func open(val uint64) string {
s := OpenMode.Parse(val & linux.O_ACCMODE)
if flags := OpenFlagSet.Parse(val &^ linux.O_ACCMODE); flags != "" {
s += "|" + flags
}
return s
}
|
package solutions
import (
"sort"
)
func permuteUnique(nums []int) [][]int {
if len(nums) == 0 {
return nil
}
sort.Ints(nums)
result := make([][]int, 0)
backtrackUnique(nums, nil, &result)
return result
}
func backtrackUnique(nums []int, previous []int, result *[][]int) {
if len(nums) == 0 {
*result = append(*result, append([]int{}, previous...))
return
}
for i := 0; i < len(nums); i++ {
if i != 0 && nums[i] == nums[i - 1] {
continue
}
current := append(append([]int{}, nums[0:i]...), nums[i + 1:]...)
backtrackUnique(current, append(previous, nums[i]), result)
}
}
|
package mfcc
import (
"math/rand"
"testing"
)
const fftBenchSize = 512
func TestFFT(t *testing.T) {
inputs := [][]float64{
[]float64{0.517450},
[]float64{0.517450, -0.515357},
[]float64{0.517450, 0.591873, 0.104983, -0.512010},
[]float64{0.517450, 0.591873, 0.104983, -0.512010, -0.037091, 0.203369,
0.452477, -0.452457, 0.873007, 0.134188, -0.515357, 0.864060, 0.838039, 0.618038,
-0.729226, 0.949877},
}
outputs := [][]float64{
[]float64{0.517450},
[]float64{0.0020930, 1.0328070},
[]float64{0.70230, 0.41247, 0.54257, 1.10388},
[]float64{3.901220, 0.598021, 0.624881, 1.641404, 2.878528, -1.558631,
0.554137, -2.103022, -0.892656, -1.616822, -0.303837, 1.961911, 0.697998,
-2.336823, -0.036587, -2.415035},
}
for i, input := range inputs {
expected := outputs[i]
res := fft(input)
actual := append(res.Cos, res.Sin...)
if len(actual) != len(expected) {
t.Errorf("%d: len should be %d but it's %d", i, len(expected), len(actual))
} else if !slicesClose(actual, expected) {
t.Errorf("%d: expected %v but got %v", i, expected, actual)
}
}
}
func TestFFTPower(t *testing.T) {
inputs := [][]float64{
[]float64{0.123},
[]float64{1, -2, 3, -2},
[]float64{0.517450, 0.591873, 0.104983, -0.512010, -0.037091, 0.203369,
0.452477, -0.452457, 0.873007, 0.134188, -0.515357, 0.864060, 0.838039, 0.618038,
-0.729226, 0.949877},
}
outputs := [][]float64{
[]float64{0.015129},
[]float64{0, 1, 16},
[]float64{0.951220, 0.185734, 0.030175, 0.408956, 0.548320,
0.493129, 0.019275, 0.640944, 0.049802},
}
for i, input := range inputs {
actual := fft(input).powerSpectrum()
expected := outputs[i]
if len(actual) != len(expected) {
t.Errorf("%d: expected len %d but got len %d", i, len(expected), len(actual))
} else if !slicesClose(actual, expected) {
t.Errorf("%d: expected %v but got %v", i, expected, actual)
}
}
}
func BenchmarkFFT(b *testing.B) {
rand.Seed(123)
inputVec := make([]float64, fftBenchSize)
for i := range inputVec {
inputVec[i] = rand.NormFloat64()
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
fft(inputVec)
}
}
|
// SPDX-License-Identifier: ISC
// Copyright (c) 2014-2020 Bitmark Inc.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package chain
// names of all chains
const (
Bitmark = "bitmark"
Testing = "testing"
Local = "local"
)
// Valid - validate a chain name
func Valid(name string) bool {
switch name {
case Bitmark, Testing, Local:
return true
default:
return false
}
}
|
package mws
import "encoding/json"
// StsRole is the object that contains cross account role arn and external app id
type StsRole struct {
RoleArn string `json:"role_arn,omitempty"`
ExternalID string `json:"external_id,omitempty"`
}
// AwsCredentials is the object that points to the cross account role
type AwsCredentials struct {
StsRole *StsRole `json:"sts_role,omitempty"`
}
// Credentials is the object that contains all the information for the credentials to create a workspace
type Credentials struct {
CredentialsID string `json:"credentials_id,omitempty"`
CredentialsName string `json:"credentials_name,omitempty"`
AwsCredentials *AwsCredentials `json:"aws_credentials,omitempty"`
AccountID string `json:"account_id,omitempty"`
CreationTime int64 `json:"creation_time,omitempty"`
}
// RootBucketInfo points to a bucket name
type RootBucketInfo struct {
BucketName string `json:"bucket_name,omitempty"`
}
// StorageConfiguration is the object that contains all the information for the root storage bucket
type StorageConfiguration struct {
StorageConfigurationID string `json:"storage_configuration_id,omitempty"`
StorageConfigurationName string `json:"storage_configuration_name,omitempty"`
RootBucketInfo *RootBucketInfo `json:"root_bucket_info,omitempty"`
AccountID string `json:"account_id,omitempty"`
CreationTime int64 `json:"creation_time,omitempty"`
}
// NetworkHealth is the object that contains all the error message when attaching a network to workspace
type NetworkHealth struct {
ErrorType string `json:"error_type,omitempty"`
ErrorMessage string `json:"error_message,omitempty"`
}
// NetworkVPCEndpoints is the object that contains VPC endpoints of a network
type NetworkVPCEndpoints struct {
RestAPI []string `json:"rest_api" tf:"slice_set"`
DataplaneRelayAPI []string `json:"dataplane_relay" tf:"slice_set"`
}
// Network is the object that contains all the information for BYOVPC
type Network struct {
AccountID string `json:"account_id"`
NetworkID string `json:"network_id,omitempty" tf:"computed"`
NetworkName string `json:"network_name"`
VPCID string `json:"vpc_id"`
SubnetIds []string `json:"subnet_ids" tf:"slice_set"`
VPCEndpoints *NetworkVPCEndpoints `json:"vpc_endpoints,omitempty" tf:"computed"`
SecurityGroupIds []string `json:"security_group_ids" tf:"slice_set"`
VPCStatus string `json:"vpc_status,omitempty" tf:"computed"`
ErrorMessages []NetworkHealth `json:"error_messages,omitempty" tf:"computed"`
WorkspaceID int64 `json:"workspace_id,omitempty" tf:"computed"`
CreationTime int64 `json:"creation_time,omitempty" tf:"computed"`
}
// List of workspace statuses for provisioning the workspace
const (
WorkspaceStatusNotProvisioned = "NOT_PROVISIONED"
WorkspaceStatusProvisioning = "PROVISIONING"
WorkspaceStatusRunning = "RUNNING"
WorkspaceStatusFailed = "FAILED"
WorkspaceStatusCanceled = "CANCELLED"
)
// WorkspaceStatusesNonRunnable is a list of statuses in which the workspace is not runnable
var WorkspaceStatusesNonRunnable = []string{WorkspaceStatusCanceled, WorkspaceStatusFailed}
type GCP struct {
ProjectID string `json:"project_id"`
}
type CloudResourceBucket struct {
GCP *GCP `json:"gcp"`
}
type GCPManagedNetworkConfig struct {
SubnetCIDR string `json:"subnet_cidr"`
GKEClusterPodIPRange string `json:"gke_cluster_pod_ip_range"`
GKEClusterServiceIPRange string `json:"gke_cluster_service_ip_range"`
}
type GCPCommonNetworkConfig struct {
GKEConnectivityType string `json:"gke_connectivity_type"`
GKEClusterMasterIPRange string `json:"gke_cluster_master_ip_range"`
}
type GCPNetwork struct {
GCPManagedNetworkConfig *GCPManagedNetworkConfig `json:"gcp_managed_network_config"`
GCPCommonNetworkConfig *GCPCommonNetworkConfig `json:"gcp_common_network_config"`
}
// Workspace is the object that contains all the information for deploying a workspace
type Workspace struct {
AccountID string `json:"account_id"`
WorkspaceName string `json:"workspace_name"`
DeploymentName string `json:"deployment_name,omitempty"`
AwsRegion string `json:"aws_region,omitempty"` // required for AWS, not allowed for GCP
CredentialsID string `json:"credentials_id,omitempty"` // required for AWS, not allowed for GCP
CustomerManagedKeyID string `json:"customer_managed_key_id,omitempty"` // just for compatibility, will be removed
StorageConfigurationID string `json:"storage_configuration_id,omitempty"` // required for AWS, not allowed for GCP
ManagedServicesCustomerManagedKeyID string `json:"managed_services_customer_managed_key_id,omitempty"`
StorageCustomerManagedKeyID string `json:"storage_customer_managed_key_id,omitempty"`
PricingTier string `json:"pricing_tier,omitempty" tf:"computed"`
PrivateAccessSettingsID string `json:"private_access_settings_id,omitempty"`
NetworkID string `json:"network_id,omitempty"`
IsNoPublicIPEnabled bool `json:"is_no_public_ip_enabled"`
WorkspaceID int64 `json:"workspace_id,omitempty" tf:"computed"`
WorkspaceURL string `json:"workspace_url,omitempty" tf:"computed"`
WorkspaceStatus string `json:"workspace_status,omitempty" tf:"computed"`
WorkspaceStatusMessage string `json:"workspace_status_message,omitempty" tf:"computed"`
CreationTime int64 `json:"creation_time,omitempty" tf:"computed"`
ExternalCustomerInfo *externalCustomerInfo `json:"external_customer_info,omitempty"`
CloudResourceBucket *CloudResourceBucket `json:"cloud_resource_bucket,omitempty"`
Network *GCPNetwork `json:"network,omitempty"`
Cloud string `json:"cloud,omitempty" tf:"computed"`
Location string `json:"location,omitempty"`
}
// this type alias hack is required for Marshaller to work without an infinite loop
type aWorkspace Workspace
// MarshalJSON is required to overcome the limitations of `omitempty` usage with reflect_resource.go
// for workspace creation in Accounts API for AWS and GCP. It exits early on AWS and picks only
// the relevant fields for GCP.
func (w *Workspace) MarshalJSON() ([]byte, error) {
if w.Cloud != "gcp" {
return json.Marshal(aWorkspace(*w))
}
workspaceCreationRequest := map[string]interface{}{
"account_id": w.AccountID,
"cloud": w.Cloud,
"cloud_resource_bucket": w.CloudResourceBucket,
"location": w.Location,
"workspace_name": w.WorkspaceName,
}
if w.Network != nil {
workspaceCreationRequest["network"] = w.Network
}
return json.Marshal(workspaceCreationRequest)
}
// VPCEndpoint is the object that contains all the information for registering an VPC endpoint
type VPCEndpoint struct {
VPCEndpointID string `json:"vpc_endpoint_id,omitempty" tf:"computed"`
AwsVPCEndpointID string `json:"aws_vpc_endpoint_id"`
AccountID string `json:"account_id,omitempty"`
VPCEndpointName string `json:"vpc_endpoint_name"`
AwsVPCEndpointServiceID string `json:"aws_endpoint_service_id,omitempty" tf:"computed"`
AWSAccountID string `json:"aws_account_id,omitempty" tf:"computed"`
UseCase string `json:"use_case,omitempty" tf:"computed"`
Region string `json:"region"`
State string `json:"state,omitempty" tf:"computed"`
}
// PrivateAccessSettings (PAS) is the object that contains all the information for creating an PrivateAccessSettings (PAS)
type PrivateAccessSettings struct {
AccountID string `json:"account_id,omitempty"`
PasID string `json:"private_access_settings_id,omitempty" tf:"computed"`
PasName string `json:"private_access_settings_name"`
Region string `json:"region"`
Status string `json:"status,omitempty" tf:"computed"`
PublicAccessEnabled bool `json:"public_access_enabled,omitempty"`
PrivateAccessLevel string `json:"private_access_level,omitempty" tf:"default:ANY"`
AllowedVpcEndpointIDS []string `json:"allowed_vpc_endpoint_ids,omitempty"`
}
type externalCustomerInfo struct {
CustomerName string `json:"customer_name"`
AuthoritativeUserEmail string `json:"authoritative_user_email"`
AuthoritativeUserFullName string `json:"authoritative_user_full_name"`
}
|
package simplepaste
import (
"net/url"
"net/http"
"bytes"
)
//look defines.go
type Paste struct {
Text string
Name string
Privacy string
ExpireDate string
//You have to get it by .GetUserKey method, if you want to create private paste
UserKey string
}
func NewPaste(name string, text string) Paste {
return Paste{
Text: text,
Name: name,
Privacy: Public,
ExpireDate: Never,
}
}
type API struct {
APIKey string
}
func NewAPI(api_key string) *API {
return &API{
APIKey: api_key,
}
}
//Returns paste link string and nil if everything is ok
func (api * API) SendPaste(paste Paste) (string, error) {
if paste.UserKey == "" && paste.Privacy == "2" {
return "", PrivacyModError
}
values := url.Values{}
values.Set("api_dev_key", api.APIKey)
values.Set("api_user_key", paste.UserKey)
values.Set("api_option", "paste")
values.Set("api_paste_code", paste.Text)
values.Set("api_paste_name", paste.Name)
values.Set("api_paste_private", paste.Privacy)
values.Set("api_paste_expire_date", paste.ExpireDate)
response, err := http.PostForm("https://pastebin.com/api/api_post.php", values)
defer response.Body.Close()
if err != nil {
return "", err
}
if response.StatusCode != 200 {
return "", PastePostingError
}
buf := bytes.Buffer{}
_, err = buf.ReadFrom(response.Body)
if err != nil {
return "", err
}
return buf.String(), nil
}
//Returns raw paste text
func (api * API) GetPasteTextById(paste_id string) (string, error) {
response, err := http.Get("https://pastebin.com/raw.php?i=" + paste_id)
defer response.Body.Close()
if err != nil {
return "", err
}
if response.StatusCode != 200 {
return "", PasteGetError
}
buf := bytes.Buffer{}
_, err = buf.ReadFrom(response.Body)
if err != nil {
return "", err
}
return buf.String(), nil
}
func (api * API) GetUserKey(username string, password string)(string, error) {
values := url.Values{}
values.Set("api_dev_key", api.APIKey)
values.Set("api_user_name", username)
values.Set("api_user_password", password)
req, err := http.NewRequest("POST", "https://pastebin.com/api/api_login.php", bytes.NewBufferString(values.Encode()))
client := &http.Client{}
response, err := client.Do(req)
if err != nil {
return "", err
}
defer response.Body.Close()
buf := bytes.Buffer{}
_, err = buf.ReadFrom(response.Body)
return buf.String(), err
}
|
package vector
import "testing"
func TestVectorNew(t *testing.T) {
v := New(1, 3, 5)
if len(v.data) != 3 {
t.Error("NewVector failed")
}
}
func TestVectorNormal(t *testing.T) {
v := New(1, 3, 5)
if v.Count() != 3 {
t.Error("VectorNormal 0 failed")
}
if v.data[0] != 1 || v.data[1] != 3 || v.data[2] != 5 {
t.Error("VectorNormal 1 failed")
}
}
func TestVectorDot(t *testing.T) {
v := New(1, 3, 5)
dot := v.Dot(New(2, 4, 6))
if dot != (1*2 + 3*4 + 5*6) {
t.Error("VectorDot failed")
}
}
func TestVectorLength(t *testing.T) {
v := New(3, 4)
if int(v.Length()) != 5 {
t.Error("VectorLength failed")
}
}
func TestVectorCos(t *testing.T) {
if int(New(0, 1).Cos(New(1, 0))) != 0 {
t.Error("VectorCos 0 failed")
}
if int(New(0, 1).Cos(New(0, 1))) != 1 {
t.Error("VectorCos 1 failed")
}
}
func TestVectorNormalize(t *testing.T) {
if int(New(1, 3, 5).Normalize().Length()) != 1 {
t.Error("VectorNormalize failed")
}
}
func TestVectorToArray(t *testing.T) {
v := New(1, 3, 5)
f := v.ToArray()
f[1] = 2
if v.data[1] == 2 {
t.Error("VectorToArray failed")
}
}
func TestVectorAsArray(t *testing.T) {
v := New(1, 3, 5)
f := v.AsArray()
f[1] = 2
if v.data[1] != 2 {
t.Error("VectorAsArray failed")
}
}
func TestVectorAdd(t *testing.T) {
v := New(1, 3, 5).Add(New(-1, 0, -5))
if v.data[0] != 0 || v.data[1] != 3 || v.data[2] != 0 {
t.Error("VectorAdd failed")
}
}
func TestVectorMul(t *testing.T) {
v := New(1, 3, 5).Mul(2)
if int(v.data[0]) != 2 || int(v.data[1]) != 6 || int(v.data[2]) != 10 {
t.Error("VectorMul failed")
}
}
|
package main
func main() {
func test() {
}
}
|
package status
import (
"github.com/gorilla/mux"
"github.com/jmoiron/sqlx"
)
// Init - initialize router
func Init(r *mux.Router, db *sqlx.DB) {
r.Methods("GET").Path("/api/status").HandlerFunc(Get(db))
r.Methods("POST").Path("/api/status").HandlerFunc(Insert(db))
r.Methods("PUT").Path("/api/status").HandlerFunc(Update(db))
r.Methods("DELETE").Path("/api/status/{id}").HandlerFunc(Delete(db))
}
|
package presenters
import "testing"
func TestBuildingANewAttachment(t *testing.T) {
attachment := NewAttachment("Bazinga", "foo", "bar", "#fff", "footer")
if attachment.Title != "Bazinga" {
t.Error("Failed to set attachments title")
}
if attachment.Text != "bar" {
t.Error("Failed to set attachments text")
}
if attachment.Footer != "footer" {
t.Error("Failed to set attachemnts footer")
}
}
|
package net
import (
"bytes"
"testing"
)
var (
testKey = []byte("bbe88b3f4106d354")
testPlaintext = []byte(`{"devId":"002004265ccf7fb1b659","dps":{"1":false,"2":0},"t":1529442366,"s":8}`)
testCiphertext = []byte("3.133ed3d4a21effe90zrA8OK3r3JMiUXpXDWauNppY4Am2c8rZ6sb4Yf15MjM8n5ByDx+QWeCZtcrPqddxLrhm906bSKbQAFtT1uCp+zP5AxlqJf5d0Pp2OxyXyjg=")
)
func TestEncrypt(t *testing.T) {
c, err := NewCipher(testKey)
if err != nil {
t.Fatal(err)
}
ciphertext := c.Encrypt(testPlaintext)
if !bytes.Equal(ciphertext, testCiphertext) {
t.Errorf("got:\n%s\nwant:\n%s", ciphertext, testCiphertext)
}
}
func TestDecrypt(t *testing.T) {
c, err := NewCipher(testKey)
if err != nil {
t.Fatal(err)
}
plaintext, err := c.Decrypt(testCiphertext)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(plaintext, testPlaintext) {
t.Errorf("got:\n%q\nwant:\n%q", plaintext, testPlaintext)
}
}
func TestDecryptBadMAC(t *testing.T) {
c, err := NewCipher(testKey)
if err != nil {
t.Fatal(err)
}
badCiphertext := append([]byte{}, testCiphertext...)
badCiphertext[10] = 'f'
_, err = c.Decrypt(badCiphertext)
if err != ErrTagVerification {
t.Errorf("got %v want %v", err, ErrTagVerification)
}
}
func TestMAC(t *testing.T) {
tag := testCiphertext[3:19]
expectedTag := macTag(nil, testKey, testCiphertext[19:])
if !bytes.Equal(tag, expectedTag) {
t.Errorf("%s != %s", tag, expectedTag)
}
}
|
package main
import (
"io/ioutil"
"time"
yaml "gopkg.in/yaml.v2"
)
type Date time.Time
type Config struct {
Birthdays map[string][]Birthday `yaml:"birthdays"`
}
type Birthday struct {
Name string `yaml:"name"`
Date Date `yaml:"date"`
}
func (b *Birthday) Time() time.Time {
return time.Time(b.Date)
}
func (d *Date) UnmarshalYAML(unmarshal func(interface{}) error) error {
var stringType string
err := unmarshal(&stringType)
if err != nil {
return err
}
t, err := time.Parse("02.01", stringType)
if err != nil {
return err
}
t = t.AddDate(time.Now().Year(), 0, 0)
if time.Until(t) < 0 {
t = t.AddDate(1, 0, 0)
}
*d = Date(t)
return nil
}
func ConfigFromFile(filename string) (*Config, error) {
b, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
c := &Config{}
return c, yaml.Unmarshal(b, c)
}
|
package main
import (
//"crypto/md5"
"database/sql"
"encoding/json"
"fmt"
_ "github.com/go-sql-driver/mysql"
"io/ioutil"
"net/http"
"os"
"strings"
"time"
)
func main() {
fmt.Println("Go access mysql!")
//db, err := sql.Open("mysql", "liminghao:liminghao@tcp(47.89.43.129:3308)/testdb?charset=utf8")
db, err := sql.Open("mysql", "bir:bir@tcp(m8001.sit.mysqldb.bingsheng.tc:8001)/bir?charset=utf8")
if err != nil {
fmt.Println(err)
return
}
defer db.Close()
type Action struct {
MD5 string
Request_id string `json:"request_id"`
Data_type int `json:"data_type"`
Bid string `json:"bid"`
Uid_type int `json:"uid_type"`
Uid string `json:"uid"`
Item_id string `json:"item_id"`
Scene_id string `json:"scene_id"`
Action_type int `json:"action_type"`
Source string `json:"source"`
Trace_id string `json:"trace_id"`
Action_time string `json:"action_time"`
}
//rows, err := db.Query("select member_id, certificate_no, use_store, update_time from coupon_ec_3p_qhx_xcx01 limit 100000")
rows, err := db.Query("select MD5, request_id, data_type, bid, uid_type, uid, item_id, scene_id, action_type, source, trace_id, action_time from Action")
for rows.Next() {
var MD5, request_id, bid, uid, item_id, scene_id, source, trace_id, action_time string
var data_type, uid_type, action_type int
err = rows.Scan(&MD5, &request_id, &data_type, &bid, &uid_type, &uid, &item_id, &scene_id, &action_type, &source, &trace_id, &action_time)
if err != nil {
fmt.Println(err)
return
}
var action Action
action.MD5 = MD5
action.Request_id = fmt.Sprintf("%d", time.Now().UnixNano()/1e6)
action.Data_type = data_type
action.Bid = bid
action.Uid_type = uid_type
action.Uid = uid
action.Item_id = item_id
action.Scene_id = scene_id
action.Action_type = action_type
action.Source = source
action.Trace_id = trace_id
action.Action_time = action_time
b, err := json.Marshal(action)
if err != nil {
fmt.Println("error:", err)
}
os.Stdout.Write(b)
fmt.Println("")
// resp, err := http.Post("http://47.89.43.129:10000/hello",
resp, err := http.Post("http://data.dm.qcloud.com:8088",
"application/x-www-form-urlencoded",
strings.NewReader(string(b)))
if err != nil {
fmt.Println(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(time.Now().Format("2006-01-02 15:04:05"), " Response body:")
fmt.Println(string(body))
}
}
|
package main
func f() {
}
f()
|
package main
import (
"bufio"
"fmt"
"io/ioutil"
"os"
)
type tape struct {
Source string
Tape [30000]byte
Cursor int
OpenLoops map[int]int
CloseLoops map[int]int
}
func (t *tape) incCursor() {
t.Cursor++
}
func (t *tape) decCursor() {
t.Cursor--
}
func (t *tape) incVal() {
t.Tape[t.Cursor]++
}
func (t *tape) decVal() {
t.Tape[t.Cursor]--
}
func (t *tape) printVal() {
fmt.Print(string(t.Tape[t.Cursor]))
}
func (t *tape) scanVal() {
reader := bufio.NewReader(os.Stdin)
char, _, _ := reader.ReadRune()
t.Tape[t.Cursor] = byte(char)
}
func (t *tape) process() {
src := []rune(t.Source)
i := 0
v := src[0]
for {
v = src[i]
switch rune(v) {
case '>':
t.incCursor()
case '<':
t.decCursor()
case '+':
t.incVal()
case '-':
t.decVal()
case '.':
t.printVal()
case ',':
t.scanVal()
case '[':
if t.Tape[t.Cursor] == byte(0) {
i = t.OpenLoops[i] + 1
continue
}
case ']':
i = t.CloseLoops[i]
continue
}
if i+1 == len(src) {
break
}
i++
}
}
func main() {
dat, _ := ioutil.ReadFile(os.Args[1])
source := string(dat)
tape := tape{}
tape.Source = source
stack := []int{}
openLoops := make(map[int]int)
closeLoops := make(map[int]int)
for i, v := range source {
if v == '[' {
stack = append([]int{i}, stack...)
} else if v == ']' {
openLoops[stack[0]] = i
closeLoops[i] = stack[0]
stack = stack[1:]
}
}
tape.OpenLoops = openLoops
tape.CloseLoops = closeLoops
tape.process()
}
|
package wtemplate_test
import (
"testing"
"github.com/okke/wired/wtemplate"
)
type evalContext struct {
variables map[string]string
}
func (evalContext *evalContext) Solve(name string) string {
return evalContext.variables[name]
}
func newEvalContext() wtemplate.Context {
variables := make(map[string]string, 0)
variables["pepper"] = "jalapeno"
return &evalContext{variables: variables}
}
func testParser(t *testing.T, template string, expected string) {
ctx := newEvalContext()
if txt := wtemplate.Parse(ctx, template); txt != expected {
t.Errorf("expected %s, got '%s'", expected, txt)
}
}
func TestParser(t *testing.T) {
testParser(t, "", "")
testParser(t, "chipotle", "chipotle")
testParser(t, "${pepper}", "jalapeno")
testParser(t, "${pepper}Pepper", "jalapenoPepper")
testParser(t, "LoveToEat${pepper}", "LoveToEatjalapeno")
testParser(t, "$pepper", "jalapeno")
testParser(t, "$pepper/$pepper", "jalapeno/jalapeno")
testParser(t, "$pepper $pepper", "jalapeno jalapeno")
testParser(t, "$pepper:$pepper", "jalapeno:jalapeno")
testParser(t, "$pepper\t$pepper", "jalapeno\tjalapeno")
testParser(t, "$pepper\n$pepper", "jalapeno\njalapeno")
testParser(t, "${pepper}\\\\$pepper", "jalapeno\\jalapeno")
testParser(t, "$", "")
testParser(t, "$$", "")
testParser(t, "\\$", "$")
testParser(t, "\\", "")
testParser(t, "\\\\", "\\")
testParser(t, "${url:http://hotpeppers.com/habanero?color=red}", "http://hotpeppers.com/habanero?color=red")
}
|
package marshalutil
// Uint8Size contains the amount of bytes of a marshaled uint8 value.
const Uint8Size = 1
// WriteUint8 writes a marshaled uint8 value to the internal buffer.
func (util *MarshalUtil) WriteUint8(value uint8) *MarshalUtil {
writeEndOffset := util.expandWriteCapacity(Uint8Size)
util.bytes[util.writeOffset] = value
util.WriteSeek(writeEndOffset)
return util
}
// ReadUint8 reads an uint8 value from the internal buffer.
func (util *MarshalUtil) ReadUint8() (uint8, error) {
readEndOffset, err := util.checkReadCapacity(Uint8Size)
if err != nil {
return 0, err
}
defer util.ReadSeek(readEndOffset)
return util.bytes[util.readOffset], nil
}
|
package play
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/joshprzybyszewski/cribbage/model"
)
func TestPlayersToDealTo(t *testing.T) {
alice := model.Player{
ID: model.PlayerID(`1`),
Name: `alice`,
}
bob := model.Player{
ID: model.PlayerID(`2`),
Name: `bob`,
}
charlie := model.Player{
ID: model.PlayerID(`3`),
Name: `charlie`,
}
testCases := []struct {
msg string
g model.Game
expPlayerIDs []model.PlayerID
}{{
msg: `two person game`,
g: model.Game{
Players: []model.Player{alice, bob},
CurrentDealer: alice.ID,
},
expPlayerIDs: []model.PlayerID{bob.ID, alice.ID},
}, {
msg: `two person game, other dealer`,
g: model.Game{
Players: []model.Player{alice, bob},
CurrentDealer: bob.ID,
},
expPlayerIDs: []model.PlayerID{alice.ID, bob.ID},
}, {
msg: `three person game`,
g: model.Game{
Players: []model.Player{alice, bob, charlie},
CurrentDealer: alice.ID,
},
expPlayerIDs: []model.PlayerID{bob.ID, charlie.ID, alice.ID},
}, {
msg: `three person game, second dealer`,
g: model.Game{
Players: []model.Player{alice, bob, charlie},
CurrentDealer: bob.ID,
},
expPlayerIDs: []model.PlayerID{charlie.ID, alice.ID, bob.ID},
}, {
msg: `three person game, third dealer`,
g: model.Game{
Players: []model.Player{alice, bob, charlie},
CurrentDealer: charlie.ID,
},
expPlayerIDs: []model.PlayerID{alice.ID, bob.ID, charlie.ID},
}}
for _, tc := range testCases {
actPlayerIDs := playersToDealTo(&tc.g)
assert.Equal(t, tc.expPlayerIDs, actPlayerIDs, tc.msg)
}
}
|
package cmd
import (
"fmt"
"io"
"os"
"os/exec"
"github.com/baetyl/baetyl-go/v2/errors"
"github.com/baetyl/baetyl-go/v2/log"
"github.com/baetyl/baetyl-go/v2/utils"
"github.com/kardianos/service"
"github.com/spf13/cobra"
"gopkg.in/natefinch/lumberjack.v2"
)
func init() {
rootCmd.AddCommand(programCmd)
}
var programCmd = &cobra.Command{
Use: "program",
Short: "Run a program of Baetyl",
Long: `Baetyl loads program's configuration from program.yml, then runs and waits the program to stop.`,
Run: func(_ *cobra.Command, _ []string) {
if err := startProgramService(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
},
}
func startProgramService() error {
prg := &program{
exit: make(chan struct{}),
log: os.Stdout,
}
err := utils.LoadYAML("program.yml", &prg.cfg)
if err != nil {
return errors.Trace(err)
}
if prg.cfg.Logger.Filename != "" {
prg.log = &lumberjack.Logger{
Compress: prg.cfg.Logger.Compress,
Filename: prg.cfg.Logger.Filename,
MaxAge: prg.cfg.Logger.MaxAge,
MaxSize: prg.cfg.Logger.MaxSize,
MaxBackups: prg.cfg.Logger.MaxBackups,
}
}
svcCfg := &service.Config{
Name: prg.cfg.Name,
DisplayName: prg.cfg.DisplayName,
Description: prg.cfg.Description,
}
prg.svc, err = service.New(prg, svcCfg)
if err != nil {
return errors.Trace(err)
}
return errors.Trace(prg.svc.Run())
}
// Config is the runner app config structure.
type Config struct {
Name string `yaml:"name" json:"name" validate:"nonzero"`
DisplayName string `yaml:"displayName" json:"displayName"`
Description string `yaml:"description" json:"description"`
Dir string `yaml:"dir" json:"dir"`
Exec string `yaml:"exec" json:"exec"`
Args []string `yaml:"args" json:"args"`
Env []string `yaml:"env" json:"env"`
Logger log.Config `yaml:"logger" json:"logger"`
}
type program struct {
cfg Config
cmd *exec.Cmd
svc service.Service
exit chan struct{}
log io.Writer
}
func (p *program) Start(s service.Service) error {
// Look for exec.
// Verify home directory.
fullExec, err := exec.LookPath(p.cfg.Exec)
if err != nil {
return errors.Trace(err)
}
p.cmd = exec.Command(fullExec, p.cfg.Args...)
p.cmd.Dir = p.cfg.Dir
p.cmd.Env = append(os.Environ(), p.cfg.Env...)
p.cmd.Stderr = p.log
p.cmd.Stdout = p.log
go p.run()
return nil
}
func (p *program) run() {
fmt.Fprintln(p.log, "Program starting", p.cfg.DisplayName)
defer p.Stop(p.svc)
err := p.cmd.Run()
if err != nil {
fmt.Fprintln(p.log, "Program error:", err)
}
return
}
func (p *program) Stop(s service.Service) error {
close(p.exit)
fmt.Fprintln(p.log, "Program stopping", p.cfg.DisplayName)
if p.cmd.Process != nil {
p.cmd.Process.Kill()
}
os.Exit(0)
return nil
}
|
package mvc
import (
"io/ioutil"
"log"
"net/http"
"sync"
)
var luftDaten LuftDatenReading
const (
Last string = "last"
FiveMins string = "5mins"
OneHour string = "1hour"
TwentyFourHours string = "24hours"
)
type LuftDatenReading struct {
lastReading *Welcome
mutLastReading sync.Mutex
avgLast5MinsReading *Welcome
mutAvgLast5Mins sync.Mutex
avgLast1HourReading *Welcome
mutAvgLast1hour sync.Mutex
avgLast24HoursReading *Welcome
mutAvgLast24Hours sync.Mutex
}
func (c *LuftDatenReading) queryAllSensorsData(uri string) *Welcome {
response, err := http.Get(uri)
if err != nil {
log.Printf("Error fetching sensor data %s\n", err)
}
var sensorData Welcome
bodyBytes, err := ioutil.ReadAll(response.Body)
sensorData, err = UnmarshalWelcome(bodyBytes)
if err != nil {
log.Printf("Error converting response to json %s\n", err)
}
trimedData := postProcessSensorsData(&sensorData)
return trimedData
}
func (c *LuftDatenReading) updateReading(tp string) {
switch tp {
case Last:
c.mutLastReading.Lock()
c.lastReading = c.queryAllSensorsData("https://api.luftdaten.info/static/v1/data.json")
c.mutLastReading.Unlock()
break
case FiveMins:
c.mutAvgLast5Mins.Lock()
c.avgLast5MinsReading = c.queryAllSensorsData("http://api.luftdaten.info/static/v2/data.json")
c.mutAvgLast5Mins.Unlock()
break
case OneHour:
c.mutAvgLast1hour.Lock()
c.avgLast1HourReading = c.queryAllSensorsData("http://api.luftdaten.info/static/v2/data.1h.json")
c.mutAvgLast1hour.Unlock()
break
case TwentyFourHours:
c.mutAvgLast24Hours.Lock()
c.avgLast24HoursReading = c.queryAllSensorsData("http://api.luftdaten.info/static/v2/data.24h.json")
c.mutAvgLast24Hours.Unlock()
break
}
log.Printf("Updated luftdaten data type: %s", tp)
}
func (c *LuftDatenReading) getLastReading(tp string) *Welcome {
var data *Welcome
switch tp {
case Last:
c.mutLastReading.Lock()
data = c.lastReading
c.mutLastReading.Unlock()
break
case FiveMins:
c.mutAvgLast5Mins.Lock()
data = c.avgLast5MinsReading
c.mutAvgLast5Mins.Unlock()
break
case OneHour:
c.mutAvgLast1hour.Lock()
data = c.avgLast1HourReading
c.mutAvgLast1hour.Unlock()
break
case TwentyFourHours:
c.mutAvgLast24Hours.Lock()
data = c.avgLast24HoursReading
c.mutAvgLast24Hours.Unlock()
break
default:
log.Print("Wrong type of sensor reading requested")
}
return data
}
func postProcessSensorsData(data *Welcome) *Welcome {
var trimedData Welcome
for _, element := range *data {
if sensorHasPmReading(&element) {
trimedData = append(trimedData, element)
}
}
return &trimedData
}
func sensorHasPmReading(elem *WelcomeElement) bool {
sensorName := elem.Sensor.SensorType.Name
if sensorName == Sds011 || sensorName == Sds021 || sensorName == Hpm ||
sensorName == Pms1003 || sensorName == Pms3003 || sensorName == Pms5003 ||
sensorName == Pms7003 || sensorName == Ppd42NS {
return true
}
return false
}
//func getHTMLpage() {
// file, _ := http.Get("http://archive.luftdaten.info/2019-10-18/")
// fmt.Print(file.Body)
//}
|
package main
import (
"log"
"os/exec"
"strings"
"time"
"gobot.io/x/gobot"
"gobot.io/x/gobot/drivers/gpio"
"gobot.io/x/gobot/platforms/beaglebone"
"gobot.io/x/gobot/platforms/dragonboard"
"gobot.io/x/gobot/platforms/raspi"
)
func main() {
out, err := exec.Command("uname", "-r").Output()
if err != nil {
log.Fatal(err)
}
var adaptor gobot.Adaptor
var pin string
kernelRelease := string(out)
if strings.Contains(kernelRelease, "raspi2") {
adaptor = raspi.NewAdaptor()
pin = "7"
} else if strings.Contains(kernelRelease, "snapdragon") {
adaptor = dragonboard.NewAdaptor()
pin = "GPIO_A"
} else {
adaptor = beaglebone.NewAdaptor()
pin = "P8_7"
}
digitalWriter, ok := adaptor.(gpio.DigitalWriter)
if !ok {
log.Fatal("Invalid adaptor")
}
led := gpio.NewLedDriver(digitalWriter, pin)
work := func() {
gobot.Every(1*time.Second, func() {
led.Toggle()
})
}
robot := gobot.NewRobot("snapbot",
[]gobot.Connection{adaptor},
[]gobot.Device{led},
work,
)
robot.Start()
}
|
package routers
import (
"festival/app/common/middleware/auth"
"festival/app/common/router"
"festival/app/controller/system"
)
func init() {
g2 := router.New("admin", "/admin/system", auth.Auth)
g2.GET("/users", true, system.UserList)
g2.GET("/user/edit", true, system.UserEdit)
g2.POST("/user/save", true, system.UserSave)
g2.POST("/user/del", true, system.UserDelete)
g2.GET("/menus", true, system.MenuList)
g2.GET("/menu/edit", true, system.MenuEdit)
g2.POST("/menu/save", true, system.MenuSave)
g2.POST("/menu/del", true, system.MenuDel)
g2.GET("/roles", true, system.RoleList)
g2.GET("/role/edit", true, system.RoleEdit)
g2.POST("/role/save", true, system.RoleSave)
g2.POST("/role/del", true, system.RoleDelete)
}
|
package protectionpolicies
import "github.com/cohesity/management-sdk-go/models"
import "github.com/cohesity/management-sdk-go/configuration"
/*
* Interface for the PROTECTIONPOLICIES_IMPL
*/
type PROTECTIONPOLICIES interface {
GetProtectionPolicyById (string) (*models.ProtectionPolicy, error)
UpdateProtectionPolicy (*models.ProtectionPolicyRequest, string) (*models.ProtectionPolicy, error)
DeleteProtectionPolicy (string) (error)
GetProtectionPolicies ([]models.Environments1Enum, []int64, []string, *bool, []string, []string) ([]*models.ProtectionPolicy, error)
CreateProtectionPolicy (*models.ProtectionPolicyRequest) (*models.ProtectionPolicy, error)
}
/*
* Factory for the PROTECTIONPOLICIES interaface returning PROTECTIONPOLICIES_IMPL
*/
func NewPROTECTIONPOLICIES(config configuration.CONFIGURATION) *PROTECTIONPOLICIES_IMPL {
client := new(PROTECTIONPOLICIES_IMPL)
client.config = config
return client
}
|
/*
Valid Parentheses
Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid.
The brackets must close in the correct order,
"()" and "()[]{}" are all valid but "(]" and "([)]" are not.
*/
package main
func isValid(s string) bool {
stack, top := make([]rune, len(s)/2), -1
for _, v := range s {
switch v {
case '(', '{', '[':
top++
if top == len(stack) {
return false
}
stack[top] = v
case ')':
if top == -1 || stack[top] != '(' {
return false
}
top--
case '}', ']':
if top == -1 || stack[top] != v-2 {
return false
}
top--
}
}
return top == -1
}
|
package main
import "testing"
type point struct {
x, y int
}
type tuple struct {
a, b, c, d point
}
func TestOverlapping(t *testing.T) {
for k, v := range map[tuple]bool{
tuple{point{-3, 3}, point{-1, 1}, point{1, -1}, point{3, -3}}: false,
tuple{point{-3, 3}, point{-1, 1}, point{-2, 4}, point{2, 2}}: true} {
if r := overlapping(k.a, k.b, k.c, k.d); r != v {
t.Errorf("failed: overlapping %d %d %d %d %d %d %d %d is %t, got %t",
k.a.x, k.a.y, k.b.x, k.b.y, k.c.x, k.c.y, k.d.x, k.d.y, v, r)
}
}
}
func within(a, b, c point) bool {
return c.x >= a.x && c.x <= b.x && c.y >= b.y && c.y <= a.y
}
func overlapping(a, b, c, d point) bool {
for _, i := range []point{a, point{a.x, b.y}, point{b.x, a.y}, b} {
if within(c, d, i) {
return true
}
}
for _, i := range []point{c, point{c.x, d.y}, point{d.x, c.y}, d} {
if within(a, b, i) {
return true
}
}
return false
}
|
package image
import (
gocontext "context"
"fmt"
"net/url"
"runtime"
lxd "github.com/lxc/lxd/client"
lxdapi "github.com/lxc/lxd/shared/api"
"github.com/sirupsen/logrus"
"github.com/travis-ci/worker/context"
"golang.org/x/sync/errgroup"
)
var (
arch = runtime.GOARCH
infra = fmt.Sprintf("lxd-%s", arch)
tags = []string{"os:linux"}
groups = []string{"group:stable", "group:edge", "group:dev"}
)
func NewManager(ctx gocontext.Context, selector *APISelector, imagesServerURL *url.URL) (*Manager, error) {
logger := context.LoggerFromContext(ctx).WithField("self", "image_manager")
client, err := lxd.ConnectLXDUnix("", nil)
if err != nil {
return nil, err
}
return &Manager{
client: client,
selector: selector,
logger: logger,
imagesServerURL: imagesServerURL,
}, nil
}
type Manager struct {
client lxd.ContainerServer
selector *APISelector
logger *logrus.Entry
imagesServerURL *url.URL
}
func (m *Manager) Load(imageName string) error {
ok, err := m.Exists(imageName)
if err != nil {
return err
}
if ok {
m.logger.WithFields(logrus.Fields{
"image_name": imageName,
}).Info("image already present")
return nil
}
imageURL := m.imageUrl(imageName)
m.logger.WithFields(logrus.Fields{
"image_name": imageName,
"image_url": imageURL,
}).Info("importing image")
return m.importImage(imageName, imageURL)
}
func (m *Manager) Exists(imageName string) (bool, error) {
images, err := m.client.GetImages()
if err != nil {
return false, err
}
for _, img := range images {
for _, alias := range img.Aliases {
if alias.Name == imageName {
return true, nil
}
}
}
return false, nil
}
func (m *Manager) Update(ctx gocontext.Context) error {
m.logger.WithFields(logrus.Fields{
"arch": arch,
"infra": infra,
}).Info("updating lxc images")
images := []*apiSelectorImageRef{}
for _, group := range groups {
imagesGroup, err := m.selector.SelectAll(ctx, infra, append(tags, group))
if err != nil {
return err
}
images = append(images, imagesGroup...)
}
g, _ := errgroup.WithContext(ctx)
for _, img := range images {
img := img
g.Go(func() error {
m.logger.WithFields(logrus.Fields{
"image_name": img.Name,
"infra": infra,
"group": img.Group(),
}).Info("updating image")
return m.Load(img.Name)
})
}
return g.Wait()
}
func (m *Manager) Cleanup() error {
// TODO
return nil
}
func (m *Manager) importImage(imageName, imgURL string) error {
op, err := m.client.CreateImage(
lxdapi.ImagesPost{
Filename: imageName,
Source: &lxdapi.ImagesPostSource{
Type: "url",
URL: imgURL,
},
Aliases: []lxdapi.ImageAlias{
lxdapi.ImageAlias{Name: imageName},
},
}, nil,
)
if err != nil {
return err
}
err = op.Wait()
if err != nil {
return err
}
alias, _, err := m.client.GetImageAlias(imageName)
if err != nil {
return err
}
image, _, err := m.client.GetImage(alias.Target)
if err != nil {
return err
}
containerName := fmt.Sprintf("%s-warmup", imageName)
rop, err := m.client.CreateContainerFromImage(
m.client,
*image,
lxdapi.ContainersPost{
Name: containerName,
},
)
if err != nil {
return err
}
err = rop.Wait()
if err != nil {
return err
}
defer func() {
op, err := m.client.DeleteContainer(containerName)
if err != nil {
m.logger.WithFields(logrus.Fields{
"error": err,
"container_name": containerName,
}).Error("failed to delete container")
return
}
err = op.Wait()
if err != nil {
m.logger.WithFields(logrus.Fields{
"error": err,
"container_name": containerName,
}).Error("failed to delete container")
return
}
}()
return err
}
func (m *Manager) imageUrl(name string) string {
u := *m.imagesServerURL
u.Path = fmt.Sprintf("/images/travis/%s", name)
return u.String()
}
|
package jmodels
// BasicUser базовые поля
type BasicUser struct {
Username string `json:"username"`
PhotoUUID string `json:"photo_uuid"`
}
// InfoUser BasicUser, расширенный служебной инфой
type InfoUser struct {
BasicUser
ID int64 `json:"id"`
Active bool `json:"active"`
}
// ScoredUser инфа о юзере расширенная его баллами
type ScoredUser struct {
InfoUser
Score int32 `json:"score"`
}
// Game схема объекта игры для карусельки
type Game struct {
Slug string `json:"slug"`
Title string `json:"title"`
BackgroundUUID string `json:"background_uuid"`
}
// GameFull полная инфа об игре
type GameFull struct {
Game
Description string `json:"description"`
Rules string `json:"rules"`
CodeExample string `json:"code_example"`
BotCode string `json:"bot_code"`
LogoUUID string `json:"logo_uuid"`
}
|
// +build go1.9
package sqlmock
import (
"context"
"testing"
)
func TestCustomValueConverterExec(t *testing.T) {
db, mock, _ := New(ValueConverterOption(CustomConverter{}))
expectedQuery := "INSERT INTO tags \\(name,email,age,hobbies\\) VALUES \\(\\?,\\?,\\?,\\?\\)"
query := "INSERT INTO tags (name,email,age,hobbies) VALUES (?,?,?,?)"
name := "John"
email := "j@jj.j"
age := 12
hobbies := []string{"soccer", "netflix"}
mock.ExpectBegin()
mock.ExpectPrepare(expectedQuery)
mock.ExpectExec(expectedQuery).WithArgs(name, email, age, hobbies).WillReturnResult(NewResult(1, 1))
mock.ExpectCommit()
ctx := context.Background()
tx, e := db.BeginTx(ctx, nil)
if e != nil {
t.Error(e)
return
}
stmt, e := db.PrepareContext(ctx, query)
if e != nil {
t.Error(e)
return
}
_, e = stmt.Exec(name, email, age, hobbies)
if e != nil {
t.Error(e)
return
}
tx.Commit()
if err := mock.ExpectationsWereMet(); err != nil {
t.Error(err)
}
}
|
package main
//2006. 差的绝对值为 K 的数对数目
//给你一个整数数组nums和一个整数k,请你返回数对(i, j)的数目,满足i < j且|nums[i] - nums[j]| == k。
//
//|x|的值定义为:
//
//如果x >= 0,那么值为x。
//如果x < 0,那么值为-x。
//
//
//示例 1:
//
//输入:nums = [1,2,2,1], k = 1
//输出:4
//解释:差的绝对值为 1 的数对为:
//- [1,2,2,1]
//- [1,2,2,1]
//- [1,2,2,1]
//- [1,2,2,1]
//示例 2:
//
//输入:nums = [1,3], k = 3
//输出:0
//解释:没有任何数对差的绝对值为 3 。
//示例 3:
//
//输入:nums = [3,2,1,5,4], k = 2
//输出:3
//解释:差的绝对值为 2 的数对为:
//- [3,2,1,5,4]
//- [3,2,1,5,4]
//- [3,2,1,5,4]
//
//
//提示:
//
//1 <= nums.length <= 200
//1 <= nums[i] <= 100
//1 <= k <= 99
func countKDifference(nums []int, k int) int {
cnt := make(map[int]int)
var result int
for _, v := range nums {
result += cnt[v-k] + cnt[v+k]
cnt[v]++
}
return result
}
func main() {
println(countKDifference([]int{1, 2, 2, 1}, 1))
}
|
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT License was not distributed with this
// file, you can obtain one at https://opensource.org/licenses/MIT.
//
// Copyright (c) DUSK NETWORK. All rights reserved.
package blindbid
import (
"bytes"
"github.com/dusk-network/dusk-blockchain/pkg/p2p/wire/encoding"
"github.com/dusk-network/dusk-protobuf/autogen/go/rusk"
)
// GenerateScoreRequest is used by block generators to generate a score
// and a proof of blind bid, in order to propose a block.
type GenerateScoreRequest struct {
K []byte `json:"k"`
Seed []byte `json:"seed"`
Secret []byte `json:"secret"`
Round uint32 `json:"round"`
Step uint32 `json:"step"`
IndexStoredBid uint64 `json:"index_stored_bid"`
}
// NewGenerateScoreRequest returns a new empty GenerateScoreRequest struct.
func NewGenerateScoreRequest() *GenerateScoreRequest {
return &GenerateScoreRequest{
K: make([]byte, 32),
Seed: make([]byte, 32),
Secret: make([]byte, 32),
}
}
// Copy complies with message.Safe interface. It returns a deep copy of
// the message safe to publish to multiple subscribers.
func (g *GenerateScoreRequest) Copy() *GenerateScoreRequest {
k := make([]byte, len(g.K))
seed := make([]byte, len(g.Seed))
secret := make([]byte, len(g.Secret))
copy(k, g.K)
copy(seed, g.Seed)
copy(secret, g.Secret)
return &GenerateScoreRequest{
K: k,
Seed: seed,
Secret: secret,
Round: g.Round,
Step: g.Step,
IndexStoredBid: g.IndexStoredBid,
}
}
// MGenerateScoreRequest copies the GenerateScoreRequest structure into the Rusk equivalent.
func MGenerateScoreRequest(r *rusk.GenerateScoreRequest, f *GenerateScoreRequest) {
copy(r.K, f.K)
copy(r.Seed, f.Seed)
copy(r.Secret, f.Secret)
r.Round = f.Round
r.Step = f.Step
r.IndexStoredBid = f.IndexStoredBid
}
// UGenerateScoreRequest copies the Rusk GenerateScoreRequest structure into the native equivalent.
func UGenerateScoreRequest(r *rusk.GenerateScoreRequest, f *GenerateScoreRequest) {
copy(f.K, r.K)
copy(f.Seed, r.Seed)
copy(f.Secret, r.Secret)
f.Round = r.Round
f.Step = r.Step
f.IndexStoredBid = r.IndexStoredBid
}
// MarshalGenerateScoreRequest writes the GenerateScoreRequest struct into a bytes.Buffer.
func MarshalGenerateScoreRequest(r *bytes.Buffer, f *GenerateScoreRequest) error {
if err := encoding.Write256(r, f.K); err != nil {
return err
}
if err := encoding.Write256(r, f.Seed); err != nil {
return err
}
if err := encoding.Write256(r, f.Secret); err != nil {
return err
}
if err := encoding.WriteUint32LE(r, f.Round); err != nil {
return err
}
if err := encoding.WriteUint32LE(r, f.Step); err != nil {
return err
}
return encoding.WriteUint64LE(r, f.IndexStoredBid)
}
// UnmarshalGenerateScoreRequest reads a GenerateScoreRequest struct from a bytes.Buffer.
func UnmarshalGenerateScoreRequest(r *bytes.Buffer, f *GenerateScoreRequest) error {
if err := encoding.Read256(r, f.K); err != nil {
return err
}
if err := encoding.Read256(r, f.Seed); err != nil {
return err
}
if err := encoding.Read256(r, f.Secret); err != nil {
return err
}
if err := encoding.ReadUint32LE(r, &f.Round); err != nil {
return err
}
if err := encoding.ReadUint32LE(r, &f.Step); err != nil {
return err
}
return encoding.ReadUint64LE(r, &f.IndexStoredBid)
}
// GenerateScoreResponse contains the resulting proof of blind bid, score,
// and the prover identity, to be used for proposing a block.
type GenerateScoreResponse struct {
BlindbidProof []byte `json:"blindbid_proof"`
Score []byte `json:"score"`
ProverIdentity []byte `json:"prover_identity"`
}
// NewGenerateScoreResponse returns a new empty GenerateScoreResponse struct.
func NewGenerateScoreResponse() *GenerateScoreResponse {
return &GenerateScoreResponse{
BlindbidProof: make([]byte, 0),
Score: make([]byte, 32),
ProverIdentity: make([]byte, 32),
}
}
// Copy complies with message.Safe interface. It returns a deep copy of
// the message safe to publish to multiple subscribers.
func (g *GenerateScoreResponse) Copy() *GenerateScoreResponse {
proof := make([]byte, len(g.BlindbidProof))
score := make([]byte, len(g.Score))
identity := make([]byte, len(g.ProverIdentity))
copy(proof, g.BlindbidProof)
copy(score, g.Score)
copy(identity, g.ProverIdentity)
return &GenerateScoreResponse{
BlindbidProof: proof,
Score: score,
ProverIdentity: identity,
}
}
// MGenerateScoreResponse copies the GenerateScoreResponse structure into the Rusk equivalent.
func MGenerateScoreResponse(r *rusk.GenerateScoreResponse, f *GenerateScoreResponse) {
copy(r.BlindbidProof, f.BlindbidProof)
copy(r.Score, f.Score)
copy(r.ProverIdentity, f.ProverIdentity)
}
// UGenerateScoreResponse copies the Rusk GenerateScoreResponse structure into the native equivalent.
func UGenerateScoreResponse(r *rusk.GenerateScoreResponse, f *GenerateScoreResponse) {
copy(f.BlindbidProof, r.BlindbidProof)
copy(f.Score, r.Score)
copy(f.ProverIdentity, r.ProverIdentity)
}
// MarshalGenerateScoreResponse writes the GenerateScoreResponse struct into a bytes.Buffer.
func MarshalGenerateScoreResponse(r *bytes.Buffer, f *GenerateScoreResponse) error {
if err := encoding.WriteVarBytes(r, f.BlindbidProof); err != nil {
return err
}
if err := encoding.Write256(r, f.Score); err != nil {
return err
}
return encoding.Write256(r, f.ProverIdentity)
}
// UnmarshalGenerateScoreResponse reads a GenerateScoreResponse struct from a bytes.Buffer.
func UnmarshalGenerateScoreResponse(r *bytes.Buffer, f *GenerateScoreResponse) error {
if err := encoding.ReadVarBytes(r, &f.BlindbidProof); err != nil {
return err
}
if err := encoding.Read256(r, f.Score); err != nil {
return err
}
return encoding.Read256(r, f.ProverIdentity)
}
// VerifyScoreRequest is used by provisioners to ensure that a given
// blind bid proof is valid.
type VerifyScoreRequest struct {
Proof []byte `json:"proof"`
Score []byte `json:"score"`
Seed []byte `json:"seed"`
ProverID []byte `json:"prover_id"`
Round uint64 `json:"round"`
Step uint32 `json:"step"`
}
// Copy complies with message.Safe interface. It returns a deep copy of
// the message safe to publish to multiple subscribers.
func (v *VerifyScoreRequest) Copy() *VerifyScoreRequest {
proof := make([]byte, len(v.Proof))
score := make([]byte, len(v.Score))
seed := make([]byte, len(v.Seed))
proverID := make([]byte, len(v.ProverID))
copy(proof, v.Proof)
copy(score, v.Score)
copy(seed, v.Seed)
copy(proverID, v.ProverID)
return &VerifyScoreRequest{
Proof: proof,
Score: score,
Seed: seed,
ProverID: proverID,
Round: v.Round,
Step: v.Step,
}
}
// MVerifyScoreRequest copies the VerifyScoreRequest structure into the Rusk equivalent.
func MVerifyScoreRequest(r *rusk.VerifyScoreRequest, f *VerifyScoreRequest) {
copy(r.Proof, f.Proof)
copy(r.Score, f.Score)
copy(r.Seed, f.Seed)
copy(r.ProverId, f.ProverID)
r.Round = f.Round
r.Step = f.Step
}
// UVerifyScoreRequest copies the Rusk VerifyScoreRequest structure into the native equivalent.
func UVerifyScoreRequest(r *rusk.VerifyScoreRequest, f *VerifyScoreRequest) {
copy(f.Proof, r.Proof)
copy(f.Score, r.Score)
copy(f.Seed, r.Seed)
copy(f.ProverID, r.ProverId)
f.Round = r.Round
f.Step = r.Step
}
// MarshalVerifyScoreRequest writes the VerifyScoreRequest struct into a bytes.Buffer.
func MarshalVerifyScoreRequest(r *bytes.Buffer, f *VerifyScoreRequest) error {
if err := encoding.WriteVarBytes(r, f.Proof); err != nil {
return err
}
if err := encoding.Write256(r, f.Score); err != nil {
return err
}
if err := encoding.Write256(r, f.Seed); err != nil {
return err
}
if err := encoding.Write256(r, f.ProverID); err != nil {
return err
}
if err := encoding.WriteUint64LE(r, f.Round); err != nil {
return err
}
return encoding.WriteUint32LE(r, f.Step)
}
// UnmarshalVerifyScoreRequest reads a VerifyScoreRequest struct from a bytes.Buffer.
func UnmarshalVerifyScoreRequest(r *bytes.Buffer, f *VerifyScoreRequest) error {
if err := encoding.ReadVarBytes(r, &f.Proof); err != nil {
return err
}
if err := encoding.Read256(r, f.Score); err != nil {
return err
}
if err := encoding.Read256(r, f.Seed); err != nil {
return err
}
if err := encoding.Read256(r, f.ProverID); err != nil {
return err
}
if err := encoding.ReadUint64LE(r, &f.Round); err != nil {
return err
}
return encoding.ReadUint32LE(r, &f.Step)
}
// VerifyScoreResponse tells a provisioner whether a supplied proof is
// valid or not.
type VerifyScoreResponse struct {
Success bool `json:"success"`
}
// Copy complies with message.Safe interface. It returns a deep copy of
// the message safe to publish to multiple subscribers.
func (v *VerifyScoreResponse) Copy() *VerifyScoreResponse {
return &VerifyScoreResponse{
Success: v.Success,
}
}
// MVerifyScoreResponse copies the VerifyScoreResponse structure into the Rusk equivalent.
func MVerifyScoreResponse(r *rusk.VerifyScoreResponse, f *VerifyScoreResponse) {
r.Success = f.Success
}
// UVerifyScoreResponse copies the Rusk VerifyScoreResponse structure into the native equivalent.
func UVerifyScoreResponse(r *rusk.VerifyScoreResponse, f *VerifyScoreResponse) {
f.Success = r.Success
}
// MarshalVerifyScoreResponse writes the VerifyScoreResponse struct into a bytes.Buffer.
func MarshalVerifyScoreResponse(r *bytes.Buffer, f *VerifyScoreResponse) error {
return encoding.WriteBool(r, f.Success)
}
// UnmarshalVerifyScoreResponse reads a VerifyScoreResponse struct from a bytes.Buffer.
func UnmarshalVerifyScoreResponse(r *bytes.Buffer, f *VerifyScoreResponse) error {
return encoding.ReadBool(r, &f.Success)
}
|
// Package version contains version information
package version
const (
// Version is the software version
Version = "3.11.0-alpha"
)
|
package api
import (
"context"
"fmt"
"github.com/love477/cooking_book/proto/menu"
)
type MenuServer struct {
menu.UnimplementedMenuServer
}
func (menuServer * MenuServer) CreateMenu(ctx context.Context, request *menu.CreateMenuRequest) (*menu.CreateMenuResponse, error) {
fmt.Println("get request from client for create menu")
return &menu.CreateMenuResponse{}, nil
}
|
package gdash
//FindLastIndex return last slice element index when predicate is true
func FindLastIndex(slice []interface{}, predicate func(interface{}) bool) int {
for i := len(slice) - 1; i >= 0; i-- {
if predicate(slice[i]) {
return i
}
}
return -1
}
|
package signer
import (
"io/ioutil"
"os"
"path"
)
const (
DIRNAME = ".store"
)
type Store interface {
Save(key string, data []byte) error
Delete(key string) error
ReadAll() ([][]byte, error)
}
// Saves key data in files under a given directory
type FileStore struct {
}
func MakeFileStore() (*FileStore, error) {
err := os.MkdirAll(DIRNAME, 0700)
if err != nil { return nil, err }
return &FileStore{}, nil
}
func (self *FileStore) ReadAll() ([][]byte, error) {
files, err := ioutil.ReadDir(DIRNAME)
if err != nil { return nil, err }
data := make([][]byte, 0, len(files))
for _, f := range files {
if f.IsDir() { continue }
content, err := ioutil.ReadFile(path.Join(DIRNAME, f.Name()))
if err != nil { return nil, err }
data = append(data, content)
}
return data, nil
}
func (self *FileStore) Save(key string, data []byte) error {
return ioutil.WriteFile(path.Join(DIRNAME, key), data, 0600)
}
func (self *FileStore) Delete(key string) error {
return os.Remove(path.Join(DIRNAME, key))
}
// Test-only in-memory key store
type TestStore struct {
store map[string][]byte
}
func MakeTestStore() *TestStore {
return &TestStore{make(map[string][]byte)}
}
func (self *TestStore) ReadAll() ([][]byte, error) {
values := make([][]byte, 0, len(self.store))
for _, value := range self.store {
values = append(values, value)
}
return values, nil
}
func (self *TestStore) Save(key string, data []byte) error {
self.store[key] = data
return nil
}
func (self *TestStore) Delete(key string) error {
delete(self.store, key)
return nil
}
|
package engine
import (
"regexp"
"strings"
)
var re1 = regexp.MustCompile("{[0-9]}*.{[0-9]}*")
var re2 = regexp.MustCompile("({[!-/:-@[-`{-~]}+|{[0-9]}+)+")
type HMM struct {
tagCounts map[string]int64
wordCounts map[string]map[string]int64
tagBigramCounts map[string]map[string]int64
tagForWordCounts map[string]map[string]int64
goodTuringTagBigramCounts map[string]map[string]float64
goodTuringTagUnigramCounts map[string]float64
numberOfBigramsWithCount map[int64]int64
goodTuringCountsAvailable bool
numTrainingBigrams int64
mostFreqTag string
writer string
ADDONE bool
GOODTURING bool
}
func NewHMM(p HMMParser) *HMM {
instance := new(HMM)
instance.tagCounts = p.TagCounts
instance.wordCounts = p.WordCounts
instance.tagBigramCounts = p.TagBigramCounts
instance.tagForWordCounts = p.TagForWordCounts
instance.mostFreqTag = p.MostFreqTag
instance.goodTuringTagBigramCounts = make(map[string]map[string]float64)
instance.goodTuringTagUnigramCounts = make(map[string]float64)
instance.numberOfBigramsWithCount = make(map[int64]int64)
instance.numTrainingBigrams = p.NumTrainingBigrams
instance.ADDONE = true
instance.GOODTURING = false
return instance
}
func (this *HMM) f1Counts(m map[string]int64, key string) int64 {
return m[key]
}
func (this *HMM) f2Counts(m map[string]map[string]int64, key1 string, key2 string) int64 {
if _, exists := m[key1]; exists {
return this.f1Counts(m[key1], key2)
} else {
return 0
}
}
func (this *HMM) fd1Counts(m map[string]float64, key string) float64 {
return m[key]
}
func (this *HMM) fd2Counts(m map[string]map[string]float64, key1 string, key2 string) float64 {
if _, exists := m[key1]; exists {
return m[key1][key2]
} else {
return 0.0
}
}
func (this *HMM) fNumberOfBigramsWithCount(count int64) int64 {
return this.numberOfBigramsWithCount[count]
}
func (this *HMM) fMakeGoodTuringCounts() {
for _, im := range this.tagBigramCounts {
for _, count := range im {
this.numberOfBigramsWithCount[count]++
}
}
for tag1, im := range this.tagBigramCounts {
igtm := make(map[string]float64)
this.goodTuringTagBigramCounts[tag1] = igtm
unigramCount := 0.0
for tag2, count := range im {
newCount := (float64(count) + 1.0) * (float64(this.fNumberOfBigramsWithCount(count + 1))) / float64(this.fNumberOfBigramsWithCount(count))
igtm[tag2] = newCount
unigramCount += newCount
}
this.goodTuringTagUnigramCounts[tag1] = unigramCount
}
this.goodTuringCountsAvailable = true
}
func (this *HMM) fCalcLikelihood(tag string, word string) float64 {
if this.ADDONE {
vocabSize := len(this.tagForWordCounts)
return float64(this.f2Counts(this.wordCounts, tag, word)+1) / float64(this.f1Counts(this.tagCounts, tag)+int64(vocabSize))
} else if this.GOODTURING {
return float64(this.f2Counts(this.wordCounts, tag, word)) / float64(this.fd1Counts(this.goodTuringTagUnigramCounts, tag))
} else {
return float64(this.f2Counts(this.wordCounts, tag, word)) / float64(this.f1Counts(this.tagCounts, tag))
}
}
func (this *HMM) fCalcPriorProb(tag1 string, tag2 string) float64 {
if this.ADDONE {
vocabSize := len(this.tagCounts)
return float64(this.f2Counts(this.tagBigramCounts, tag1, tag2)+1) / float64(this.f1Counts(this.tagCounts, tag1)+int64(vocabSize))
} else if this.GOODTURING {
if !this.goodTuringCountsAvailable {
this.fMakeGoodTuringCounts()
}
gtcount := this.fd2Counts(this.goodTuringTagBigramCounts, tag1, tag2)
if gtcount > 0.0 {
return gtcount / float64(this.fd1Counts(this.goodTuringTagUnigramCounts, tag1))
}
return float64(this.fNumberOfBigramsWithCount(1)) / float64(this.numTrainingBigrams)
} else {
return float64(this.f2Counts(this.tagBigramCounts, tag1, tag2)) / float64(this.f1Counts(this.tagCounts, tag1))
}
}
func (this *HMM) FViterbi(words []string) {
sentenceStart := true
var prevMap map[string]*Node
for i, word := range words {
sm := make(map[string]*Node)
if sentenceStart {
n := NewFullNode(word, "<s>", nil, 1.0)
sm[word] = n
sentenceStart = false
} else {
if tagcounts, exists := this.tagForWordCounts[word]; exists {
for tag, _ := range tagcounts {
sm[tag] = this.fCalcNode(word, tag, prevMap)
}
} else if strings.Title(word) == word {
sm["NNP"] = this.fCalcNode(word, "NNP", prevMap)
} else if re1.MatchString(word) || re2.MatchString(word) {
sm["CD"] = this.fCalcNode(word, "CD", prevMap)
} else if strings.Contains(word, "-") || strings.HasSuffix(word, "able") {
sm["JJ"] = this.fCalcNode(word, "JJ", prevMap)
} else if strings.HasPrefix(word, "ing") {
sm["VBG"] = this.fCalcNode(word, "VBG", prevMap)
} else if strings.HasPrefix(word, "ly") {
sm["RB"] = this.fCalcNode(word, "RB", prevMap)
} else if strings.HasPrefix(word, "ed") {
sm["VBN"] = this.fCalcNode(word, "VBN", prevMap)
} else if strings.HasPrefix(word, "s") {
sm["NNS"] = this.fCalcNode(word, "NNS", prevMap)
} else {
//sm[this.mostFreqTag] = this.fCalcNode(word, this.mostFreqTag, prevMap)
//newNode := this.fCalcUnseenWordNode(word, prevMap)
//sm[newNode.tag] = newNode
for tag, _ := range this.tagCounts {
sm[tag] = this.fCalcNode(word, tag, prevMap)
}
}
if i == len(words)-1 || words[i] == "<s>" {
this.fBacktrace(sm)
sentenceStart = true
}
}
prevMap = sm
}
}
func (this *HMM) fCalcNode(word string, tag string, prevMap map[string]*Node) *Node {
n := NewSimpleNode(word, tag)
maxProb := 0.0
for prevTag, prevNode := range prevMap {
prevProb := prevNode.prob
prevProb *= this.fCalcPriorProb(prevTag, tag)
if prevProb >= maxProb {
maxProb = prevProb
n.parent = prevNode
}
}
n.prob = maxProb * this.fCalcLikelihood(tag, word)
return n
}
func (this *HMM) fBacktrace(m map[string]*Node) {
n := NewSimpleNode("NOMAX", "NOMAX")
for _, currentNode := range m {
if currentNode.prob >= n.prob {
n = currentNode
}
}
stack := new(Stack)
for n != nil {
stack.Push(n)
n = n.parent
}
for stack.Len() != 0 {
n = stack.Pop().(*Node)
this.writer += n.tag + " " + n.word + " "
}
println(this.writer)
}
func (this *HMM) fCalcUnseenWordNode(word string, prevMap map[string]*Node) *Node {
maxProb := 0.0
bestTag := "NOTAG"
var bestParent *Node
for prevTag, prevNode := range prevMap {
prevProb := prevNode.prob
possibleTagMap := this.tagBigramCounts[prevTag]
var maxCount int64 = 0
nextTag := "NOTAG"
for possibleTag, count := range possibleTagMap {
if count > maxCount {
maxCount = count
nextTag = possibleTag
}
}
prevProb *= this.fCalcPriorProb(prevTag, nextTag)
if prevProb >= maxProb {
maxProb = prevProb
bestTag = nextTag
bestParent = prevNode
}
}
return NewFullNode(word, bestTag, bestParent, maxProb*this.fCalcLikelihood(bestTag, word))
}
|
package main
import "fmt"
func desc(s1 []int) {
fmt.Printf("s1: %p; Len: %d, Cap: %d; %#v\n", s1, len(s1), cap(s1), s1)
for idx, el := range s1 {
fmt.Println("\t", idx, ":", el)
}
}
func main() {
// s := make([]int, 5)
s := []int{1, 2, 3, 5, 7}
desc(s)
s = s[0:1]
desc(s)
s = s[0:cap(s)]
desc(s)
}
|
package solutions
func letterCombinations(digits string) []string {
if len(digits) == 0 {
return nil
}
result := make([]string, 0)
combinations(&result, digits, "", 0)
return result
}
func combinations(result *[]string, digits string, letters string, i int) {
if i == len(digits) {
*result = append(*result, letters)
return
}
var hash = map[uint8]string {
'2': "abc",
'3': "def",
'4': "ghi",
'5': "jkl",
'6': "mno",
'7': "pqrs",
'8': "tuv",
'9': "wxyz",
}
for _, c := range hash[digits[i]] {
combinations(result, digits, letters + string(c), i + 1)
}
}
|
package raft
import "github.com/shaneing/go-examples/raft/pb"
type TransportInterface interface {
SendAppendEntries(server Server, request *raftpb.AppendEntriesRequest) (*raftpb.AppendEntriesReply, error)
SendRequestVote(server Server, request *raftpb.RequestVoteRequest) (*raftpb.RequestVoteReply, error)
LocalAddr() ServerAddress
Consumer() <-chan *RPC
}
type RPC struct {
Request interface{}
ResponseCh chan RPCResponse
}
func (r *RPC) Reply(resp interface{}, err error) {
r.ResponseCh <- RPCResponse{
Err: err,
Data: resp,
}
}
type RPCResponse struct {
Err error
Data interface{}
}
|
package metrics
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/tilt-dev/tilt/internal/tiltfile/starkit"
)
func TestMetricsEnabled(t *testing.T) {
f := newFixture(t)
f.File("Tiltfile", "experimental_metrics_settings(enabled=True)")
_, err := f.ExecFile("Tiltfile")
assert.NoError(t, err)
assert.Contains(t, f.PrintOutput(), "deprecated")
}
func newFixture(tb testing.TB) *starkit.Fixture {
return starkit.NewFixture(tb, NewPlugin())
}
|
package app
import (
"github.com/kataras/iris"
"../app/configs"
)
type App struct {
}
func New() (app *App) {
return
}
func (app *App) Start() {
irisApp := iris.New()
configs.ConfigureServer(irisApp)
configs.ConfigureRoutes(irisApp)
configs.ConfigureDB()
irisApp.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed))
}
|
package main
import (
"fmt"
"gopkg.in/yaml.v2"
)
var e = yaml.Encoder{}
func init() { fmt.Printf("Type: %T\n", e) }
func main() {}
|
//
// Copyright (c) SAS Institute 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 comdoc
import (
"errors"
"fmt"
"io"
)
type streamReader struct {
remaining uint32
nextSector SecID
sat []SecID
sectorSize int
readSector func(SecID, []byte) (int, error)
buf, saved []byte
}
// Open a stream for reading
func (r *ComDoc) ReadStream(e *DirEnt) (io.Reader, error) {
if e.Type != DirStream {
return nil, errors.New("not a stream")
}
sr := &streamReader{
remaining: e.StreamSize,
nextSector: e.NextSector,
}
if e.StreamSize < r.Header.MinStdStreamSize {
sr.sectorSize = r.ShortSectorSize
sr.sat = r.SSAT
sr.readSector = r.readShortSector
} else {
sr.sectorSize = r.SectorSize
sr.sat = r.SAT
sr.readSector = r.readSector
}
sr.buf = make([]byte, sr.sectorSize)
return sr, nil
}
func (sr *streamReader) Read(d []byte) (copied int, err error) {
if sr.remaining == 0 {
return 0, io.EOF
} else if len(d) == 0 {
return 0, nil
}
if int64(len(d)) > int64(sr.remaining) {
d = d[:int(sr.remaining)]
}
// read from previously buffered sector
if len(sr.saved) > 0 {
n := copy(d, sr.saved)
d = d[n:]
sr.saved = sr.saved[n:]
copied += n
sr.remaining -= uint32(n)
}
// read whole sectors
for len(d) >= sr.sectorSize {
if sr.nextSector < 0 {
return copied, errors.New("unexpected end to stream")
}
n, err := sr.readSector(sr.nextSector, d[:sr.sectorSize])
if n > 0 {
d = d[n:]
copied += n
sr.remaining -= uint32(n)
}
if err != io.EOF && err != nil {
return copied, err
} else if n < sr.sectorSize && sr.remaining > 0 {
return copied, fmt.Errorf("short read of sector %d: expected %d bytes but got %d", sr.nextSector, sr.sectorSize, n)
}
sr.nextSector = sr.sat[sr.nextSector]
}
// read partial sector and buffer the rest
if len(d) > 0 {
if sr.nextSector < 0 {
return copied, errors.New("unexpected end to stream")
}
// read the full sector
sectorN, err := sr.readSector(sr.nextSector, sr.buf)
if sectorN > 0 {
// fill the rest of the result
copyN := copy(d, sr.buf)
copied += copyN
sr.remaining -= uint32(copyN)
}
if err != io.EOF && err != nil {
return copied, err
} else if sectorN < sr.sectorSize && sr.remaining > 0 {
// it's ok if the final sector is truncated if there are no more bytes in the stream
return copied, fmt.Errorf("short read of sector %d: expected %d bytes but got %d", sr.nextSector, sr.remaining, sectorN)
}
// save the remainder, if anything
sr.saved = sr.buf[len(d):]
sr.nextSector = sr.sat[sr.nextSector]
}
return copied, nil
}
// Store a blob as a chain of sectors, updating the sector table (or
// short-sector table if "short" is set) and return the first sector ID
func (r *ComDoc) addStream(contents []byte, short bool) (SecID, error) {
var sectorSize int
var sat, freeList []SecID
if short {
sectorSize = int(r.ShortSectorSize)
needSectors := (len(contents) + sectorSize - 1) / sectorSize
freeList = r.makeFreeSectors(needSectors, true)
sat = r.SSAT
} else {
sectorSize = int(r.SectorSize)
needSectors := (len(contents) + sectorSize - 1) / sectorSize
freeList = r.makeFreeSectors(needSectors, false)
sat = r.SAT
}
first := SecIDEndOfChain
previous := first
for _, i := range freeList {
if previous == SecIDEndOfChain {
first = i
} else {
sat[previous] = i
}
previous = i
// write to file
n := sectorSize
if n > len(contents) {
n = len(contents)
}
var err error
if short {
err = r.writeShortSector(i, contents[:n])
} else {
err = r.writeSector(i, contents[:n])
}
if err != nil {
return 0, err
}
contents = contents[n:]
}
sat[previous] = SecIDEndOfChain
if len(contents) > 0 {
panic("didn't allocate enough sectors")
}
return first, nil
}
|
package main
import (
"fmt"
)
func main() {
//fmt.Println(check())
//a:=make([]string,10)
a := []string{"a", "b", "c", "d"}
//join := strings.Join(a, "c")
//fmt.Println(join)
VarAgesJoin(a, "aaa", "vvv")
fmt.Println(a)
}
func check(vals ...int) (max, min int) {
if len(vals) == 0 {
return
}
max, min = vals[0], vals[0]
for _, val := range vals {
if val > max {
max = val
}
if val < min {
min = val
}
}
return
}
func VarAgesJoin(a []string, seqs ...string) {
if len(seqs) == 0 {
return
}
for _, val := range a {
}
}
|
package function
func Returnval(a, b int) (int, int, int) {
return a + b, a * b, a - b
}
func Returnval2(a, b int) (sum, mul, diff int) {
sum = a + b
mul = a * b
diff = a - b
return
}
|
package godlutil
import (
"crypto/sha256"
"fmt"
"io"
"path"
"github.com/mitchellh/go-homedir"
)
// GetDownloadDir returns the `godl` download directory
func GetDownloadDir() (string, error) {
home, err := homedir.Dir()
if err != nil {
return "", fmt.Errorf("home directory cannot be detected: %v", err)
}
return path.Join(home, ".godl", "downloads"), nil
}
// Must enforces that error is non-nil else it panics
func Must(err error) {
if err != nil {
panic(err)
}
}
// VerifyHash reports whether the named file has contents with
// SHA-256 of the given hex value.
func VerifyHash(input io.Reader, hex string) error {
hash := sha256.New()
if _, err := io.Copy(hash, input); err != nil {
return err
}
if hex != fmt.Sprintf("%x", hash.Sum(nil)) {
return fmt.Errorf("%s corrupt? does not have expected SHA-256 of %v", input, hex)
}
return nil
}
|
package main
import (
"configer/server"
"configer/server/structure"
"fmt"
)
func main() {
a := &structure.A{Name: "wmq"}
exist, err := server.Get(server.NewAer(a))
fmt.Println(a, exist, err)
b := &structure.A{Name: "wxx", Age: 30}
num, err := server.Insert(server.NewAer(b))
fmt.Println(num, err)
}
|
package application
import (
"flag"
"fmt"
"strings"
)
type App struct {
oneOff oneOff
}
type oneOff interface {
Run(oneOffInputs OneOffInputs) error
}
func New(oneOff oneOff) App {
return App{
oneOff: oneOff,
}
}
func (a App) Execute(args []string) error {
oneOffInputs, err := a.parseArgs(args)
if err != nil {
return err
}
err = a.validateInputs(oneOffInputs)
if err != nil {
return err
}
err = a.oneOff.Run(oneOffInputs)
if err != nil {
return err
}
return nil
}
func (App) parseArgs(args []string) (OneOffInputs, error) {
var oneOffInputs OneOffInputs
flags := flag.NewFlagSet("app", flag.ContinueOnError)
flags.StringVar(&oneOffInputs.TargetAlias, "ta", "", "concourse target alias")
flags.StringVar(&oneOffInputs.Pipeline, "p", "", "name of pipeline")
flags.StringVar(&oneOffInputs.Job, "j", "", "name of job")
flags.StringVar(&oneOffInputs.Task, "t", "", "name of task")
flags.StringVar(&oneOffInputs.FlyOverride, "fo", "", `(optional) override path to fly. one-off uses "fly" in $PATH by default`)
err := flags.Parse(args)
if err != nil {
return OneOffInputs{}, err
}
return oneOffInputs, nil
}
func (App) validateInputs(oneOffInputs OneOffInputs) error {
var errs []string
if oneOffInputs.TargetAlias == "" {
errs = append(errs, "target alias -ta")
}
if oneOffInputs.Pipeline == "" {
errs = append(errs, "pipeline -p")
}
if oneOffInputs.Job == "" {
errs = append(errs, "job -j")
}
if oneOffInputs.Task == "" {
errs = append(errs, "task -t")
}
if len(errs) > 0 {
return fmt.Errorf("missing %s", strings.Join(errs, ", "))
}
return nil
}
|
package structs
import "math"
type Shape interface {
Area() float64
}
type Rectangle struct {
Width float64
Height float64
}
type Circle struct {
Radius float64
}
type Triangle struct {
Base float64
Height float64
}
type Person struct {
AgeYears int
Name string
Friends []Person
}
func NewPerson() Person {
var p Person
return p
}
func NewPersonPointer() *Person {
var p *Person
return p
}
func NewPersonPointer2() *Person {
p := &Person{}
return p
}
func Perimeter(rectangle Rectangle) float64 {
return 2 * (rectangle.Width + rectangle.Height)
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func (c Circle) Area() float64 {
return math.Pi * c.Radius * c.Radius
}
func (t Triangle) Area() float64 {
return (t.Base * t.Height) / 2
}
|
package legs
import (
"context"
dt "github.com/filecoin-project/go-data-transfer"
"github.com/ipfs/go-cid"
"github.com/kenlabs/pando/pkg/metrics"
"sync"
)
type dataTransferRecorder struct {
record map[cid.Cid]func()
lock sync.Mutex
}
var recorder = dataTransferRecorder{
record: make(map[cid.Cid]func()),
lock: sync.Mutex{},
}
func onDataTransferComplete(event dt.Event, channelState dt.ChannelState) {
logger.Debugf("transfer event: %s, cid: %s\n", dt.Events[event.Code], channelState.BaseCID())
if event.Code == dt.Open {
recorder.lock.Lock()
recorder.record[channelState.BaseCID()] =
metrics.APITimer(context.Background(), metrics.GraphPersistenceLatency)
recorder.lock.Unlock()
}
if event.Code == dt.FinishTransfer {
recorder.lock.Lock()
if record, exist := recorder.record[channelState.BaseCID()]; exist {
record()
}
recorder.lock.Unlock()
}
}
|
package main
import (
"github.com/cobersky/xlsxconv"
)
func main() {
xlsxconv.Launch()
}
|
package arraysandstrings
func ContainsOnlyUniqueChars(str string) bool {
m := make(map[rune]int)
for _, c := range str {
_, exists := m[c]
if (exists) {
return false
}
m[c] = 1
}
return true
}
func ContainsOnlyUniqueCharsWithoutDataStructure(str string) bool {
var substr string
for i, c := range str {
substr = str[i+1:]
for _, o := range substr {
if (c == o) {
return false
}
}
}
return true
}
func ContainsOnlyUniqueCharsForLowerAscii(str string) bool {
var tally uint = 0
var offset uint;
var mask uint = 0
for _, c := range str {
offset = uint(c - 'a')
mask = 0
mask = 1 << offset
if (tally & mask > 0) {
return false
}
tally |= mask
}
return true
}
|
package json
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"strings"
formatter_api "github.com/cyberark/secretless-broker/bin/juxtaposer/formatter/api"
"github.com/cyberark/secretless-broker/bin/juxtaposer/formatter/util"
"github.com/cyberark/secretless-broker/bin/juxtaposer/timing"
)
type JsonFormatter struct {
Options formatter_api.FormatterOptions
}
type ConfidenceIntervalJson struct {
IntervalPercent int `json:"intervalPercent"`
LowerBoundPercent float64 `json:"lowerBoundPercent"`
UpperBoundPercent float64 `json:"upperBoundPercent"`
}
type BackendTimingDataJson struct {
AverageDurationNs int64 `json:"averageDurationNs"`
ConfidenceInterval ConfidenceIntervalJson `json:"confidenceInterval"`
Errors []timing.TestRunError `json:"errors"`
FailedRounds int `json:"failedRounds"`
MaximumDurationNs int64 `json:"maximumDurationNs"`
MinimumDurationNs int64 `json:"minimumDurationNs"`
SuccessfulRounds int `json:"successfulRounds"`
SuccessPercentage float64 `json:"successPercentage"`
ThresholdBreachedPercent float64 `json:"thresholdBreachedPercent"`
TotalDurationNs int64 `json:"totalDurationNs"`
TotalRounds int `json:"totalRounds"`
}
type JsonOutput struct {
Backends map[string]BackendTimingDataJson `json:"backends"`
}
func NewFormatter(options formatter_api.FormatterOptions) (formatter_api.OutputFormatter, error) {
return &JsonFormatter{
Options: options,
}, nil
}
func (formatter *JsonFormatter) ProcessResults(backendNames []string,
aggregatedTimings map[string]timing.BackendTiming, baselineThresholdMaxPercent int) error {
jsonOutput := JsonOutput{
Backends: map[string]BackendTimingDataJson{},
}
for _, backendName := range backendNames {
timingInfo := aggregatedTimings[backendName]
failedRounds := len(timingInfo.Errors)
successfulRounds := timingInfo.Count - failedRounds
averageDuration := util.GetAverageDuration(&timingInfo)
successPercentage := util.GetSuccessPercentage(&timingInfo)
lowerBoundCI, upperBoundCI := util.GetConfidenceInterval90(&timingInfo.BaselineDivergencePercent)
thresholdBreachedPercent := util.GetThresholdBreachedPercent(&timingInfo.BaselineDivergencePercent,
baselineThresholdMaxPercent)
timingDataJson := BackendTimingDataJson{
AverageDurationNs: averageDuration.Nanoseconds(),
Errors: timingInfo.Errors,
FailedRounds: failedRounds,
ConfidenceInterval: ConfidenceIntervalJson{
IntervalPercent: 90,
LowerBoundPercent: lowerBoundCI,
UpperBoundPercent: upperBoundCI,
},
MaximumDurationNs: timingInfo.MaximumDuration.Nanoseconds(),
MinimumDurationNs: timingInfo.MinimumDuration.Nanoseconds(),
SuccessfulRounds: successfulRounds,
SuccessPercentage: successPercentage,
ThresholdBreachedPercent: thresholdBreachedPercent,
TotalDurationNs: timingInfo.Duration.Nanoseconds(),
TotalRounds: timingInfo.Count,
}
jsonOutput.Backends[backendName] = timingDataJson
}
timingInfoBytes, err := json.MarshalIndent(jsonOutput, "", strings.Repeat(" ", 4))
if err != nil {
return err
}
outputFilename := formatter.Options["outputFile"]
if outputFilename == "" {
fmt.Printf("%s\n", timingInfoBytes)
return nil
}
err = ioutil.WriteFile(outputFilename, timingInfoBytes, 0644)
if err == nil {
log.Printf("Successfully wrote JSON results to file '%s'.", outputFilename)
}
return err
}
|
//
// goamz - Go packages to interact with the Amazon Web Services.
//
// https://wiki.ubuntu.com/goamz
//
// Copyright (c) 2011 Canonical Ltd.
//
// Written by Graham Miller <graham.miller@gmail.com>
//
package mturk
import (
"bytes"
"os"
"http"
"url"
"time"
"xml"
"strconv"
"fmt"
"launchpad.net/goamz/aws"
)
const (
TIMESTAMP_FORMAT = "2006-01-02T15:04:05Z"
MTURK_SERVICE = "AWSMechanicalTurkRequester"
MTURK_URL = "http://mechanicalturk.amazonaws.com/"
)
type MTurk struct {
aws.Auth
URL *url.URL
}
func New(auth aws.Auth) *MTurk {
mt := &MTurk{Auth:auth}
var err os.Error
mt.URL, err = url.Parse(MTURK_URL)
if err != nil {
panic(err.String())
}
return mt
}
// ----------------------------------------------------------------------------
// Request dispatching logic.
// Error encapsulates an error returned by MTurk.
type Error struct {
StatusCode int // HTTP status code (200, 403, ...)
Code string // EC2 error code ("UnsupportedOperation", ...)
Message string // The human-oriented error message
RequestId string
}
func (err *Error) String() string {
return err.Message
}
// The request stanza included in several response types, for example
// in a "CreateHITResponse". http://goo.gl/qGeKf
type xmlRequest struct {
RequestId string
IsValid string
Errors []Error `xml:"Errors>Error"`
}
// Common price structure used in requests and responses
// http://goo.gl/tE4AV
type Price struct {
Amount string
CurrencyCode string
FormattedPrice string
}
// Really just a country string
// http://goo.gl/mU4uG
type Locale string
// Data structure used to specify requirements for the worker
// used in CreateHIT, for example
// http://goo.gl/LvRo9
type QualificationRequirement struct {
QualificationTypeId string
Comparator string
IntegerValue int
LocaleValue Locale
RequiredToPreview string
}
// Data structure holding the contents of an "external"
// question. http://goo.gl/NP8Aa
type ExternalQuestion struct {
XMLName xml.Name `xml:"http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2006-07-14/ExternalQuestion.xsd ExternalQuestion"`
ExternalURL string
FrameHeight int
}
// The data structure representing a "human interface task" (HIT)
// Currently only supports "external" questions, because Go
// structs don't support union types. http://goo.gl/NP8Aa
// This type is returned, for example, from SearchHITs
// http://goo.gl/PskcX
type HIT struct {
Request xmlRequest
HITId string
HITTypeId string
CreationTime string
Title string
Description string
Keywords string
HITStatus string
Reward Price
LifetimeInSeconds uint
AssignmentDurationInSeconds uint
MaxAssignments uint
AutoApprovalDelayInSeconds uint
QualificationRequirement QualificationRequirement
Question ExternalQuestion
RequesterAnnotation string
NumberofSimilarHITs uint
HITReviewStatus string
NumberofAssignmentsPending uint
NumberofAssignmentsAvailable uint
NumberofAssignmentsCompleted uint
}
// The main data structure returned by SearchHITs
// http://goo.gl/PskcX
type SearchHITsResult struct {
NumResults uint
PageNumber uint
TotalNumResults uint
HITs []HIT `xml:"HIT"`
}
// The wrapper data structure returned by SearchHITs
// http://goo.gl/PskcX
type SearchHITsResponse struct {
RequestId string `xml:"OperationRequest>RequestId"`
SearchHITsResult
}
// The wrapper data structure returned by CreateHIT
// http://goo.gl/PskcX
type CreateHITResponse struct {
RequestId string `xml:"OperationRequest>RequestId"`
HIT
}
// Corresponds to the "CreateHIT" operation of the Mechanical Turk
// API. http://goo.gl/cDBRc Currently only supports "external"
// questions (see "HIT" struct above). If "keywords", "maxAssignments",
// "qualificationRequirement" or "requesterAnnotation" are the zero
// value for their types, they will not be included in the request.
func (mt *MTurk) CreateHIT(title, description string, question ExternalQuestion, reward Price, assignmentDurationInSeconds, lifetimeInSeconds uint, keywords string, maxAssignments uint, qualificationRequirement *QualificationRequirement, requesterAnnotation string) (h *HIT, err os.Error) {
params := make(map[string]string)
params["Title"] = title
params["Description"] = description
params["Question"], err = xmlEncode(&question)
println("sending question", params["Question"])
if err != nil {
return
}
params["Reward.1.Amount"] = reward.Amount
params["Reward.1.CurrencyCode"] = reward.CurrencyCode
params["AssignmentDurationInSeconds"] = strconv.Uitoa(assignmentDurationInSeconds)
params["LifetimeInSeconds"] = strconv.Uitoa(lifetimeInSeconds)
if keywords != "" {
params["Keywords"] = keywords
}
if maxAssignments != 0 {
params["MaxAssignments"] = strconv.Uitoa(maxAssignments)
}
if qualificationRequirement != nil {
params["QualificationRequirement"], err = xmlEncode(qualificationRequirement)
if err != nil {
return
}
}
if requesterAnnotation != "" {
params["RequesterAnnotation"] = requesterAnnotation
}
var response CreateHITResponse
err = mt.query(params, "CreateHIT", &response)
if err == nil {
h = &response.HIT
}
return
}
// Corresponds to the "CreateHIT" operation of the Mechanical Turk
// API, using an existing "hit type". http://goo.gl/cDBRc Currently only
// supports "external" questions (see "HIT" struct above). If
// "maxAssignments" or "requesterAnnotation" are the zero value for
// their types, they will not be included in the request.
func (mt *MTurk) CreateHITOfType(hitTypeId string, q ExternalQuestion, lifetimeInSeconds uint, maxAssignments uint, requesterAnnotation string) (h *HIT, err os.Error) {
params := make(map[string]string)
params["HITTypeId"] = hitTypeId
params["Question"], err = xmlEncode(&q)
if err != nil {
return
}
params["LifetimeInSeconds"] = strconv.Uitoa(lifetimeInSeconds)
if maxAssignments != 0 {
params["MaxAssignments"] = strconv.Uitoa(maxAssignments)
}
if requesterAnnotation != "" {
params["RequesterAnnotation"] = requesterAnnotation
}
var response CreateHITResponse
err = mt.query(params, "CreateHIT", &response)
if err == nil {
h = &response.HIT
}
return
}
// Corresponds to "SearchHITs" operation of Mechanical Turk. http://goo.gl/PskcX
// Currenlty supports none of the optional parameters.
func (mt *MTurk) SearchHITs() (s *SearchHITsResult, err os.Error) {
params := make(map[string]string)
var response SearchHITsResponse
err = mt.query(params, "SearchHITs", &response)
if err == nil {
s = &response.SearchHITsResult
}
return
}
// Adds common parameters to the "params" map, signs the request,
// adds the signature to the "params" map and sends the request
// to the server. It then unmarshals the response in to the "resp"
// parameter using xml.Unmarshal()
func (mt *MTurk) query(params map[string]string, operation string, resp interface{}) os.Error {
service := MTURK_SERVICE
timestamp := time.UTC().Format(TIMESTAMP_FORMAT)
params["AWSAccessKeyId"] = mt.Auth.AccessKey
params["Service"] = service
params["Timestamp"] = timestamp
params["Operation"] = operation
// make a copy
url := *mt.URL
sign(mt.Auth, service, operation, timestamp, params)
url.RawQuery = multimap(params).Encode()
r, err := http.Get(url.String())
if err != nil {
return err
}
dump, _ := http.DumpResponse(r, true)
println("DUMP:\n", string(dump))
if r.StatusCode != 200 {
return os.NewError(fmt.Sprintf("%d: unexpected status code", r.StatusCode))
}
err = xml.Unmarshal(r.Body, resp)
r.Body.Close()
return err
}
func multimap(p map[string]string) url.Values {
q := make(url.Values, len(p))
for k, v := range p {
q[k] = []string{v}
}
return q
}
func xmlEncode(i interface{}) (s string, err os.Error) {
var buf bytes.Buffer
err = xml.Marshal(&buf, i)
if err != nil {
return
}
s = buf.String()
fmt.Printf("marshaled %v as %s\n", i, s)
return
}
|
/*
* Copyright (c) 2020. Uriel Márquez All Rights Reserved
* https://umarquez.c0d3.mx
*/
package day1_test
import (
"log"
"main/day1"
"strconv"
"strings"
"testing"
)
var input = `1348
1621
1500
1818
1266
1449
1880
1416
1862
1665
1588
1704
1922
1482
1679
1263
1137
1045
1405
1048
1619
1520
455
1142
1415
1554
1690
1886
1891
1701
1915
1521
1253
1580
1376
1564
1747
1814
1749
1485
1969
974
1566
1413
1451
1200
1558
1756
1910
1044
470
1620
1772
1066
1261
1776
988
1976
1834
1896
1646
1626
1300
1692
1204
2006
1265
1911
1361
1766
1750
2000
1824
1726
1672
651
1226
1954
1055
1999
1793
1640
1567
1040
1426
1717
1658
1864
1917
695
1071
1573
1897
1546
1727
1801
1259
1290
1481
1148
1332
1262
1536
1184
1821
1681
1671
1612
1678
1703
1604
1697
2003
1453
1493
1797
1180
1234
1775
1859
1388
1393
667
1767
1429
1990
1322
1684
1696
1565
1380
1745
1685
1189
1396
1593
1850
1722
1495
1844
1285
1483
1635
1072
1947
1109
1586
1730
1723
1246
1389
1135
1827
1531
1583
1743
1958
183
1323
1949
1799
1269
1379
1950
1592
1467
1052
1418
2009
1227
1254
1865
1609
1848
1653
1691
1633
1349
1104
1790
1755
1847
1598
1872
1478
1778
1952
1694
1238
1825
1508
1141
1464
1838
1292
1403
1365
1494
934
1235`
var values []int
func TestFindNumbersAndMultiply(t *testing.T) {
type args struct {
sum int
nums int
values []int
}
tests := []struct {
name string
args args
want int
wantErr bool
}{
{
name: "incorrect numbers",
args: args{
sum: 2020,
nums: 1,
values: values,
},
want: -1,
wantErr: true,
},
{
name: "two numbers that sums 2020",
args: args{
sum: 2020,
nums: 2,
values: values,
},
want: 712075,
wantErr: false,
},
{
name: "three numbers that sums 2020",
args: args{
sum: 2020,
nums: 3,
values: values,
},
want: 145245270,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := day1.FindNumbersAndMultiply(tt.args.sum, tt.args.nums, tt.args.values...)
if (err != nil) != tt.wantErr {
t.Errorf("FindNumbersAndMultiply() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("FindNumbersAndMultiply() got = %v, want %v", got, tt.want)
}
})
}
}
func init() {
for _, line := range strings.Split(input, "\n") {
num, err := strconv.Atoi(line)
if err != nil {
log.Fatalf("error decoding input text, %v", err)
}
values = append(values, num)
}
}
|
package datastore
import (
"github.com/mongodb/mongo-go-driver/mongo"
)
func IsDuplicateError(err error) bool {
if err, ok := err.(mongo.WriteErrors); ok {
if (err)[0].Code == 11000 {
return true
}
}
return false
}
func IsNotFoundError(err error) bool {
return err.Error() == mongo.ErrNoDocuments.Error()
}
|
package robot
var move []Point = []Point{
{0, 1},
{1, 0},
{0, -1},
{-1, 0},
}
// Advance goes forward
func Advance() {
Step1Robot.X += move[Step1Robot.Dir].X
Step1Robot.Y += move[Step1Robot.Dir].Y
}
// Right turns right
func Right() {
Step1Robot.Dir = (Step1Robot.Dir + 1) % 4
}
// Left turns left
func Left() {
Step1Robot.Dir = (Step1Robot.Dir + 3) % 4
}
func StartRobot(cmd chan Command, act chan Action) {
for c := range cmd {
act <- Action(c)
}
close(act)
}
func isInRoom(x, y RU, rect Rect) bool {
return x >= rect.Min.Easting && x <= rect.Max.Easting &&
y >= rect.Min.Northing && y <= rect.Max.Northing
}
func goForward(robot *Step2Robot, rect Rect) {
var newX, newY RU
newX = robot.Easting + RU(move[robot.Dir].X)
newY = robot.Northing + RU(move[robot.Dir].Y)
if isInRoom(newX, newY, rect) {
robot.Pos = Pos{newX, newY}
}
}
func turn(robot *Step2Robot, alpha int) {
robot.Dir = Dir(int(robot.Dir)+alpha+4) % 4
}
func Room(rect Rect, robot Step2Robot, act chan Action, rep chan Step2Robot) {
for a := range act {
switch a {
case 'A':
goForward(&robot, rect)
case 'R':
turn(&robot, 1)
case 'L':
turn(&robot, -1)
}
}
rep <- robot
}
func StartRobot3(name string, script string, act chan Action3, log chan string) {
act <- Action3{name, script}
act <- Action3{name, "D"}
}
func Room3(rect Rect, robots []Step3Robot, act chan Action3, rep chan []Step3Robot, log chan string) {
robotExistence := map[string]*Step3Robot{}
isPlaced := map[Pos]bool{}
for i := range robots {
if robots[i].Name == "" {
log <- "Robot has noname"
}
if robotExistence[robots[i].Name] != nil {
log <- "Duplicate robot name"
} else {
robotExistence[robots[i].Name] = &robots[i]
}
if isPlaced[robots[i].Pos] {
log <- "Robot placed at the same place"
} else {
isPlaced[robots[i].Pos] = true
}
if !isInRoom(robots[i].Easting, robots[i].Northing, rect) {
log <- "Robot placed outside of the room"
}
}
doneCount := 0
for a := range act {
robot := robotExistence[a.Name]
script := a.Script
if len(script) == 1 && script[0] == 'D' {
doneCount++
if doneCount == len(robots) {
rep <- robots
return
}
}
if robot == nil {
log <- "An action from unknown robot"
}
for _, action := range script {
if robot != nil {
if action == ' ' || action == 'D' {
} else if action == 'A' {
newX := robot.Easting + RU(move[robot.Dir].X)
newY := robot.Northing + RU(move[robot.Dir].Y)
if !isInRoom(newX, newY, rect) {
log <- "A robot attempting to advance into a wall"
} else {
if isPlaced[Pos{newX, newY}] {
log <- "A robot attempting to advance into another robot"
} else {
isPlaced[robot.Pos] = false
isPlaced[Pos{newX, newY}] = true
goForward(&robot.Step2Robot, rect)
}
}
} else if action == 'R' {
turn(&robot.Step2Robot, 1)
} else if action == 'L' {
turn(&robot.Step2Robot, -1)
} else {
log <- "An undefined command in a script"
break
}
}
}
}
}
|
package testing
import (
"fmt"
"github.com/gruntwork-io/terratest/modules/terraform"
"github.com/stretchr/testify/suite"
"testing"
)
type resourceGroupSuite struct {
terraformOptions *terraform.Options
fixturefolde string
suite.Suite
}
func TestInputOutput(t *testing.T) {
suite.Run(t, new(resourceGroupSuite))
}
//func (suite *resourcegroupSuite) TearDownTest() {
// fmt.Println("This will run after every test")
//}
func (suite *resourceGroupSuite) SetupSuite() {
fixtureDir := "./fixture"
suite.fixturefolde = fixtureDir
terraformOptions := &terraform.Options{
TerraformDir: fixtureDir,
}
terraform.InitAndApply(suite.T(), terraformOptions)
suite.terraformOptions = terraformOptions
fmt.Println("This will run once before one suite test")
}
func (suite *resourceGroupSuite) TearDownSuite() {
fmt.Println("This will run once after one suite test")
terraform.Destroy(suite.T(), suite.terraformOptions)
}
//func (t *inputoutsuite) SetupTest() {
// fmt.Println("this is run before every test")
//}
func (a resourceGroupSuite) TestOne() {
actualOuputName := terraform.Output(a.T(), a.terraformOptions, "resource_group_name")
a.Equal("voyager-infra-test-centralus-rg-unit-test", actualOuputName)
}
func (a resourceGroupSuite) TestTwo() {
actualOutputLocation := terraform.Output(a.T(), a.terraformOptions, "resource_group_location")
a.Equal("centralus", actualOutputLocation)
}
|
package owplugin
import (
// Please excuse this
"nano/plugins/ow"
"github.com/Krognol/dgofw"
)
func OWOnMessage(m *dgofw.DiscordMessage) {
bt := m.Arg("battletag")
region := m.Arg("region")
if bt == "" || region == "" {
return
}
stats, err := ow.GetStats(bt, region)
if err != nil {
m.Reply("Something happened...")
return
}
m.ReplyEmbed(stats)
}
|
package vault
import (
"bytes"
"crypto/rand"
"errors"
"io"
"io/ioutil"
"os"
"path"
"encoding/gob"
"github.com/NebulousLabs/entropy-mnemonics"
"golang.org/x/crypto/nacl/secretbox"
"golang.org/x/crypto/scrypt"
)
const (
scryptN = 16384
scryptR = 8
scryptP = 1
keyLen = 32
genEntropySize = 16
)
var (
// ErrNoSuchCredential is returned from a Get call if the requested
// credential does not exist
ErrNoSuchCredential = errors.New("credential at specified location does not exist in vault")
// ErrCouldNotDecrypt is returned if secretbox decryption fails.
ErrCouldNotDecrypt = errors.New("provided decryption key is incorrect or the provided vault is corrupt")
// ErrCredentialExists is returned from Add if a credential already exists
// at the provided location.
ErrCredentialExists = errors.New("credential at specified location already exists")
)
type (
// Vault is a secure password vault. It can be created by calling New()
// with a passphrase. Passwords, usernames, and locations are encrypted
// using nacl/secretbox.
Vault struct {
data []byte
nonce [24]byte
secret [32]byte
}
// Credential defines a Username and Password to store inside the vault.
Credential struct {
Username string
Password string
}
)
// New creates a new, empty, vault using the passphrase provided to
// `passphrase`.
func New(passphrase string) (*Vault, error) {
var nonce [24]byte
if _, err := io.ReadFull(rand.Reader, nonce[:]); err != nil {
panic(err)
}
var secret [32]byte
key, err := scrypt.Key([]byte(passphrase), nonce[:], scryptN, scryptR, scryptP, keyLen)
if err != nil {
panic(err)
}
copy(secret[:], key)
v := &Vault{
nonce: nonce,
secret: secret,
}
err = v.encrypt(make(map[string]*Credential))
if err != nil {
return nil, err
}
return v, nil
}
// Open reads a vault from the location provided to `filename` and decrypts
// it using `passphrase`. If decryption succeeds, new nonce is chosen and the
// vault is re-encrypted, ensuring nonces are unique and not reused across
// sessions.
func Open(filename string, passphrase string) (*Vault, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
var encryptedData bytes.Buffer
_, err = io.Copy(&encryptedData, f)
if err != nil {
return nil, err
}
var nonce [24]byte
copy(nonce[:], encryptedData.Bytes()[:24])
key, err := scrypt.Key([]byte(passphrase), nonce[:], scryptN, scryptR, scryptP, keyLen)
if err != nil {
return nil, err
}
var secret [32]byte
copy(secret[:], key)
vault := &Vault{
data: encryptedData.Bytes(),
nonce: nonce,
secret: secret,
}
creds, err := vault.decrypt()
if err != nil {
return nil, err
}
if _, err = io.ReadFull(rand.Reader, nonce[:]); err != nil {
panic(err)
}
key, err = scrypt.Key([]byte(passphrase), nonce[:], scryptN, scryptR, scryptP, keyLen)
if err != nil {
panic(err)
}
copy(secret[:], key)
vault.secret = secret
vault.nonce = nonce
if err = vault.encrypt(creds); err != nil {
return nil, err
}
return vault, nil
}
// Generate generates a new strong mnemonic passphrase and Add()s it to the
// vault.
func (v *Vault) Generate(location string, username string) error {
buf := new(bytes.Buffer)
_, err := io.CopyN(buf, rand.Reader, genEntropySize)
if err != nil {
panic(err)
}
phrase, err := mnemonics.ToPhrase(buf.Bytes(), mnemonics.English)
if err != nil {
return err
}
cred := Credential{
Username: username,
Password: phrase.String(),
}
err = v.Add(location, cred)
if err != nil {
return err
}
return nil
}
// decrypt decrypts the vault and returns the credential data as a map of
// strings (locations) to Credentials.
func (v *Vault) decrypt() (map[string]*Credential, error) {
decryptedData, success := secretbox.Open([]byte{}, v.data[len(v.nonce):], &v.nonce, &v.secret)
if !success {
return nil, ErrCouldNotDecrypt
}
credentials := make(map[string]*Credential)
err := gob.NewDecoder(bytes.NewBuffer(decryptedData)).Decode(&credentials)
if err != nil {
return nil, err
}
return credentials, nil
}
// encrypt encrypts the supplied credential map and updates the vault's
// encrypted data.
func (v *Vault) encrypt(creds map[string]*Credential) error {
var buf bytes.Buffer
err := gob.NewEncoder(&buf).Encode(creds)
if err != nil {
return err
}
v.data = secretbox.Seal(v.nonce[:], buf.Bytes(), &v.nonce, &v.secret)
return nil
}
// Add adds the credential provided to `credential` at the location provided
// by `location` to the vault.
func (v *Vault) Add(location string, credential Credential) error {
creds, err := v.decrypt()
if err != nil {
return err
}
if _, exists := creds[location]; exists {
return ErrCredentialExists
}
creds[location] = &credential
err = v.encrypt(creds)
if err != nil {
return err
}
return nil
}
// Get retrieves a Credential at the provided `location`.
func (v *Vault) Get(location string) (*Credential, error) {
creds, err := v.decrypt()
if err != nil {
return nil, err
}
cred, ok := creds[location]
if !ok {
return nil, ErrNoSuchCredential
}
return cred, nil
}
// Save safely (atomically) persists the vault to disk at the filename
// provided to `filename`.
func (v *Vault) Save(filename string) error {
tempfile, err := ioutil.TempFile(path.Dir(filename), "masterkey-temp")
if err != nil {
return err
}
_, err = io.Copy(tempfile, bytes.NewBuffer(v.data))
if err != nil {
return err
}
err = os.Rename(tempfile.Name(), filename)
if err != nil {
return err
}
return nil
}
// Edit replaces the credential at location with the provided `credential`.
func (v *Vault) Edit(location string, credential Credential) error {
creds, err := v.decrypt()
if err != nil {
return err
}
if _, ok := creds[location]; !ok {
return ErrNoSuchCredential
}
creds[location] = &credential
err = v.encrypt(creds)
if err != nil {
return err
}
return nil
}
// Locations retrieves the locations in the vault and returns them as a
// slice of strings.
func (v *Vault) Locations() ([]string, error) {
var locations []string
creds, err := v.decrypt()
if err != nil {
return locations, err
}
for location := range creds {
locations = append(locations, location)
}
return locations, nil
}
|
package main
func main() {
var y int
for x = 0; x < 10; x++ {
}
}
|
// Package ccaddrepo allows to add a GitHub repository to CodeClimate
// and setup its report id as a CC_TEST_REPORTER_ID secret in the repository.
//
// This two function works together in order to automate the setup of
// a GitHub repository.
//
// If you are using this package in GitHub Actions,
// you can easily publish coverages reports to CodeClimate
// using e.g. [paambaati/codeclimate-action](https://github.com/paambaati/codeclimate-action)
package ccaddrepo
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
)
const ccBaseURL = "https://api.codeclimate.com/v1/"
const ccGetURL = "https://api.codeclimate.com/v1/repos"
const ccURL = "https://api.codeclimate.com/v1/github/repos"
const ccBodyFormat = `{"data":{"type": "repos","attributes": {"url": "https://github.com/%s"}}}`
// CodeClimate represent an authenticated
// session on Code Climate.
type CodeClimate string
func (cc CodeClimate) doRequest(method string, URL string, body io.Reader, response interface{}) (string, error) {
req, err := http.NewRequest(method, ccBaseURL+URL, body)
if err != nil {
return "", err
}
req.Header.Add("Accept", "application/vnd.api+json")
req.Header.Add("Authorization", "Token token="+string(cc))
req.Header.Add("Content-Type", "application/vnd.api+json")
var c http.Client
res, err := c.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
resbuf, err := io.ReadAll(res.Body)
if err != nil {
return "", err
}
if response == nil {
return string(resbuf), nil
}
err = json.Unmarshal(resbuf, response)
if err != nil {
return "", err
}
return string(resbuf), nil
}
// GetRepoID returns the ID of a repository
func (cc CodeClimate) GetRepoID(reposlug string) (string, error) {
var response struct {
Data []struct {
ID string
}
}
rowdata, err := cc.doRequest("GET", "repos?github_slug="+reposlug, nil, &response)
if err != nil {
return "", err
}
if len(response.Data) == 0 {
return "", fmt.Errorf("repository not found: %s\nRESPONSE: %s", reposlug, rowdata)
}
data := response.Data[0]
return data.ID, nil
}
// DeleteRepo remove a repository from CodeClimate
func (cc CodeClimate) DeleteRepo(repoid string) error {
_, err := cc.doRequest("DELETE", "repos/"+repoid, nil, nil)
if err != nil {
return err
}
return nil
}
// GetOwnOrgID returns the ID of an organization
func (cc CodeClimate) GetOwnOrgID(orgname string) (string, error) {
var response struct {
Data []struct {
ID string
Attributes struct {
Name string
}
}
}
rowdata, err := cc.doRequest("GET", "orgs", nil, &response)
if err != nil {
return "", err
}
for _, data := range response.Data {
if data.Attributes.Name == orgname {
return data.ID, nil
}
}
return "", fmt.Errorf("org ID `%s` not found in response data\nRESPONSE:\n%v", orgname, rowdata)
}
// RepoInfo represents the information retrieved from a repo
type RepoInfo struct {
Data struct {
ID string
Attributes struct {
TestReporterID string `json:"test_reporter_id"`
BadgeTokenID string `json:"badge_token"`
}
}
}
// AddRepo create a repository within an organization
// and return the reporter ID.
func (cc CodeClimate) AddRepo(reposlug string) (*RepoInfo, error) {
var response RepoInfo
parts := strings.Split(reposlug, "/")
org := parts[0]
orgID, err := cc.GetOwnOrgID(org)
if err != nil {
return nil, err
}
URL := fmt.Sprintf("orgs/%s/repos", orgID)
var body bytes.Buffer
_, err = body.Write([]byte(fmt.Sprintf(ccBodyFormat, reposlug)))
if err != nil {
return nil, err
}
_, err = cc.doRequest("POST", URL, &body, &response)
if err != nil {
return nil, err
}
//fmt.Println(res)
return &response, nil
}
|
package main
import (
"io/ioutil"
"encoding/json"
"strconv"
)
type GameJSON struct {
Id int `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
HintAttempts int `json:"hint_attempts"`
Questions []struct {
Id int `json:"id"`
Name string `json:"name"`
Text string `json:"text"`
Image string `json:"image"`
Audio string `json:"audio"`
Answers []string `json:"answers"`
Hint string `json:"hint"`
Attempts int `json:"attempts"`
} `json:"questions"`
}
type GamesJSON []GameJSON
var GAMES GamesJSON = GamesJSON{}
var GAMES_MAP map[string] int = make(map[string] int)
func LoadGames() {
gamesFile, err := ioutil.ReadFile(conf.Bot.Resources.Games)
if err != nil {
panic("Not found games.json by path " + conf.Bot.Resources.Messages)
}
err = json.Unmarshal(gamesFile, &GAMES)
if err != nil {
panic("Cannot read games.json by path " + conf.Bot.Resources.Messages)
}
for i, game := range GAMES {
gameIdString := strconv.Itoa(game.Id)
GAMES_MAP[gameIdString] = i
}
}
func GetGame(gameId string) *GameJSON {
return &GAMES[GAMES_MAP[gameId]]
}
|
package library
import "fmt"
type nama_mahasiswa struct{
nama string
umur int
}
// Public
func Public(){
var m1 nama_mahasiswa
m1.nama = "Aldo"
m1.umur = 19
var m2 = nama_mahasiswa{"John Mayer", 26}
m1.tampil()
m2.tampil()
}
/* Private
func private(){
var m1 nama_mahasiswa
m1.nama = "Aldo"
m1.umur = 19
var m2 = nama_mahasiswa{"John Mayer", 26}
m1.tampil()
m2.tampil()
}
func Public(){
private()
}
*/
func (s nama_mahasiswa) tampil(){
fmt.Println("Nama Saya Adalah :" ,s.nama)
fmt.Println("Nama Saya Adalah :" ,s.umur)
fmt.Println("")
}
|
package main
import (
"flag"
"fmt"
"strings"
"github.com/ema/qdisc"
mp "github.com/mackerelio/go-mackerel-plugin"
)
type QdiscPlugin struct {
Prefix string
Interfaces []string
}
func (q QdiscPlugin) GraphDefinition() map[string]mp.Graphs {
return map[string]mp.Graphs{
"#": {
Label: "Qdisc data Summary",
Unit: "integer",
Metrics: []mp.Metrics{
{Name: "tx_bytes", Label: "tx_bytes", Diff: true},
{Name: "tx_packets", Label: "tx_packets", Diff: true},
{Name: "tx_drops", Label: "tx_drops", Diff: false},
{Name: "tx_overlimits", Label: "tx_overlimits", Diff: false},
{Name: "tx_requeues", Label: "tx_requeues", Diff: false},
{Name: "qlen", Label: "qlen", Diff: false},
{Name: "backlog", Label: "backlog", Diff: false},
},
},
}
}
func (q QdiscPlugin) FetchMetrics() (map[string]float64, error) {
info, err := qdisc.Get()
if err != nil {
return nil, err
}
metrics := map[string]float64{}
for _, msg := range info {
for _, i := range q.Interfaces {
if msg.IfaceName != i {
continue
}
metrics[i+".tx_bytes"] = float64(msg.Bytes)
metrics[i+".tx_packets"] = float64(msg.Packets)
metrics[i+".tx_drops"] = float64(msg.Drops)
metrics[i+".tx_overlimits"] = float64(msg.Overlimits)
metrics[i+".tx_requeues"] = float64(msg.Requeues)
metrics[i+".qlen"] = float64(msg.Qlen)
metrics[i+".backlog"] = float64(msg.Backlog)
}
}
if len(metrics) == 0 {
return nil, fmt.Errorf("interface is not found")
}
return metrics, nil
}
func (q QdiscPlugin) MetricKeyPrefix() string {
if q.Prefix == "" {
q.Prefix = "qdisc"
}
return q.Prefix
}
// main
func main() {
optPrefix := flag.String("metric-key-prefix", "qdisc", "Metric key prefix")
optTempfile := flag.String("tempfile", "", "Temp file name")
optInterface := flag.String("interface", "eth0", "network interface name")
flag.Parse()
interfaces := strings.Split(*optInterface, ",")
q := QdiscPlugin{
Prefix: *optPrefix,
Interfaces: interfaces,
}
plugin := mp.NewMackerelPlugin(q)
plugin.Tempfile = *optTempfile
plugin.Run()
}
|
package main
import (
"fmt"
"time"
"github.com/golang/glog"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
informers "k8s.io/client-go/informers/core/v1"
clientset "k8s.io/client-go/kubernetes"
listers "k8s.io/client-go/listers/core/v1"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/workqueue"
)
// Controller represents a controller used for binding pvcs to rook cephfs pvs
type Controller struct {
kubeClient clientset.Interface
pvcLister listers.PersistentVolumeClaimLister
pvcsSynced cache.InformerSynced
handler func(*v1.PersistentVolumeClaim) error
queue workqueue.RateLimitingInterface
}
// NewController creates a new rook cephfs provisioning controller
func NewController(
client clientset.Interface,
informer informers.PersistentVolumeClaimInformer,
handler func(*v1.PersistentVolumeClaim) error,
) *Controller {
cc := &Controller{
kubeClient: client,
queue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "pvc"),
handler: handler,
}
// Manage the addition/update of pvcs
informer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
pvc := obj.(*v1.PersistentVolumeClaim)
glog.V(4).Infof("Adding pvc %s", pvc.Name)
cc.enqueue(obj)
},
UpdateFunc: func(old, new interface{}) {
oldPVC := old.(*v1.PersistentVolumeClaim)
glog.V(4).Infof("Updating pvc %s", oldPVC.Name)
cc.enqueue(new)
},
DeleteFunc: func(obj interface{}) {
pvc, ok := obj.(*v1.PersistentVolumeClaim)
if !ok {
tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
if !ok {
glog.V(2).Infof("Couldn't get object from tombstone %#v", obj)
return
}
pvc, ok = tombstone.Obj.(*v1.PersistentVolumeClaim)
if !ok {
glog.V(2).Infof("Tombstone contained object that is not a pvc: %#v", obj)
return
}
}
glog.V(4).Infof("Deleting pvc %s", pvc.Name)
cc.enqueue(obj)
},
})
cc.pvcLister = informer.Lister()
cc.pvcsSynced = informer.Informer().HasSynced
return cc
}
// Run the controller workers.
func (cc *Controller) Run(workers int, stopCh <-chan struct{}) {
defer utilruntime.HandleCrash()
defer cc.queue.ShutDown()
glog.Infof("Starting pvc controller")
defer glog.Infof("Shutting down pvc controller")
if !cache.WaitForCacheSync(stopCh, cc.pvcsSynced) {
return
}
for i := 0; i < workers; i++ {
go wait.Until(cc.runWorker, time.Second, stopCh)
}
<-stopCh
}
func (cc *Controller) runWorker() {
for cc.processNextWorkItem() {
}
}
func (cc *Controller) processNextWorkItem() bool {
cKey, quit := cc.queue.Get()
if quit {
return false
}
defer cc.queue.Done(cKey)
if err := cc.sync(cKey.(string)); err != nil {
cc.queue.AddRateLimited(cKey)
utilruntime.HandleError(fmt.Errorf("Sync %v failed with : %v", cKey, err))
return true
}
cc.queue.Forget(cKey)
return true
}
func (cc *Controller) enqueue(obj interface{}) {
key, err := cache.MetaNamespaceKeyFunc(obj)
if err != nil {
utilruntime.HandleError(fmt.Errorf("Couldn't get key for object %+v: %v", obj, err))
return
}
cc.queue.Add(key)
}
func (cc *Controller) sync(key string) error {
startTime := time.Now()
namespace, name, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
utilruntime.HandleError(fmt.Errorf("invalid resource key: %s", key))
return nil
}
defer func() {
glog.V(4).Infof("Finished syncing pvc %q (%v)", key, time.Since(startTime))
}()
pvc, err := cc.pvcLister.PersistentVolumeClaims(namespace).Get(name)
if errors.IsNotFound(err) {
glog.V(3).Infof("pvc has been deleted: %v", key)
return nil
}
if err != nil {
return err
}
// need to operate on a copy so we don't mutate the pvc in the shared cache
pvc = pvc.DeepCopy()
err = cc.handler(pvc)
if err != nil {
return fmt.Errorf("couldn't sync pvc `%s` in namespace `%s`, see: %v", name, namespace, err)
}
return nil
}
|
package main
// import "fmt"
func main() {
// var colors map[string]string
color:=map[string]string{
"white":"ffff",
"Green":"ffff0",
"yellow":"dmat",
}
println(color)
delete(color,"yellow")
// delete(color,"white")
mapPrint(color)
}
func mapPrint(c map[string]string) {
for color, hex := range c {
println(color,hex)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.