text stringlengths 11 4.05M |
|---|
package govid
// Stores covid data about any country
type CountryData struct {
Country string `json:"country"`
Cases int `json:"cases"`
TodayCases int `json:"todayCases"`
Deaths int `json:"deaths"`
TodayDeaths int `json:"todayDeaths"`
Recovered int `json:"recovered"`
Active int `json:"active"`
Critical int `json:"critical"`
CasesPerOneMillion int `json:"casesPerOneMillion"`
DeathsPerOneMillion int `json:"deathsPerOneMillion"`
TotalTests int `json:"totalTests"`
TestsPerOneMillion int `json:"testsPerOneMillion"`
}
|
//
// June 2016, cisco
//
// Copyright (c) 2016 by cisco Systems, Inc.
// All rights reserved.
//
//
package main
import (
"github.com/dlintw/goconf"
"testing"
)
func TestMetricsInfluxConfigure(t *testing.T) {
var nc nodeConfig
var err error
nc.config, err = goconf.ReadConfigFile("pipeline_test.conf")
if err != nil {
t.Fatalf("Failed to read config [%v]", err)
}
//
// Now that a password is set, let's test the non-interactive
// negative and positive path.
name := "influxtest"
nc.config.AddOption(name, "influx", "")
_, err = metricsInfluxNew(name, nc)
if err == nil {
t.Fatalf("Test passed but should fail, empty influx")
}
nc.config.AddOption(name, "influx", "http://localhost:8086")
_, err = metricsInfluxNew(name, nc)
if err == nil {
t.Fatalf("Test passed but should fail, missing database")
}
nc.config.AddOption(name, "database", "mydatabase")
*pemFileName = "id_rsa_FOR_TEST_ONLY"
pw := "mysillysillysillypassword"
err, epw := encrypt_password(*pemFileName, []byte(pw))
nc.config.AddOption(name, "password", epw)
nc.config.AddOption(name, "username", "user")
_, err = metricsInfluxNew(name, nc)
if err != nil {
t.Fatalf("Test failed: %v", err)
}
}
|
package memorystorage
import (
"time"
storage "github.com/ezhk/golang-learning/hw12_13_14_15_calendar/internal/storage"
utils "github.com/ezhk/golang-learning/hw12_13_14_15_calendar/internal/utils"
)
type MemoryDatabase storage.MemoryDatabase
func NewDatatabase() storage.ClientInterface {
return &MemoryDatabase{
Events: make(map[int64]*storage.Event),
Users: make(map[int64]*storage.User),
EventsByUserID: make(map[int64][]*storage.Event),
UsersByEmail: make(map[string]*storage.User),
}
}
func (m *MemoryDatabase) Connect(_ string) error {
return nil
}
func (m *MemoryDatabase) Close() error {
return nil
}
func (m *MemoryDatabase) GetUserByEmail(email string) (storage.User, error) {
m.RLock()
userPtr, ok := m.UsersByEmail[email]
m.RUnlock()
if !ok {
return storage.User{}, storage.ErrUserDoesNotExist
}
return *userPtr, nil
}
func (m *MemoryDatabase) CreateUser(email string, firstName string, lastName string) (storage.User, error) {
existUser, err := m.GetUserByEmail(email)
if err == nil {
return existUser, storage.ErrUserExists
}
user := storage.User{
Email: email,
FirstName: firstName,
LastName: lastName,
}
m.Lock()
defer m.Unlock()
m.LatestUserID++
user.ID = m.LatestUserID
m.Users[user.ID] = &user
m.UsersByEmail[user.Email] = &user
return user, nil
}
func (m *MemoryDatabase) UpdateUser(user storage.User) error {
m.RLock()
userPointer, ok := m.Users[user.ID]
m.RUnlock()
if !ok {
return storage.ErrUserDoesNotExist
}
m.Lock()
defer m.Unlock()
delete(m.UsersByEmail, userPointer.Email)
m.UsersByEmail[user.Email] = &user
m.Users[user.ID] = &user
return nil
}
func (m *MemoryDatabase) DeleteUser(user storage.User) error {
m.RLock()
userPointer, ok := m.Users[user.ID]
m.RUnlock()
if !ok {
return storage.ErrUserDoesNotExist
}
m.Lock()
defer m.Unlock()
delete(m.UsersByEmail, userPointer.Email)
delete(m.Users, userPointer.ID)
return nil
}
func (m *MemoryDatabase) GetEventsByUserID(userID int64) ([]storage.Event, error) {
m.RLock()
defer m.RUnlock()
events, ok := m.EventsByUserID[userID]
if !ok {
return nil, storage.ErrEmptyEvents
}
selectedEvents := make([]storage.Event, 0)
for _, eventPointer := range events {
selectedEvents = append(selectedEvents, *eventPointer)
}
return selectedEvents, nil
}
func (m *MemoryDatabase) getEventsByDateRange(userID int64, fromDate, toDate time.Time) ([]storage.Event, error) {
m.RLock()
defer m.RUnlock()
events, ok := m.EventsByUserID[userID]
if !ok {
return nil, storage.ErrEmptyEvents
}
selectedEvents := make([]storage.Event, 0)
for _, eventPointer := range events {
if eventPointer.DateFrom.Before(toDate) && eventPointer.DateTo.After(fromDate) {
selectedEvents = append(selectedEvents, *eventPointer)
continue
}
}
return selectedEvents, nil
}
func (m *MemoryDatabase) CreateEvent(userID int64, title, content string, dateFrom, dateTo time.Time) (storage.Event, error) {
event := storage.Event{
UserID: userID,
Title: title,
Content: content,
DateFrom: dateFrom,
DateTo: dateTo,
}
m.Lock()
defer m.Unlock()
m.LatestRecordID++
event.ID = m.LatestRecordID
m.Events[event.ID] = &event
m.EventsByUserID[userID] = append(m.EventsByUserID[userID], &event)
return event, nil
}
func (m *MemoryDatabase) UpdateEvent(event storage.Event) error {
m.RLock()
eventPointer, ok := m.Events[event.ID]
m.RUnlock()
if !ok {
return storage.ErrEventDoesNotExist
}
m.Lock()
defer m.Unlock()
// Change attributes by exist pointer.
eventPointer.UserID = event.UserID
eventPointer.Title = event.Title
eventPointer.Content = event.Content
eventPointer.DateFrom = event.DateFrom
eventPointer.DateTo = event.DateTo
eventPointer.Notified = event.Notified
return nil
}
func (m *MemoryDatabase) DeleteEvent(event storage.Event) error {
m.RLock()
eventPointer, ok := m.Events[event.ID]
m.RUnlock()
if !ok {
return storage.ErrEventDoesNotExist
}
m.Lock()
defer m.Unlock()
for idx, pointers := range m.EventsByUserID[eventPointer.UserID] {
if pointers != eventPointer {
continue
}
m.EventsByUserID[eventPointer.UserID] = append(
m.EventsByUserID[eventPointer.UserID][:idx],
m.EventsByUserID[eventPointer.UserID][idx+1:]...,
)
break
}
delete(m.Events, event.ID)
return nil
}
func (m *MemoryDatabase) DailyEvents(userID int64, date time.Time) ([]storage.Event, error) {
fromDate := utils.StartDay(date)
toDate := utils.EndDay(date)
return m.getEventsByDateRange(userID, fromDate, toDate)
}
func (m *MemoryDatabase) WeeklyEvents(userID int64, date time.Time) ([]storage.Event, error) {
fromDate := utils.StartWeek(date)
toDate := utils.EndWeek(date)
return m.getEventsByDateRange(userID, fromDate, toDate)
}
func (m *MemoryDatabase) MonthlyEvents(userID int64, date time.Time) ([]storage.Event, error) {
fromDate := utils.StartMonth(date)
toDate := utils.EndMonth(date)
return m.getEventsByDateRange(userID, fromDate, toDate)
}
func (m *MemoryDatabase) GetNotifyReadyEvents() ([]storage.Event, error) {
m.RLock()
defer m.RUnlock()
twoWeekLeft := time.Now().Add(2 * time.Hour * 24 * 7)
selectedEvents := make([]storage.Event, 0)
for _, eventPointer := range m.Events {
if !eventPointer.Notified && eventPointer.DateFrom.Before(twoWeekLeft) {
selectedEvents = append(selectedEvents, *eventPointer)
}
}
return selectedEvents, nil
}
func (m *MemoryDatabase) MarkEventAsNotified(event *storage.Event) error {
m.RLock()
eventPointer, ok := m.Events[event.ID]
m.RUnlock()
if !ok {
return storage.ErrEventDoesNotExist
}
m.Lock()
defer m.Unlock()
// Back compatibility with SQL.
event.Notified = true
eventPointer.Notified = true
return nil
}
|
package lcache
import (
"errors"
"time"
)
type Params struct {
Loader Loader
MaximumEntries uint32
ExpireAfterWrite time.Duration
ExpireAfterRead time.Duration
GracefulRefresh bool
}
type Cache struct {
Params
entries map[string]*cacheEntry
refreshes chan string
}
func NewCache(params Params) (*Cache, error) {
var refreshes chan string
if params.MaximumEntries <= 0 {
params.MaximumEntries = 4096
}
if params.GracefulRefresh {
refreshes = make(chan string, 32)
}
ret := &Cache {
Params: params,
refreshes: refreshes,
}
if params.GracefulRefresh {
go RunRefresh(ret)
}
return ret, nil
}
func (this *Cache) Get(key string) (interface{}, error) {
now := time.Now()
// try to find a pre-existing entry
entry, exists := this.entries[key]
if exists {
// if we had an error last time refreshing, hand it back here, and delete the entry.
if entry.refreshError != nil {
delete(this.entries, key)
return entry.value, entry.refreshError
}
if entry.expiration.After(now) {
if this.refreshes == nil {
// refresh not available, remove.
delete(this.entries, key)
} else {
// if it's not already refreshing, queue it for refresh and prevent further queueing.
if !entry.refreshing {
entry.refreshing = true
this.refreshes <- key
}
}
}
// always return an entry from cache, even if we expired it by doing so.
return entry.value, entry.refreshError
}
// not found in cache, load.
value, err := this.Loader.Load(key)
if err != nil {
// error during loading, hand it back.
return 0, err
}
// insert.
entry = &cacheEntry{value: value}
entry.updateTimestamps(this.ExpireAfterWrite)
// make sure we never go over the cache size.
if uint32(len(this.entries)) >= this.MaximumEntries {
this.removeLRU()
}
this.entries[key] = entry
return value, nil
}
/*
goroutine.
Waits for cache entries to be flagged as expired, and reloads them using the Loader.
By default, every Cache starts one of these goroutines for themselves, only call again if you need multiple refreshers (it's safe).
*/
func RunRefresh(cache *Cache) error {
var entry *cacheEntry
if cache.refreshes == nil {
return errors.New("Cache was not created with graceful refresh enabled")
}
for key := range cache.refreshes {
value, err := cache.Get(key)
if err != nil {
entry.refreshError = err
continue
}
entry.value = value
entry.refreshing = false
entry.refreshError = nil
}
return nil
}
// Removes the least-recently-used entry.
func (this *Cache) removeLRU() {
var lruKey string
var lastUsed time.Time
for k, v := range this.entries {
if lastUsed.After(v.lastUsed) {
lruKey = k
}
}
delete(this.entries, lruKey)
}
// Stops all refreshing on this cache.
func (this *Cache) StopRefresh() {
close(this.refreshes)
} |
package main
import (
"encoding/json"
"fmt"
"os"
)
type responseOne struct {
Page int
Fruits []string
}
type responseTwo struct {
Page int `json:"page"`
Fruits []string `json:"fruits"`
}
func main() {
booleanB, _ := json.Marshal(true)
fmt.Println(string(booleanB))
integerB, _ := json.Marshal(1)
fmt.Println(string(integerB))
floatB, _ := json.Marshal(2.34)
fmt.Println(string(floatB))
stringB, _ := json.Marshal("gopher")
fmt.Println(string(stringB))
sliceD := []string{"apple", "peach", "pear"}
sliceB, _ := json.Marshal(sliceD)
fmt.Println(string(sliceB))
mapD := map[string]int{"apple": 5, "lettuce": 7}
mapB, _ := json.Marshal(mapD)
fmt.Println(string(mapB))
resOneD := &responseOne{
Page: 1,
Fruits: []string{"apple", "peach", "pear"}}
resOneB, _ := json.Marshal(resOneD)
fmt.Println(string(resOneB))
resTwoD := &responseTwo{
Page: 1,
Fruits: []string{"apple", "peach", "pear"}}
resTwoB, _ := json.Marshal(resTwoD)
fmt.Println(string(resTwoB))
byt := []byte(`{"num": 6.13, "strings": ["a", "b"]}`)
var dat map[string]interface{}
if err := json.Unmarshal(byt, &dat); err != nil {
panic(err)
}
fmt.Println(dat)
num := dat["num"].(float64)
fmt.Println(num)
strings := dat["strings"].([]interface{})
stringOne := strings[0].(string)
fmt.Println(stringOne)
fruits := `{"page": 1, "fruits": ["apple", "peach"]}`
response := responseTwo{}
json.Unmarshal([]byte(fruits), &response)
fmt.Println(response)
fmt.Println(response.Page)
fmt.Println(response.Fruits[0])
enc := json.NewEncoder(os.Stdout)
d := map[string]int{"apple": 5, "lettuce": 7}
enc.Encode(d)
}
|
package provider
import "strings"
func ensureLabel(labels string, key string, value string) string {
if key == "" {
return labels
}
if value == "" {
return labels
}
var split []string
if labels != "" {
split = strings.Split(labels, ",")
}
var found bool
for i, l := range split {
if !strings.HasPrefix(l, key+"=") {
continue
}
found = true
split[i] = key + "=" + value
}
if !found {
split = append(split, key+"="+value)
}
joined := strings.Join(split, ",")
return joined
}
|
// Copyright 2021 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package fingerprint
import "testing"
func TestRollbackStateEctoolUnmarshaler(t *testing.T) {
// Note that the following test string is not exactly what ectool would
// emit, since it contains tabs at the beginning of each line and includes
// a few extra newlines. These tabs and newlines are purely consmetic.
var out = []byte(`
Rollback block id: 19
Rollback min version: 0
RW rollback version: 255
`)
var rExpect = RollbackState{BlockID: 19, MinVersion: 0, RWVersion: 255}
var r RollbackState
if err := r.UnmarshalerEctool(out); err != nil {
t.Fatal("Failed to unmarshal: ", err)
}
if r != rExpect {
t.Fatalf("Unmarshaled rollback block %+v doesn't match expected block %+v.", r, rExpect)
}
}
func TestRollbackStateEctoolUnmarshalerError(t *testing.T) {
var out = []byte(`
Rollback block id: 19
Rollback min version: 0F
RW rollback version: 255
`)
var r RollbackState
if err := r.UnmarshalerEctool(out); err == nil {
t.Fatalf("Failed to detect error in rollback min version. Produced rollback block %+v.", r)
}
}
func TestParseColonDelimitedOutput(t *testing.T) {
const ectoolVersionOutput = `
f1: A B C
f2 : D E F
f3 : G : H : I
`
vals := parseColonDelimitedOutput(ectoolVersionOutput)
if keys := len(vals); keys != 3 {
t.Fatalf("Wrong number of keys. Expected 3, but received %d keys.", keys)
}
for k, v := range vals {
if v == "" {
t.Fatalf("Key %s had blank value.", k)
}
}
check := func(field, value string) {
v, ok := vals[field]
if !ok {
t.Fatal("Missing field '" + field + "'.")
}
if vals[field] != value {
t.Fatal("Field " + field + " contains invalid entry '" + v + "'.")
}
delete(vals, field)
}
check("f1", "A B C")
check("f2", "D E F")
check("f3", "G : H : I")
if len(vals) != 0 {
t.Fatal("Parsed extra values.")
}
}
func TestEctoolFlagsUnmarshaler(t *testing.T) {
var out = `0x00000c02`
var expect uint32 = 0xc02
actual, err := UnmarshalEctoolFlags(out)
if err != nil {
t.Fatal("Failed to unmarshal ectool flags: ", err)
}
if actual != expect {
t.Fatalf("Unmarshaled ectool flags %+v doesn't match expected flags %+v.", actual, expect)
}
}
func TestEctoolFlagsUnmarshalerLargerThanUint32(t *testing.T) {
var out = `0x100000c02`
_, err := UnmarshalEctoolFlags(out)
if err == nil {
t.Fatal("Expected parsing error for numbers larger than uint32")
}
}
|
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
package eventcollection
import (
rbacv1 "k8s.io/api/rbac/v1"
"github.com/DataDog/datadog-operator/controllers/datadogagent/common"
"github.com/DataDog/datadog-operator/pkg/kubernetes/rbac"
)
// getRBACRules generates the rbac rules required for EventCollection
func getRBACPolicyRules(tokenResourceName string) []rbacv1.PolicyRule {
rbacRules := []rbacv1.PolicyRule{
{
APIGroups: []string{rbac.CoreAPIGroup},
Resources: []string{rbac.ConfigMapsResource},
ResourceNames: []string{
common.DatadogTokenOldResourceName, // agent <7.37 token reource name
tokenResourceName,
},
Verbs: []string{rbac.GetVerb, rbac.UpdateVerb},
},
}
return rbacRules
}
// getLeaderElectionRBACPolicyRules generates the rbac rules required for leader election
func getLeaderElectionRBACPolicyRules(leaderElectionResourceName string) []rbacv1.PolicyRule {
rbacRules := []rbacv1.PolicyRule{
{
APIGroups: []string{rbac.CoreAPIGroup},
Resources: []string{rbac.ConfigMapsResource},
ResourceNames: []string{
common.DatadogLeaderElectionOldResourceName, // agent <7.37 leader election resource name
leaderElectionResourceName,
},
Verbs: []string{rbac.GetVerb, rbac.UpdateVerb},
},
{ // To create the leader election token
APIGroups: []string{rbac.CoreAPIGroup},
Resources: []string{rbac.ConfigMapsResource},
Verbs: []string{rbac.CreateVerb},
},
}
return rbacRules
}
|
// Copyright 2021 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package ui
import (
"context"
"fmt"
"time"
"chromiumos/tast/ctxutil"
"chromiumos/tast/errors"
"chromiumos/tast/local/bundles/cros/ui/notification"
uiperf "chromiumos/tast/local/bundles/cros/ui/perf"
"chromiumos/tast/local/chrome"
"chromiumos/tast/local/chrome/ash"
"chromiumos/tast/local/chrome/browser"
"chromiumos/tast/local/chrome/browser/browserfixt"
"chromiumos/tast/local/chrome/lacros/lacrosfixt"
"chromiumos/tast/local/chrome/uiauto"
"chromiumos/tast/local/chrome/uiauto/nodewith"
"chromiumos/tast/local/perfutil"
"chromiumos/tast/local/power"
"chromiumos/tast/testing"
"chromiumos/tast/testing/hwdep"
)
type notificationCloseTestType int
const (
clearOneAtATime notificationCloseTestType = iota // In test, clear notifications one at a time.
clearOneAtATimeWithARC // In test, clear notifications one at a time, with ARC notification.
clearAll // In test, clear all notifications at once.
clearAllWithARC // In test, clear all notifications at once, with ARC notification.
)
type notificationClearTestVal struct {
testType notificationCloseTestType
bt browser.Type
}
func init() {
testing.AddTest(&testing.Test{
Func: NotificationClosePerf,
LacrosStatus: testing.LacrosVariantExists,
Desc: "Measures animation performance of the clear all animation or individual notification deletion in the message center",
Contacts: []string{"newcomer@chromium.org", "cros-status-area-eng@google.com", "chromeos-wmp@google.com", "chromeos-sw-engprod@google.com"},
Attr: []string{"group:crosbolt", "crosbolt_perbuild"},
SoftwareDeps: []string{"chrome"},
HardwareDeps: hwdep.D(hwdep.InternalDisplay()),
Timeout: 10 * time.Minute,
Params: []testing.Param{{
Name: "one_at_a_time",
Val: notificationClearTestVal{clearOneAtATime, browser.TypeAsh},
}, {
Name: "one_at_a_time_arc",
ExtraSoftwareDeps: []string{"arc"},
Val: notificationClearTestVal{clearOneAtATimeWithARC, browser.TypeAsh},
}, {
Name: "clear_all",
Val: notificationClearTestVal{clearAll, browser.TypeAsh},
}, {
Name: "clear_all_arc",
ExtraSoftwareDeps: []string{"arc"},
Val: notificationClearTestVal{clearAllWithARC, browser.TypeAsh},
}, {
Name: "one_at_a_time_lacros",
ExtraSoftwareDeps: []string{"lacros"},
Val: notificationClearTestVal{clearOneAtATime, browser.TypeLacros},
}, {
Name: "one_at_a_time_arc_lacros",
ExtraSoftwareDeps: []string{"arc", "lacros"},
Val: notificationClearTestVal{clearOneAtATimeWithARC, browser.TypeLacros},
}, {
Name: "clear_all_lacros",
ExtraSoftwareDeps: []string{"lacros"},
Val: notificationClearTestVal{clearAll, browser.TypeLacros},
}, {
Name: "clear_all_arc_lacros",
ExtraSoftwareDeps: []string{"arc", "lacros"},
Val: notificationClearTestVal{clearAllWithARC, browser.TypeLacros},
}},
})
}
func NotificationClosePerf(ctx context.Context, s *testing.State) {
// Reserve a few seconds for various cleanup.
cleanupCtx := ctx
ctx, cancel := ctxutil.Shorten(ctx, 10*time.Second)
defer cancel()
testType := s.Param().(notificationClearTestVal).testType
shouldClearOneAtATime := testType == clearOneAtATime || testType == clearOneAtATimeWithARC
isArc := testType == clearOneAtATimeWithARC || testType == clearAllWithARC
// Ensure display on to record ui performance correctly.
if err := power.TurnOnDisplay(ctx); err != nil {
s.Fatal("Failed to turn on display: ", err)
}
var initArcOpt []chrome.Option
if isArc {
initArcOpt = []chrome.Option{chrome.ARCEnabled()}
}
bt := s.Param().(notificationClearTestVal).bt
cr, br, closeBrowser, err := browserfixt.SetUpWithNewChrome(ctx, bt, lacrosfixt.NewConfig(), initArcOpt...)
if err != nil {
s.Fatal("Failed to set up browser: ", err)
}
defer cr.Close(cleanupCtx)
defer closeBrowser(cleanupCtx)
atconn, err := cr.TestAPIConn(ctx)
if err != nil {
s.Fatal("Failed to connect to test API from ash: ", err)
}
btconn, err := br.TestAPIConn(ctx)
if err != nil {
s.Fatal("Failed to connect to test API from browser: ", err)
}
// Minimize opened windows (if exists) to reduce background noise during the measurement.
if err := ash.ForEachWindow(ctx, atconn, func(w *ash.Window) error {
return ash.SetWindowStateAndWait(ctx, atconn, w.ID, ash.WindowStateMinimized)
}); err != nil {
s.Fatal("Failed to set window states: ", err)
}
var arcclient *notification.ARCClient
if isArc {
// Note that ARC uses the test API from ash-chrome to manage notifications.
arcclient, err = notification.NewARCClient(ctx, atconn, cr, s.OutDir())
if err != nil {
s.Fatal("Failed to start ARCClient: ", err)
}
defer arcclient.Close(cleanupCtx, atconn)
}
automationController := uiauto.New(atconn)
statusArea := nodewith.ClassName("ash/StatusAreaWidgetDelegate")
collapseButton := nodewith.ClassName("CollapseButton")
// Ensure no notifications currently exist.
if err := ash.CloseNotifications(ctx, atconn); err != nil {
s.Fatal("Failed to clear all notifications prior to adding notifications")
}
var histogramName string
if shouldClearOneAtATime {
histogramName = "Ash.Notification.MoveDown.AnimationSmoothness"
} else {
histogramName = "Ash.Notification.ClearAllVisible.AnimationSmoothness"
}
const (
uiTimeout = 30 * time.Second
// Create 12 notifications, 3 groups of 4 types of notifications. This is
// enough to force notification overflow to happen.
n = 3
)
// Add some notifications so that notification centre shows up when opening
// Quick Settings.
notificationTypes := []browser.NotificationType{
browser.NotificationTypeBasic,
browser.NotificationTypeImage,
browser.NotificationTypeProgress,
browser.NotificationTypeList,
}
// Create 12 notifications (3 groups of 4 different notifications) with 3 ARC notifications if applicable,
// close them all via either the ClearAll button or one at a time, and record performance metrics.
// Note that ash-chrome (cr and atconn) is passed in to take traces and metrics from ash-chrome.
if err := perfutil.RunMultipleAndSave(ctx, s.OutDir(), cr.Browser(), uiperf.Run(s, perfutil.RunAndWaitAll(atconn, func(ctx context.Context) error {
ids := make([]string, n*len(notificationTypes))
for i := 0; i <= n-1; i++ {
for idx, t := range notificationTypes {
if id, err := browser.CreateTestNotification(ctx, btconn, t, fmt.Sprintf("Test%sNotification%d", t, i), "test message"); err != nil {
s.Fatalf("Failed to create %d-th %s notification: %v", i, t, err)
} else {
var index = i*len(notificationTypes) + idx
ids[index] = id
// Wait for each notification to post. This is faster than waiting for
// the final notification at the end, because sometimes posting 12
// notifications at once can result in a very long wait.
if _, err := ash.WaitForNotification(ctx, atconn, uiTimeout, ash.WaitTitle(fmt.Sprintf("Test%sNotification%d", t, i))); err != nil {
s.Fatal("Failed waiting for notification: ", err)
}
}
}
// Create an ARC notification.
if isArc {
if err := arcclient.CreateOrUpdateTestNotification(ctx, atconn, fmt.Sprintf("TestARCNotification%d", i), "test message", fmt.Sprintf("%d", i)); err != nil {
s.Fatalf("Failed to create %d-th ARC notification: %v", i, err)
}
}
}
// Open the uber tray, then collapse quick settings which results in an expanded MessageCenter.
if err := uiauto.Combine(
"open the uber tray, then collapse quick settings",
automationController.LeftClick(statusArea),
automationController.WaitUntilExists(collapseButton),
automationController.LeftClick(collapseButton),
automationController.WaitForLocation(collapseButton),
)(ctx); err != nil {
s.Fatal("Failed to open the uber tray and expand quick settings: ", err)
}
if err := testing.Poll(ctx, func(ctx context.Context) error {
// Wait a few seconds, otherwise all notifications will be added and
// removed very quickly.
// TODO(crbug/1236150): Replace Sleeps with WaitUntilIdle when implemented.
if err := testing.Sleep(ctx, 2*time.Second); err != nil {
return errors.Wrap(err, "failed to wait")
}
if shouldClearOneAtATime {
// Clear the notifications one at a time.
for i := len(ids) - 1; i >= 0; i-- {
if err := testing.Poll(ctx, func(ctx context.Context) error {
if err := browser.ClearNotification(ctx, btconn, ids[i]); err != nil {
return errors.Wrap(err, "failed to clear notification")
}
// Wait for stabilization / animation completion, otherwise all
// notification removals will happen unrealistically fast.
// TODO(crbug/1236150): Replace Sleeps with WaitUntilIdle when implemented.
if err := testing.Sleep(ctx, time.Second); err != nil {
return errors.Wrap(err, "failed to wait")
}
return nil
}, &testing.PollOptions{Timeout: uiTimeout}); err != nil {
return errors.Wrap(err, "failed to wait for clearing the notification")
}
}
if isArc {
// Clear ARC notifications.
for i := n - 1; i >= 0; i-- {
if err := testing.Poll(ctx, func(ctx context.Context) error {
if err := arcclient.RemoveNotification(ctx, atconn, fmt.Sprintf("%d", i)); err != nil {
return errors.Wrap(err, "failed to remove notification")
}
if err := testing.Sleep(ctx, time.Second); err != nil {
return errors.Wrap(err, "failed to wait")
}
return nil
}, &testing.PollOptions{Timeout: uiTimeout}); err != nil {
return errors.Wrap(err, "failed to wait for clearing the notification")
}
}
// While clearing ARC notification, we interact with the testing app and there's a chance that
// quick settings gets closed because it looses focus. If that's the case, reopen quick settings.
if err := automationController.Exists(collapseButton)(ctx); err != nil {
if err := uiauto.Combine(
"open the uber tray",
automationController.LeftClick(statusArea),
automationController.WaitUntilExists(collapseButton),
)(ctx); err != nil {
s.Fatal("Failed to open the uber tray: ", err)
}
}
}
} else {
// Clear all notifications at once via the ClearAll button.
if err := uiauto.Combine(
"click the ClearAll button to close all notifications",
automationController.LeftClick(nodewith.ClassName("StackingBarLabelButton")),
)(ctx); err != nil {
return errors.Wrap(err, "failed to collapse the uber tray")
}
// Wait a few seconds for notifications to stabilize.
// TODO(crbug/1236150): Replace Sleeps with WaitUntilIdle when implemented.
if err := testing.Sleep(ctx, 3*time.Second); err != nil {
return errors.Wrap(err, "failed to wait")
}
}
// Expand quick settings back to original state, then close uber tray.
if err := uiauto.Combine(
"expand quick settings, then close the uber tray",
automationController.LeftClick(collapseButton),
automationController.WaitForLocation(collapseButton),
automationController.LeftClick(statusArea),
automationController.WaitUntilGone(collapseButton),
)(ctx); err != nil {
s.Fatal("Failed to expand quick settings and close the uber tray: ", err)
}
return nil
}, &testing.PollOptions{Timeout: uiTimeout}); err != nil {
return errors.Wrap(err, "failed to wait for notification")
}
return nil
},
histogramName)),
perfutil.StoreAllWithHeuristics("")); err != nil {
s.Fatal("Failed to run or save: ", err)
}
}
|
package netutil
import (
"net"
"testing"
)
func TestIP4ToInt(t *testing.T) {
t.Parallel()
if IP4ToInt(net.ParseIP("0.0.1.0")) != 256 {
t.Error(`0.0.1.0 != 256`)
}
if IP4ToInt(net.ParseIP("0.0.1.1")) != 257 {
t.Error(`0.0.1.0 != 257`)
}
}
func TestIntToIP4(t *testing.T) {
t.Parallel()
if !IntToIP4(256).Equal(net.ParseIP("0.0.1.0")) {
t.Error(`256 != 0.0.1.0`)
}
if !IntToIP4(257).Equal(net.ParseIP("0.0.1.1")) {
t.Error(`257 != 0.0.1.0`)
}
}
func TestHostsFunc(t *testing.T) {
t.Parallel()
_, n, err := net.ParseCIDR("12.34.56.0/30")
if err != nil {
t.Fatal(err)
}
f, err := HostsFunc(n)
if err != nil {
t.Fatal(err)
}
if !f().Equal(net.ParseIP("12.34.56.1")) {
t.Error("f() != 12.34.56.1")
}
if !f().Equal(net.ParseIP("12.34.56.2")) {
t.Error("f() != 12.34.56.2")
}
if f() != nil {
t.Error("f() != nil")
}
}
|
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
//
package model
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestHeaders(t *testing.T) {
headerValue := "bar"
t.Run("value", func(t *testing.T) {
testCases := []struct {
input *Headers
value any
err bool
}{
{
input: &Headers{{
Key: "foo", Value: &headerValue,
}},
value: []byte(`[{"key":"foo","value":"bar"}]`),
err: false,
},
{
input: &Headers{},
value: []byte(`[]`),
err: false,
},
}
for _, test := range testCases {
value, err := test.input.Value()
require.Equal(t, test.value, value)
if test.err {
require.Error(t, err)
} else {
require.NoError(t, err)
}
}
})
t.Run("scan", func(t *testing.T) {
testCases := []struct {
input any
scan Headers
err bool
}{
{
input: []byte(`[{"key":"foo", "value": "bar"}]`),
scan: Headers{{
Key: "foo", Value: &headerValue,
}},
err: false,
},
{
input: nil,
scan: Headers{},
err: false,
},
}
for _, test := range testCases {
headers := Headers{}
err := headers.Scan(test.input)
require.Equal(t, test.scan, headers)
if test.err {
require.Error(t, err)
} else {
require.NoError(t, err)
}
}
})
}
|
package server
import (
"github.com/gorilla/websocket"
"github.com/qaisjp/studenthackv-go-gameserver/game"
"log"
"net/http"
)
type Server struct {
Options *Options
Games []*game.Game
newGameChan (chan *game.Game)
}
func NewServer(options *Options) *Server {
return &Server{
Options: options,
}
}
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
}
func (s *Server) servePlayer(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
game.NewPlayer(s.Games[0], conn)
}
func (s *Server) Run() {
// Prepare the server game list
s.Games = []*game.Game{}
s.newGameChan = make(chan *game.Game)
// Start processing games
go processGames(s)
// Test game
s.newGameChan <- game.NewGame()
http.HandleFunc("/game/0/ws", s.servePlayer)
log.Println("Server hosted at " + s.Options.Address)
err := http.ListenAndServe(s.Options.Address, nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
func (s *Server) Exit() {
}
func processGames(s *Server) {
for {
// Add to the games list and process ticks
g := <-s.newGameChan
s.Games = append(s.Games, g)
go g.Run()
}
}
|
package wxapi
//请求微信网页授权access_token 返回值
type AuthResp struct {
Access_token string
Expires_in string
Refresh_token string
Openid string
Scope string
}
type BaseResp struct {
Errcode string
Errmsg string
*JsonResponse
}
//网页授权返回用户结构体
type AuthuserResp struct {
Openid string //用户的唯一标识
Nickname string //用户昵称
Sex int //用户的性别,值为1时是男性,值为2时是女性,值为0时是未知
Province string //用户个人资料填写的省份
City string //普通用户个人资料填写的城市
Country string //国家,如中国为CN
Headimgurl string //用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空。若用户更换头像,原有头像URL将失效
Privilege []string //用户特权信息,json 数组,
Unionid string //只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段
*BaseResp
}
type TicketReso struct {
ticket string
expire_seconds string
url string
}
type QueryMaterialistlResp struct {
Total_count int
Item_count int
Item []Materia
*BaseResp
}
type Materia struct {
title string//图文消息的标题
thumb_media_id string//图文消息的封面图片素材id(必须是永久mediaID)
show_cover_pic string//是否显示封面,0为false,即不显示,1为true,即显示
author string//作者
digest string//图文消息的摘要,仅有单图文消息才有摘要,多图文此处为空
content string//图文消息的具体内容,支持HTML标签,必须少于2万字符,小于1M,且此处会去除JS
url string//图文页的URL,或者,当获取的列表是图片素材列表时,该字段是图片的URL
content_source_url string//图文消息的原文地址,即点击“阅读原文”后的URL
update_time string//这篇图文消息素材的最后更新时间
name string//文件名称
}
//素材请求todo
type ArticleReq struct {
}
// JSSDKSignature JSSDK 签名对象
type JSSDKSignature struct {
AppID, Noncestr, Sign string
Timestamp int64
} |
package twosum
import (
"reflect"
"testing"
)
func TestTwoSum(t *testing.T) {
tests := []struct {
in1 []int
in2 int
want []int
}{
{
in1: []int{2, 7, 11, 15},
in2: 9,
want: []int{1, 2},
},
{
in1: []int{2, 7, 11, 15},
in2: 17,
want: []int{1, 4},
},
{
in1: []int{2, 7, 11, 15},
in2: 26,
want: []int{3, 4},
},
{
in1: []int{2, 7},
in2: 9,
want: []int{1, 2},
},
{
in1: []int{1, 2, 3, 5, 8, 13, 21, 34, 55},
in2: 39,
want: []int{4, 8},
},
{
in1: []int{1, 2, 3, 5, 8, 13, 21, 34, 55},
in2: 60,
want: []int{4, 9},
},
}
for _, test := range tests {
got := twoSum(test.in1, test.in2)
if !reflect.DeepEqual(got, test.want) {
t.Errorf("twoSum(%v,%d)=%v, want %v", test.in1, test.in2, got, test.want)
}
}
}
|
package api_tweet_controller
import (
"context"
"encoding/json"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"log"
awsCommon "mytweet/middlewares/aws"
"mytweet/middlewares/crypto"
"mytweet/models/tweet"
"mytweet/models/user"
"net/http"
"strconv"
"time"
)
type Controller struct{}
func (pc Controller) CreateUser(c *gin.Context) {
log.Println("CreateUser")
var body user.User
// バリデーション処理
if err := c.ShouldBindJSON(&body); err != nil {
c.HTML(http.StatusInternalServerError, "signup.html", gin.H{"err": err})
return
} else {
username := body.Username
password := body.Password
// 登録ユーザーが重複していた場合にはじく処理
if err := user.CreateUser(username, password); err != nil {
c.HTML(http.StatusBadRequest, "signup.html", gin.H{"err": err})
}
c.JSON(http.StatusOK, gin.H{"status": "you are signup"})
}
}
func (pc Controller) Login(c *gin.Context) {
log.Println("Login")
var body user.User
if err := c.ShouldBindJSON(&body); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "Abort"})
panic("ログインできませんでした")
}
// リクエストから取得したユーザー名、パスワード
username := body.Username
password := body.Password
// DBから取得したユーザーパスワード(Hash)
dbPassword := user.GetUser(username).Password
// ユーザーパスワードの比較
if err := crypto.CompareHashAndPassword(dbPassword, password); err != nil {
log.Println("ログインできませんでした")
c.JSON(http.StatusBadRequest, gin.H{"status": "Abort"})
return
} else {
log.Println("ログインできました")
cfg, err := awsCommon.GetAwsCredential()
if err != nil {
log.Fatalf("unable to load SDK config, %v", err)
}
// Using the Config value, create the DynamoDB client
svc := dynamodb.NewFromConfig(cfg)
uuid, err := uuid.NewRandom()
fmt.Println("new uuid:" + uuid.String())
// 現在時刻+1時間後
now := time.Now().Add(1 * time.Hour).Unix()
n := strconv.FormatInt(now, 10)
fmt.Println("new expires:" + n)
output, err := svc.PutItem(context.TODO(), &dynamodb.PutItemInput{
TableName: aws.String("sessions"),
Item: map[string]types.AttributeValue{
"id": &types.AttributeValueMemberS{Value: uuid.String()},
"data": &types.AttributeValueMemberM{Value: map[string]types.AttributeValue{
"username": &types.AttributeValueMemberS{Value: username},
"login": &types.AttributeValueMemberBOOL{Value: true},
}},
"expires": &types.AttributeValueMemberN{Value: n},
},
})
if err != nil {
log.Fatalf("failed to PutItem, %v", err)
return
}
jsonE, _ := json.Marshal(output)
fmt.Println(string(jsonE))
c.SetSameSite(http.SameSiteNoneMode)
c.SetCookie("uuid", uuid.String(), 60000, "/", c.Request.URL.Hostname(), true, true)
c.SetCookie("username", username, 60000, "/", c.Request.URL.Hostname(), true, true)
c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
}
}
func (pc Controller) Index(c *gin.Context) {
tweets := tweet.GetAll()
sessions, _ := c.Get("sessions")
c.JSON(http.StatusOK, gin.H{"tweets": tweets, "sessions": sessions})
}
func (pc Controller) New(c *gin.Context) {
var body tweet.Tweet
// ここがバリデーション部分
if err := c.Bind(&body); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"err": err})
} else {
content := body.Content
tweet.Insert(content)
c.JSON(http.StatusOK, gin.H{"status": "New"})
}
}
func (pc Controller) Detail(c *gin.Context) {
n := c.Param("id")
id, err := strconv.Atoi(n)
if err != nil {
panic(err)
}
tweet := tweet.GetOne(id)
c.JSON(http.StatusOK, gin.H{"tweet": tweet})
}
func (pc Controller) Update(c *gin.Context) {
var body tweet.Tweet
n := c.Param("id")
id, err := strconv.Atoi(n)
if err != nil {
panic("ERROR")
}
if err := c.Bind(&body); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"err": err})
} else {
postTweet := body.Content
tweet.Update(id, postTweet)
c.JSON(http.StatusOK, gin.H{"status": "update"})
}
}
func (pc Controller) Delete(c *gin.Context) {
n := c.Param("id")
id, err := strconv.Atoi(n)
if err != nil {
panic("ERROR")
}
tweet.Delete(id)
c.JSON(http.StatusOK, gin.H{"status": "delete"})
}
|
// create a file
package main
import (
"fmt"
"os"
)
// create a file
func proverbs(name string) error {
f, err := os.Create(name)
if err != nil {
return err
}
// from here the file is opened, now we can write in the file
// close the file
_, err = fmt.Fprintln(f, "Errors are values.")
// here we checking for any err otherwise will add the next line below
if err != nil {
f.Close()
return err
}
_, err = fmt.Fprintln(f, "Don't just check errors, handle them gracefully")
f.Close()
return err
}
func main() {
err := proverbs("proverbs.txt")
if err != nil {
fmt.Println(err)
}
}
// creates a new file everytime - proverbs.txt and will add 2 lines and will close the file
|
package imagemap
import (
"context"
"fmt"
"k8s.io/apimachinery/pkg/types"
apierrors "k8s.io/apimachinery/pkg/api/errors"
ctrlclient "sigs.k8s.io/controller-runtime/pkg/client"
"github.com/tilt-dev/tilt/pkg/apis/core/v1alpha1"
"github.com/tilt-dev/tilt/pkg/model"
)
// Inject completed ImageMaps into the environment of a local process that
// wants to deploy to a cluster.
//
// Current env vars:
// TILT_IMAGE_i - The reference to the image #i from the point of view of the cluster container runtime.
// TILT_IMAGE_MAP_i - The name of the image map #i with the current status of the image.
//
// where an env may depend on arbitrarily many image maps.
func InjectIntoDeployEnv(cmd *model.Cmd, imageMapNames []string, imageMaps map[types.NamespacedName]*v1alpha1.ImageMap) error {
for i, imageMapName := range imageMapNames {
imageMap, ok := imageMaps[types.NamespacedName{Name: imageMapName}]
if !ok {
return fmt.Errorf("internal error: missing imagemap %s", imageMapName)
}
cmd.Env = append(cmd.Env, fmt.Sprintf("TILT_IMAGE_MAP_%d=%s", i, imageMapName))
cmd.Env = append(cmd.Env, fmt.Sprintf("TILT_IMAGE_%d=%s", i, imageMap.Status.ImageFromCluster))
}
return nil
}
// Inject completed ImageMaps into the environment of a local process that
// wants to build images locally.
//
// Current env vars:
// TILT_IMAGE_i - The reference to the image #i from the point of view of the local host.
// TILT_IMAGE_MAP_i - The name of the image map #i with the current status of the image.
//
// where an env may depend on arbitrarily many image maps.
func InjectIntoLocalEnv(cmd *v1alpha1.Cmd, imageMapNames []string, imageMaps map[types.NamespacedName]*v1alpha1.ImageMap) (*v1alpha1.Cmd, error) {
cmd = cmd.DeepCopy()
for i, imageMapName := range imageMapNames {
imageMap, ok := imageMaps[types.NamespacedName{Name: imageMapName}]
if !ok {
return nil, fmt.Errorf("internal error: missing imagemap %s", imageMapName)
}
cmd.Spec.Env = append(cmd.Spec.Env, fmt.Sprintf("TILT_IMAGE_MAP_%d=%s", i, imageMapName))
cmd.Spec.Env = append(cmd.Spec.Env, fmt.Sprintf("TILT_IMAGE_%d=%s", i, imageMap.Status.ImageFromLocal))
}
return cmd, nil
}
// Populate a map with all the given imagemaps, skipping any that don't exist
func NamesToObjects(ctx context.Context, client ctrlclient.Client, names []string) (map[types.NamespacedName]*v1alpha1.ImageMap, error) {
imageMaps := make(map[types.NamespacedName]*v1alpha1.ImageMap)
for _, name := range names {
var im v1alpha1.ImageMap
nn := types.NamespacedName{Name: name}
err := client.Get(ctx, nn, &im)
if err != nil {
if apierrors.IsNotFound(err) {
// If the map isn't found, keep going
continue
}
return nil, err
}
imageMaps[nn] = &im
}
return imageMaps, nil
}
|
package dockplugin
import (
"fmt"
"github.com/contiv/netplugin/core"
"github.com/contiv/netplugin/netmaster/docknet"
"github.com/contiv/netplugin/netmaster/mastercfg"
"github.com/contiv/netplugin/state"
"github.com/contiv/netplugin/utils"
"testing"
)
var stateDriver *state.FakeStateDriver
// initStateDriver initialize etcd state driver
func initFakeStateDriver(t *testing.T) {
instInfo := core.InstanceInfo{}
d, err := utils.NewStateDriver("fakedriver", &instInfo)
if err != nil {
t.Fatalf("failed to init statedriver. Error: %s", err)
t.Fail()
}
stateDriver = d.(*state.FakeStateDriver)
}
func deinitStateDriver() {
utils.ReleaseStateDriver()
}
// Ensure deleteNetworkHelper can delete docker network without issue
func TestCreateAndDeleteNetwork(t *testing.T) {
// Update plugin driver for unit test
docknet.UpdateDockerV2PluginName("bridge", "default")
initFakeStateDriver(t)
defer deinitStateDriver()
tenantName := "t1"
networkName := "net1"
serviceName := ""
nwcfg := mastercfg.CfgNetworkState{
Tenant: tenantName,
NetworkName: networkName,
PktTagType: "vlan",
PktTag: 1,
ExtPktTag: 1,
SubnetIP: "10.0.0.0",
SubnetLen: 24,
Gateway: "10.0.0.1",
}
err := docknet.CreateDockNet(tenantName, networkName, "", &nwcfg)
if err != nil {
t.Fatalf("Error creating docker network. Error: %v", err)
t.Fail()
}
// Get Docker network UUID
dnetOper := docknet.DnetOperState{}
dnetOper.StateDriver = stateDriver
err = dnetOper.Read(fmt.Sprintf("%s.%s.%s", tenantName, networkName, serviceName))
if err != nil {
t.Fatalf("Unable to read network state. Error: %v", err)
t.Fail()
}
testData := make([]byte, 3)
networkID := mastercfg.StateConfigPath + "nets/" + dnetOper.DocknetUUID + ".default"
dnetOper.StateDriver.Write(networkID, testData)
// Delete Docker network by using helper
err = deleteNetworkHelper(dnetOper.DocknetUUID)
if err != nil {
t.Fatalf("Unable to delete docker network. Error: %v", err)
t.Fail()
}
// ensure network is not in the oper state
err = dnetOper.Read(fmt.Sprintf("%s.%s.%s", tenantName, networkName, serviceName))
if err == nil {
t.Fatalf("Fail to delete docket network")
t.Fail()
}
}
|
package main
import "fmt"
func main() {
var x int
var y int
fmt.Println("Digite um numero para dividi-lo: ")
fmt.Scanf("%d", &x)
fmt.Println("digite o divisor: ")
fmt.Scanf("%d", &y)
z := x % y
fmt.Println("o remainder e: ", z)
}
|
package handlers
import (
"github.com/credo-science/credo-metadata-server/event"
"log"
"net/http"
"github.com/gin-gonic/gin"
"github.com/credo-science/credo-metadata-server/db"
)
func GetPing(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"msg": "pong"})
}
func GetEventAll(c *gin.Context) {
eventType, ok := event.StringToId(c.Params.ByName("event_type"))
if !ok {
c.JSON(http.StatusBadRequest, gin.H{"message": "Invalid event type."})
return
}
eventId := c.Params.ByName("event_id")
metadata, err := db.GetEventMetadata(eventType, eventId)
if err != nil {
if err == db.ErrNotFound {
c.JSON(http.StatusNotFound, gin.H{"message": "Event not found."})
return
} else {
c.JSON(http.StatusInternalServerError, gin.H{"message": "Could not fetch event metadata from database."})
log.Fatal(err)
return
}
}
c.JSON(http.StatusOK, metadata)
}
func PutEventAll(c *gin.Context) {
eventType, ok := event.StringToId(c.Params.ByName("event_type"))
if !ok {
c.JSON(http.StatusBadRequest, gin.H{"message": "Invalid event type."})
return
}
eventId := c.Params.ByName("event_id")
metadata := event.Metadata{}
err := c.BindJSON(&metadata)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"message": "Invalid metadata object."})
return
}
err = db.SetEventMetadata(eventType, eventId, metadata)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "Could not update event metadata."})
log.Panic(err)
return
}
c.JSON(http.StatusOK, gin.H{"message": "Metadata updated."})
}
|
package openrtb_ext
import "encoding/json"
// ExtImpPubmatic defines the contract for bidrequest.imp[i].ext.prebid.bidder.pubmatic
// PublisherId is mandatory parameters, others are optional parameters
// AdSlot is identifier for specific ad placement or ad tag
// Keywords is bid specific parameter,
// WrapExt needs to be sent once per bid request
type ExtImpPubmatic struct {
PublisherId string `json:"publisherId"`
AdSlot string `json:"adSlot"`
Dctr string `json:"dctr"`
PmZoneID string `json:"pmzoneid"`
WrapExt json.RawMessage `json:"wrapper,omitempty"`
Keywords []*ExtImpPubmaticKeyVal `json:"keywords,omitempty"`
Kadfloor string `json:"kadfloor,omitempty"`
}
// ExtImpPubmaticKeyVal defines the contract for bidrequest.imp[i].ext.prebid.bidder.pubmatic.keywords[i]
type ExtImpPubmaticKeyVal struct {
Key string `json:"key,omitempty"`
Values []string `json:"value,omitempty"`
}
|
package events
// Event dispatch event
type Event string
// Events
const (
Unknown Event = ""
Confirmed Event = "confirmed"
Login Event = "login"
Logout Event = "logout"
Signup Event = "signup"
All Event = "all" // must be last
)
|
package main
import (
"fmt"
"testing"
)
func TestGetvalueFizz(t *testing.T) {
fb := FizzBuzz{3, 100}
actual := fb.GetValue()
expected := "Fizz"
if actual != expected {
t.Errorf("got: %v\nwant: %v", actual, expected)
}
}
func TestGetvalueBuzz(t *testing.T) {
fb := FizzBuzz{5, 100}
actual := fb.GetValue()
expected := "Buzz"
if actual != expected {
t.Errorf("got: %v\nwant: %v", actual, expected)
}
}
func TestGetvalueFizzBuzz(t *testing.T) {
fb := FizzBuzz{15, 100}
actual := fb.GetValue()
expected := "FizzBuzz"
if actual != expected {
t.Errorf("got: %v\nwant: %v", actual, expected)
}
}
func TestGetvalueCur(t *testing.T) {
fb := FizzBuzz{31, 100}
actual := fb.GetValue()
expected := fmt.Sprint(fb.Cur)
if actual != expected {
t.Errorf("got: %v\nwant: %v", actual, expected)
}
}
|
package models
import (
"github.com/astaxie/beego"
)
func init() {
// beego.AppConfigPath = ""
// beego.AppConfig("ini", "/opt/local/go/src/edwardhey.com/football/wx/conf/app.conf")
beego.AppConfigPath = "../conf/app.conf"
beego.ParseConfig()
// fmt.Println(beego.AppConfig.String("appname"))
InitManual()
}
|
package service
import (
"bytes"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/xml"
"fmt"
"html/template"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
log "github.com/Sirupsen/logrus"
"github.com/crewjam/saml"
"github.com/dgrijalva/jwt-go"
"github.com/rancher/go-rancher/api"
"github.com/rancher/go-rancher/v2"
"github.com/rancher/rancher-auth-service/model"
"github.com/rancher/rancher-auth-service/server"
)
const (
redirectBackBase = "redirectBackBase"
redirectBackPath = "redirectBackPath"
postSamlTokenHTML = "/v1-auth/saml/tokenhtml"
tpl = `
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function() {
document.getElementById('TokenHTMLResponseForm').submit();
}
</script>
</head>
<body>
<form method="post" action="{{.URL}}" id="TokenHTMLResponseForm">
<input type="hidden" name="token" value="{{.Token}}" />
<input type="hidden" name="finalRedirectURL" value="{{.FinalRedirectURL}}" />
<input type="hidden" name="secure" value="{{.Secure}}" />
</form>
</body>
</html>`
)
//CreateToken is a handler for route /token and returns the jwt token after authenticating the user
func CreateToken(w http.ResponseWriter, r *http.Request) {
bytes, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Errorf("GetToken failed with error: %v", err)
}
var jsonInput map[string]string
err = json.Unmarshal(bytes, &jsonInput)
if err != nil {
log.Errorf("unmarshal failed with error: %v", err)
}
securityCode := jsonInput["code"]
accessToken := jsonInput["accessToken"]
if securityCode != "" {
log.Debugf("CreateToken called with securityCode")
//getToken
token, status, err := server.CreateToken(jsonInput)
if err != nil {
log.Errorf("GetToken failed with error: %v", err)
if status == 0 {
status = http.StatusInternalServerError
}
ReturnHTTPError(w, r, status, fmt.Sprintf("%v", err))
return
}
api.GetApiContext(r).Write(&token)
} else if accessToken != "" {
log.Debugf("RefreshToken called with accessToken %s", accessToken)
//getToken
token, status, err := server.RefreshToken(jsonInput)
if err != nil {
log.Errorf("GetToken failed with error: %v", err)
if status == 0 {
status = http.StatusInternalServerError
}
ReturnHTTPError(w, r, status, fmt.Sprintf("%v", err))
return
}
api.GetApiContext(r).Write(&token)
} else {
ReturnHTTPError(w, r, http.StatusBadRequest, "Bad Request, Please check the request content")
return
}
}
//GetIdentities is a handler for route /me/identities and returns group memberships and details of the user
func GetIdentities(w http.ResponseWriter, r *http.Request) {
apiContext := api.GetApiContext(r)
authHeader := r.Header.Get("Authorization")
if authHeader != "" {
// header value format will be "Bearer <token>"
if !strings.HasPrefix(authHeader, "Bearer ") {
log.Debugf("GetMyIdentities Failed to find Bearer token %v", authHeader)
ReturnHTTPError(w, r, http.StatusUnauthorized, "Unauthorized, please provide a valid token")
return
}
accessToken := strings.TrimPrefix(authHeader, "Bearer ")
identities, err := server.GetIdentities(accessToken)
if err == nil {
resp := client.IdentityCollection{}
resp.Data = identities
apiContext.Write(&resp)
} else {
//failed to get the user identities
log.Debugf("GetIdentities Failed with error %v", err)
ReturnHTTPError(w, r, http.StatusUnauthorized, "Unauthorized, failed to get identities")
return
}
} else {
log.Debug("No Authorization header found")
ReturnHTTPError(w, r, http.StatusUnauthorized, "Unauthorized, please provide a valid token")
return
}
}
//SearchIdentities is a handler for route /identities and filters (id + type or name) and returns the search results using the passed filters
func SearchIdentities(w http.ResponseWriter, r *http.Request) {
apiContext := api.GetApiContext(r)
authHeader := r.Header.Get("Authorization")
if authHeader != "" {
// header value format will be "Bearer <token>"
if !strings.HasPrefix(authHeader, "Bearer") {
log.Debugf("GetMyIdentities Failed to find Bearer token %v", authHeader)
ReturnHTTPError(w, r, http.StatusUnauthorized, "Unauthorized, please provide a valid token")
return
}
accessToken := strings.TrimPrefix(authHeader, "Bearer")
accessToken = strings.TrimSpace(accessToken)
//see which filters are passed, if none then error 400
externalID := r.URL.Query().Get("externalId")
externalIDType := r.URL.Query().Get("externalIdType")
name := r.URL.Query().Get("name")
if externalID != "" && externalIDType != "" {
log.Debugf("SearchIdentities by externalID: %v and externalIDType: %v", externalID, externalIDType)
//search by id and type
identity, err := server.GetIdentity(externalID, externalIDType, accessToken)
if err == nil {
log.Debugf("Found identity %v", identity)
apiContext.Write(&identity)
} else {
//failed to search the identities
log.Errorf("SearchIdentities Failed with error %v", err)
ReturnHTTPError(w, r, http.StatusInternalServerError, "Internal Server Error")
return
}
} else if name != "" {
log.Debugf("SearchIdentities by name: %v", name)
//Must call ldap SearchIdentities with exactMatch=true
identities, err := server.SearchIdentities(name, true, accessToken)
log.Debugf("Found identities %v", identities)
if err == nil {
resp := client.IdentityCollection{}
resp.Data = identities
apiContext.Write(&resp)
} else {
//failed to search the identities
log.Errorf("SearchIdentities Failed with error %v", err)
ReturnHTTPError(w, r, http.StatusInternalServerError, "Internal Server Error")
return
}
} else {
ReturnHTTPError(w, r, http.StatusBadRequest, "Bad Request, Please check the request content")
return
}
} else {
log.Debug("No Authorization header found")
ReturnHTTPError(w, r, http.StatusUnauthorized, "Unauthorized, please provide a valid token")
return
}
}
//UpdateConfig is a handler for POST /config, loads the provider with the config and saves the config back to Cattle database
func UpdateConfig(w http.ResponseWriter, r *http.Request) {
apiContext := api.GetApiContext(r)
bytes, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Errorf("UpdateConfig failed with error: %v", err)
ReturnHTTPError(w, r, http.StatusBadRequest, "Bad Request, Please check the request content")
return
}
var authConfig model.AuthConfig
err = json.Unmarshal(bytes, &authConfig)
if err != nil {
log.Errorf("UpdateConfig unmarshal failed with error: %v", err)
ReturnHTTPError(w, r, http.StatusBadRequest, "Bad Request, Please check the request content")
return
}
if authConfig.Provider == "" {
log.Errorf("UpdateConfig: Provider is a required field")
ReturnHTTPError(w, r, http.StatusBadRequest, "Bad Request, Please check the request content, Provider is a required field")
return
}
err = server.UpdateConfig(authConfig)
if err != nil {
log.Errorf("UpdateConfig failed with error: %v", err)
ReturnHTTPError(w, r, http.StatusBadRequest, "Bad Request, Please check the request content")
return
}
log.Debugf("Updated config, listing the config back")
//list the config and return in response
config, err := server.GetConfig("", true)
if err == nil {
apiContext.Write(&config)
} else {
//failed to get the config
log.Debugf("GetConfig failed with error %v", err)
ReturnHTTPError(w, r, http.StatusInternalServerError, "Failed to list the config")
return
}
}
//GetConfig is a handler for GET /config, lists the provider config
func GetConfig(w http.ResponseWriter, r *http.Request) {
apiContext := api.GetApiContext(r)
authHeader := r.Header.Get("Authorization")
var accessToken string
// header value format will be "Bearer <token>"
if authHeader != "" {
if !strings.HasPrefix(authHeader, "Bearer ") {
log.Errorf("GetMyIdentities Failed to find Bearer token %v", authHeader)
ReturnHTTPError(w, r, http.StatusUnauthorized, "Unauthorized, please provide a valid token")
return
}
accessToken = strings.TrimPrefix(authHeader, "Bearer ")
}
config, err := server.GetConfig(accessToken, true)
if err == nil {
apiContext.Write(&config)
} else {
//failed to get the config
log.Debugf("GetConfig failed with error %v", err)
ReturnHTTPError(w, r, http.StatusInternalServerError, "Failed to get the auth config")
return
}
}
//Reload is a handler for POST /reloadconfig, reloads the config from Cattle database and initializes the provider
func Reload(w http.ResponseWriter, r *http.Request) {
log.Debugf("Reload called")
_, err := server.Reload(false)
if err != nil {
//failed to reload the config from DB
log.Debugf("Reload failed with error %v", err)
ReturnHTTPError(w, r, http.StatusInternalServerError, "Failed to reload the auth config")
return
}
}
func addErrorToRedirect(redirectURL string, code string) string {
//add code query param to redirect
redirectURLInst, err := url.Parse(redirectURL)
if err == nil {
v := redirectURLInst.Query()
v.Add("errCode", code)
redirectURLInst.RawQuery = v.Encode()
redirectURL = redirectURLInst.String()
} else {
log.Errorf("Error parsing the URL %v ,error is: %v", redirectURL, err)
redirectURL = redirectURL + "?errCode=" + code
}
return redirectURL
}
//GetRedirectURL gets the redirect URL
func GetRedirectURL(w http.ResponseWriter, r *http.Request) {
redirectResponse, err := server.GetRedirectURL()
if err == nil {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(redirectResponse)
} else {
//failed to get the redirectURL
log.Debugf("GetRedirectUrl failed with error %v", err)
ReturnHTTPError(w, r, http.StatusInternalServerError, "Failed to get the redirect URL")
return
}
}
//DoSamlLogout redirects to Saml Logout
func DoSamlLogout(w http.ResponseWriter, r *http.Request) {
if server.SamlServiceProvider != nil {
if server.SamlServiceProvider.ServiceProvider.IDPMetadata != nil {
entityID := server.SamlServiceProvider.ServiceProvider.IDPMetadata.EntityID
entityURL, _ := url.Parse(entityID)
redirectURL := entityURL.Scheme + "://" + entityURL.Host + "/idp/profile/Logout"
log.Debugf("redirecting the user to %v", redirectURL)
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
log.Info("No Logout URL - Saml/Shibboleth IDPMetadata not found")
} else {
log.Info("No Logout URL - Saml/Shibboleth provider is not configured")
}
}
// TestLogin is a test API to check login with code before saving settings to db
func TestLogin(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
cookies := r.Cookies()
var token string
for _, c := range cookies {
if c.Name == "token" {
token = c.Value
}
}
var accessToken string
// header value format will be "Bearer <token>"
if authHeader != "" {
if !strings.HasPrefix(authHeader, "Bearer ") {
log.Errorf("GetMyIdentities Failed to find Bearer token %v", authHeader)
ReturnHTTPError(w, r, http.StatusUnauthorized, "Unauthorized, please provide a valid token")
return
}
accessToken = strings.TrimPrefix(authHeader, "Bearer ")
}
bytes, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Errorf("TestLogin failed with error: %v", err)
ReturnHTTPError(w, r, http.StatusBadRequest, "Bad Request, Please check the request content")
return
}
var testAuthConfig model.TestAuthConfig
err = json.Unmarshal(bytes, &testAuthConfig)
if err != nil {
log.Errorf("TestLogin unmarshal failed with error: %v", err)
ReturnHTTPError(w, r, http.StatusBadRequest, "Bad Request, Please check the request content")
return
}
if testAuthConfig.AuthConfig.Provider == "" {
log.Errorf("UpdateConfig: Provider is a required field")
ReturnHTTPError(w, r, http.StatusBadRequest, "Bad request, Provider is a required field")
return
}
status, err := server.TestLogin(testAuthConfig, accessToken, token)
if err != nil {
log.Errorf("TestLogin GetProvider failed with error: %v", err)
if status == 0 {
status = http.StatusInternalServerError
}
ReturnHTTPError(w, r, status, fmt.Sprintf("%v", err))
}
}
// HandleSamlLogin is the endpoint for /saml/login endpoint
func HandleSamlLogin(w http.ResponseWriter, r *http.Request) {
var redirectBackBaseValue string
s := server.SamlServiceProvider
s.XForwardedProto = r.Header.Get("X-Forwarded-Proto")
if r.URL.Query() != nil {
redirectBackBaseValue = r.URL.Query().Get(redirectBackBase)
if redirectBackBaseValue == "" {
redirectBackBaseValue = server.GetRancherAPIHost()
}
} else {
redirectBackBaseValue = server.GetRancherAPIHost()
}
if !isWhitelisted(redirectBackBaseValue, s.RedirectWhitelist) {
log.Errorf("Cannot redirect to anything other than whitelisted domains and rancher api host")
redirectBackPathValue := r.URL.Query().Get(redirectBackPath)
redirectURL := server.GetSamlRedirectURL(server.GetRancherAPIHost(), redirectBackPathValue)
redirectURL = addErrorToRedirect(redirectURL, "422")
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
serviceProvider := s.ServiceProvider
if r.URL.Path == serviceProvider.AcsURL.Path {
return
}
binding := saml.HTTPRedirectBinding
bindingLocation := serviceProvider.GetSSOBindingLocation(binding)
if bindingLocation == "" {
binding = saml.HTTPPostBinding
bindingLocation = serviceProvider.GetSSOBindingLocation(binding)
}
req, err := serviceProvider.MakeAuthenticationRequest(bindingLocation)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// relayState is limited to 80 bytes but also must be integrety protected.
// this means that we cannot use a JWT because it is way to long. Instead
// we set a cookie that corresponds to the state
relayState := base64.URLEncoding.EncodeToString(randomBytes(42))
secretBlock := x509.MarshalPKCS1PrivateKey(serviceProvider.Key)
state := jwt.New(jwt.SigningMethodHS256)
claims := state.Claims.(jwt.MapClaims)
claims["id"] = req.ID
claims["uri"] = r.URL.String()
signedState, err := state.SignedString(secretBlock)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
s.ClientState.SetState(w, r, relayState, signedState)
if binding == saml.HTTPRedirectBinding {
redirectURL := req.Redirect(relayState)
w.Header().Add("Location", redirectURL.String())
w.WriteHeader(http.StatusFound)
return
}
if binding == saml.HTTPPostBinding {
w.Header().Add("Content-Security-Policy", ""+
"default-src; "+
"script-src 'sha256-AjPdJSbZmeWHnEc5ykvJFay8FTWeTeRbs9dutfZ0HqE='; "+
"reflected-xss block; referrer no-referrer;")
w.Header().Add("Content-type", "text/html")
w.Write([]byte(`<!DOCTYPE html><html><body>`))
w.Write(req.Post(relayState))
w.Write([]byte(`</body></html>`))
return
}
}
// ServeHTTP is the handler for /saml/metadata and /saml/acs endpoints
func ServeHTTP(w http.ResponseWriter, r *http.Request) {
serviceProvider := server.SamlServiceProvider.ServiceProvider
if r.URL.Path == serviceProvider.MetadataURL.Path {
buf, _ := xml.MarshalIndent(serviceProvider.Metadata(), "", " ")
w.Header().Set("Content-Type", "application/samlmetadata+xml")
w.Write(buf)
return
}
if r.URL.Path == serviceProvider.AcsURL.Path {
r.ParseForm()
assertion, err := serviceProvider.ParseResponse(r, getPossibleRequestIDs(r, server.SamlServiceProvider))
if err != nil {
if parseErr, ok := err.(*saml.InvalidResponseError); ok {
log.Errorf("RESPONSE: ===\n%s\n===\nNOW: %s\nERROR: %s",
parseErr.Response, parseErr.Now, parseErr.PrivateErr)
}
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
return
}
HandleSamlAssertion(w, r, assertion, server.SamlServiceProvider)
return
}
http.NotFoundHandler().ServeHTTP(w, r)
}
func getPossibleRequestIDs(r *http.Request, s *model.RancherSamlServiceProvider) []string {
rv := []string{}
for _, value := range s.ClientState.GetStates(r) {
jwtParser := jwt.Parser{
ValidMethods: []string{jwt.SigningMethodHS256.Name},
}
token, err := jwtParser.Parse(value, func(t *jwt.Token) (interface{}, error) {
secretBlock := x509.MarshalPKCS1PrivateKey(s.ServiceProvider.Key)
return secretBlock, nil
})
if err != nil || !token.Valid {
log.Debugf("... invalid token %s", err)
continue
}
claims := token.Claims.(jwt.MapClaims)
rv = append(rv, claims["id"].(string))
}
return rv
}
func randomBytes(n int) []byte {
rv := make([]byte, n)
if _, err := saml.RandReader.Read(rv); err != nil {
panic(err)
}
return rv
}
func GetRedirectParams(w http.ResponseWriter, r *http.Request, serviceProvider *model.RancherSamlServiceProvider) (redirectBackBaseValue string,
redirectBackPathValue string) {
redirectBackBaseValue = server.GetRancherAPIHost()
redirectBackPathValue = "/login/shibboleth-auth"
if serviceProvider.ServiceProvider.Key == nil {
log.Errorf("GetRedirectParams: No key found in service provider")
redirectURL := server.GetSamlRedirectURL(redirectBackBaseValue, redirectBackPathValue)
redirectURL = addErrorToRedirect(redirectURL, "403")
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
secretBlock := x509.MarshalPKCS1PrivateKey(serviceProvider.ServiceProvider.Key)
if relayState := r.Form.Get("RelayState"); relayState != "" {
stateValue := serviceProvider.ClientState.GetState(r, relayState)
if stateValue == "" {
log.Errorf("cannot find corresponding state: %s", relayState)
redirectURL := server.GetSamlRedirectURL(redirectBackBaseValue, redirectBackPathValue)
redirectURL = addErrorToRedirect(redirectURL, "403")
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
jwtParser := jwt.Parser{
ValidMethods: []string{jwt.SigningMethodHS256.Name},
}
state, err := jwtParser.Parse(stateValue, func(t *jwt.Token) (interface{}, error) {
return secretBlock, nil
})
if err != nil || !state.Valid {
log.Errorf("Cannot decode state JWT: %s (%s)", err, stateValue)
redirectURL := server.GetSamlRedirectURL(redirectBackBaseValue, redirectBackPathValue)
redirectURL = addErrorToRedirect(redirectURL, "403")
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
claims := state.Claims.(jwt.MapClaims)
if claims == nil {
redirectURL := server.GetSamlRedirectURL(redirectBackBaseValue, redirectBackPathValue)
redirectURL = addErrorToRedirect(redirectURL, "403")
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
redirectURI := claims["uri"].(string)
log.Debugf("RelayState used to get redirect params: %v", relayState)
log.Debugf("redirectURI from claims: %v", redirectURI)
query, err := url.Parse(redirectURI)
if err != nil {
log.Errorf("Error in getting query params")
redirectURL := server.GetSamlRedirectURL(redirectBackBaseValue, redirectBackPathValue)
redirectURL = addErrorToRedirect(redirectURL, "403")
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
parsedQuery, err := url.ParseQuery(query.RawQuery)
if err != nil {
log.Errorf("Error in parsing query params")
redirectURL := server.GetSamlRedirectURL(redirectBackBaseValue, redirectBackPathValue)
redirectURL = addErrorToRedirect(redirectURL, "403")
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
redirectBackBaseValue = parsedQuery.Get(redirectBackBase)
redirectBackPathValue = parsedQuery.Get(redirectBackPath)
log.Debugf("redirectBackBaseValue, redirectBackPathValue from claims: %v, %v", redirectBackBaseValue, redirectBackPathValue)
// delete the cookie
log.Debugf("Deleting relayState: %v", relayState)
serviceProvider.ClientState.DeleteState(w, r, relayState)
}
return redirectBackBaseValue, redirectBackPathValue
}
// HandleSamlAssertion processes/handles the assertion obtained by the POST to /saml/acs from IdP
func HandleSamlAssertion(w http.ResponseWriter, r *http.Request, assertion *saml.Assertion, serviceProvider *model.RancherSamlServiceProvider) {
redirectBackBaseValue, redirectBackPathValue := GetRedirectParams(w, r, serviceProvider)
log.Debugf("redirectBackBaseValue, redirectBackPathValue from GetRedirectParams: %v, %v", redirectBackBaseValue, redirectBackPathValue)
if redirectBackBaseValue == "" {
redirectBackBaseValue = server.GetRancherAPIHost()
}
redirectURL := server.GetSamlRedirectURL(redirectBackBaseValue, redirectBackPathValue)
if !isWhitelisted(redirectBackBaseValue, serviceProvider.RedirectWhitelist) {
log.Errorf("Cannot redirect to anything other than whitelisted domains and rancher api host")
redirectURL := server.GetSamlRedirectURL(server.GetRancherAPIHost(), redirectBackPathValue)
redirectURL = addErrorToRedirect(redirectURL, "422")
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
samlData := make(map[string][]string)
for _, attributeStatement := range assertion.AttributeStatements {
for _, attr := range attributeStatement.Attributes {
attrName := attr.FriendlyName
if attrName == "" {
attrName = attr.Name
}
for _, value := range attr.Values {
samlData[attrName] = append(samlData[attrName], value.Value)
}
}
}
rancherAPI := server.GetRancherAPIHost()
//get the SAML data, create a jwt token and POST to /v1/token with code = "jwt token"
mapB, _ := json.Marshal(samlData)
inputJSON := make(map[string]string)
inputJSON["code"] = string(mapB)
outputJSON := make(map[string]interface{})
tokenURL := rancherAPI + "/v1/token"
log.Debugf("HandleSamlAssertion: tokenURL %v ", tokenURL)
err := server.RancherClient.Post(tokenURL, inputJSON, &outputJSON)
if err != nil {
//failed to get token from cattle
log.Errorf("HandleSamlAssertion failed to Get token from cattle with error %v", err.Error())
if strings.Contains(err.Error(), "401") {
//add error=401 query param to redirect
redirectURL = addErrorToRedirect(redirectURL, "401")
} else if strings.Contains(err.Error(), "403") {
redirectURL = addErrorToRedirect(redirectURL, "403")
} else {
redirectURL = addErrorToRedirect(redirectURL, "500")
}
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
jwt := outputJSON["jwt"].(string)
log.Debugf("HandleSamlAssertion: Got token %v ", jwt)
secure := false
XForwardedProtoValue := serviceProvider.XForwardedProto
if XForwardedProtoValue == "https" {
secure = true
}
/* token is created at this point. If the redirectBackBase is not same as the current URL's domain, then we cannot set the token as cookie
yet. So we will first send a 200 POST to /v1-auth/saml/tokenhtml, which will contain token cookie and redirectBackBase in HTML body,
and JS which will submit form on load to redirect URL. The handler for v1-auth/saml/tokenhtml will then set the token as cookie
*/
query, err := url.Parse(redirectBackBaseValue)
if err != nil {
log.Errorf("HandleSamlAssertion: Error in parsing redirectBackBaseValue: %v", err)
redirectURL = addErrorToRedirect(redirectURL, "500")
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
log.Debugf("HandleSamlAssertion: r.URL: %v, host: %v, redirectBackBaseValue: %v, redirectBackBaseValue.host: %v", r.URL, r.Host, redirectBackBaseValue,
query.Host)
if query.Host != r.Host {
newRedirectURL := redirectBackBaseValue + postSamlTokenHTML
w.Header().Add("Content-type", "text/html")
tmpl := template.Must(template.New("saml-post-form").Parse(tpl))
data := struct {
URL string
Token string
FinalRedirectURL string
Secure bool
}{
URL: newRedirectURL,
Token: jwt,
FinalRedirectURL: redirectURL,
Secure: secure,
}
log.Debugf("HandleSamlAssertion: Adding data to template: %#v", data)
rv := bytes.Buffer{}
if err := tmpl.Execute(&rv, data); err != nil {
redirectURL = addErrorToRedirect(redirectURL, "500")
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
w.Write(rv.Bytes())
return
}
// else, if redirectBackBase is same as the current URL, continue and set this token as cookie
tokenCookie := &http.Cookie{
Name: "token",
Value: jwt,
Secure: secure,
MaxAge: 0,
Path: "/",
}
http.SetCookie(w, tokenCookie)
log.Debugf("JWT token: %v", jwt)
log.Debugf("redirecting the user with cookie %v to %v", tokenCookie, redirectURL)
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
func PostSamlTokenHTML(w http.ResponseWriter, r *http.Request) {
var token, finalRedirectURL string
var secure bool
var err error
if err = r.ParseForm(); err != nil {
log.Errorf("PostSamlTokenHTML: Error in parsing forn: %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
tokenArr, ok := r.Form["token"]
if !ok || len(tokenArr) == 0 {
log.Errorf("PostSamlTokenHTML: No token provided in POST request: %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
token = tokenArr[0]
log.Debugf("PostSamlTokenHTML: token in the post form: %v", token)
finalRedirectURLArr, ok := r.Form["finalRedirectURL"]
if !ok || len(finalRedirectURLArr) == 0 {
log.Errorf("PostSamlTokenHTML: No finalRedirectURL provided in POST request: %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
finalRedirectURL = finalRedirectURLArr[0]
log.Debugf("PostSamlTokenHTML: finalRedirectURL in the post form: %v", finalRedirectURL)
secureArr, ok := r.Form["secure"]
if !ok || len(secureArr) == 0 {
log.Errorf("PostSamlTokenHTML: No secure parameter provided in POST request: %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
secureStr := secureArr[0]
secure, err = strconv.ParseBool(secureStr)
if err != nil {
log.Errorf("PostSamlTokenHTML: Error in parsing secure flag for token: %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
log.Debugf("PostSamlTokenHTML: secure attribute in the post form: %v, and original: %v", secure, secureStr)
tokenCookie := &http.Cookie{
Name: "token",
Value: token,
Secure: secure,
MaxAge: 0,
Path: "/",
}
http.SetCookie(w, tokenCookie)
log.Debugf("redirecting the user with cookie %v to %v", tokenCookie, finalRedirectURL)
http.Redirect(w, r, finalRedirectURL, http.StatusFound)
}
func isWhitelisted(redirectBackBaseValue string, redirectWhitelist string) bool {
var redirectBackBaseDomainNonPort string
if redirectBackBaseValue == server.GetRancherAPIHost() {
return true
}
redirectURL, err := url.Parse(redirectBackBaseValue)
if err != nil {
log.Errorf("Error in parsing redirect URL")
return false
}
redirectBackBaseDomain := redirectURL.Host
if strings.Contains(redirectBackBaseDomain, ":") {
d := strings.SplitN(redirectBackBaseDomain, ":", 2)
redirectBackBaseDomainNonPort = d[0]
}
// comma separated list of whitelisted domains to redirect to
if redirectWhitelist != "" {
whitelistedDomains := strings.Split(redirectWhitelist, ",")
log.Debugf("Whitelisted domains provided: %v, redirectBackBase: %v, redirectBackBaseNonPort: %v", whitelistedDomains,
redirectBackBaseDomain, redirectBackBaseDomainNonPort)
for _, w := range whitelistedDomains {
if w == redirectBackBaseDomain || w == redirectBackBaseDomainNonPort {
log.Debugf("Whitelisted domain matched: %v", w)
return true
}
}
}
return false
}
|
package main
import (
"log"
"net/http"
"os"
"github.com/natezyz/midget/handlers"
"github.com/natezyz/midget/storage"
)
func main() {
s := &storage.Map{}
s.Init()
http.Handle("/", handlers.Redirect(s))
http.Handle("/encode", handlers.Encode(s))
http.Handle("/decode/", handlers.Decode(s))
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
log.Printf("Starting midget on port: %s\n", port)
err := http.ListenAndServe(":"+port, nil)
if err != nil {
log.Fatal(err)
}
}
|
package set3
import (
"cryptopals/set1"
"cryptopals/utils"
)
func truncateCipherTextsToCommonLength(cipherTexts [][]byte, length int) [][]byte {
var truncated [][]byte
for _, cipherText := range cipherTexts {
truncated = append(truncated, cipherText[:length])
}
return truncated
}
func breakFixedNonceCTRStatistically(cipherTexts [][]byte, keysize int) [][]byte {
// slightly modified version of the algorithm to break Vigenere
var transpose [][]byte
for i := 0; i < keysize; i++ {
var block []byte
for j := 0; j < len(cipherTexts); j++ {
block = append(block, cipherTexts[j][i])
}
transpose = append(transpose, block)
}
var finalKey []byte
for i, block := range transpose {
var freqsTable map[string]float32
// looking at the first results from trying to decrypt the message,
// it appears that on the first block there are only capital letters;
// using the general frequencies table for this doesn't detect the plain
// text correctly, so for this block only I'm using a different
// frequencies list
if i == 0 {
freqsTable = utils.FreqsFirst
}
_, blockKey, _ := set1.DecryptSingleByteXOR(block, freqsTable)
finalKey = append(finalKey, blockKey)
}
var result [][]byte
for _, cipherText := range cipherTexts {
result = append(result, set1.RepeatingKeyXOR(cipherText, finalKey))
}
return result
}
|
package main
import (
"fmt"
"os"
"regexp"
"time"
"math/rand"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"github.com/dghubble/go-twitter/twitter"
"github.com/dghubble/oauth1"
"github.com/op/go-logging"
)
var log = logging.MustGetLogger("example")
var (
// DefaultFormatter is the default formatter used and is only the message.
DefaultFormatter = logging.MustStringFormatter("%{message}")
// GlogFormatter mimics the glog format
GlogFormatter = logging.MustStringFormatter("%{level:.1s}%{time:0102 15:04:05.999999} %{pid} %{shortfile}] %{message}")
)
// Example format string. Everything except the message has a custom color
// which is dependent on the log level. Many fields have a custom output
// formatting too, eg. the time returns the hour down to the milli second.
var format = logging.MustStringFormatter(
`%{color}%{time:15:04:05.000} %{shortfunc} ▶ %{level:.4s} %{id:03x}%{color:reset} %{message}`,
)
var (
session, merr = mgo.Dial("localhost")
client = _setup_twitter_client()
)
func main() {
if merr != nil {
panic(merr)
}
defer session.Close()
_setup_logger()
params := &twitter.StreamFilterParams{
Track: []string{"blockchain"},
StallWarnings: twitter.Bool(true),
}
stream, err := client.Streams.Filter(params)
// stream, err := client.Streams.Sample(params)
log.Info("\n")
if stream != nil {
defer stream.Stop()
demux := twitter.NewSwitchDemux()
s1 := rand.NewSource(time.Now().UnixNano())
r1 := rand.New(s1)
demux.Tweet = func(t *twitter.Tweet) {
txt := t.Text
match, _ := regexp.MatchString("( |#)blockchain ", txt)
if match {
if needToTweetAt(t.User.ID) {
if r1.Intn(100) < 30 {
saveUIDThen(t.User.ID,
func() {
go sendTweetTo(t.IDStr, t.User.ScreenName)
})
}
} else {
table := session.DB("nwbot").C("dupes")
tim := time.Now()
err := table.Insert(&User{t.User.ID, tim.Format("2006-01-02T15:04:05.999999-07:00")})
if err != nil {
log.Fatal(err)
}
}
}
}
for message := range stream.Messages {
demux.Handle(message)
}
}
if err != nil {
log.Error(err)
}
}
type User struct {
UserID int64
Time string
}
func saveUIDThen(uid int64, afterSave func()) int64 {
table := session.DB("nwbot").C("users")
t := time.Now()
err := table.Insert(&User{uid, t.Format("2006-01-02T15:04:05.999999-07:00")})
if err != nil {
log.Fatal(err)
}
afterSave()
return uid
}
func needToTweetAt(uid int64) bool {
result := User{}
table := session.DB("nwbot").C("users")
merr = table.Find(bson.M{"userid": uid}).One(&result)
if merr != nil {
// log.Fatal(merr)
}
return result.UserID != uid
}
func sendTweetTo(tid, username string) {
responseStr := "@" + username + " That's Numberwang!"//, &twitter.StatusUpdateParams{InReplyToStatusID: t.IDStr})
fmt.Println(responseStr, tid)
// // tweet, resp, err := client.Statuses.Update(responseStr, &twitter.StatusUpdateParams{InReplyToStatusID: tid})
//
// if err != nil {
// log.Debug(resp.Body)
// log.Error(err)
// }
// log.Info(tweet)
}
func _setup_twitter_client() *twitter.Client {
config := oauth1.NewConfig("ZnLFucEj6ylvkgI5qkXuZLFug", "Efi61amab0I9ZUQEt5g6fiwdpBwFbaIDB8OnIl2LDDvZNGck1S")
token := oauth1.NewToken("970375160317362176-01dg7jAAjUKPAAIPBa8QSE0zLyth5Jc", "IecJbUhttV1OLmSWyGpaA7V1UgInsfJDa0PfKWtOqBPjE")
httpClient := config.Client(oauth1.NoContext, token)
client := twitter.NewClient(httpClient)
return client;
}
func _setup_logger() {
backend1 := logging.NewLogBackend(os.Stderr, "", 0)
backend1Leveled := logging.AddModuleLevel(backend1)
backend1Formatter := logging.NewBackendFormatter(backend1, format)
logging.SetBackend(backend1Leveled, backend1Formatter)
}
|
package middleware
import (
"github.com/KashEight/not/consts"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
func SetUUIDKey() gin.HandlerFunc {
return func(ctx *gin.Context) {
v := ctx.Param("uuid")
uuid.MustParse(v)
ctx.Set(consts.UUIDKeyName, v)
ctx.Next()
}
}
|
package pipe
//Pipe for handling movement through pipeline. 3 use cases
//1. Source has only an out because it just sends messages
//2. Sink has only an in because it just receieves messages
//3. Transformer will have an in, and an out.
//Not sure about the types right now.
type Pipe struct {
In chan interface{}
Out chan interface{}
}
//NewPipe creates a new Pipe
func NewPipe(stage string) *Pipe {
p := new(Pipe)
switch {
case stage == "source" || stage == "transformer":
p.In = make(chan interface{}, 1)
case stage == "sink" || stage == "transformer":
p.Out = make(chan interface{}, 1)
}
return p
} |
package fyndiqv1
import (
"bytes"
"encoding/json"
"github.com/aquilax/gocommerce/transport"
"strconv"
)
type API struct {
tr transport.Transport
}
// MetaData holds the generic meta data response header
type MetaData struct {
Limit int `json: "limit"`
Next string `json: "next"`
Offset int `json: "offset"`
Previous string `json: "previous"`
TotalCount int `json: "total_count"`
}
// MetaResponse holds generic response with meta data
type MetaResponse struct {
Meta MetaData `json: "meta"`
}
// Variation for article group
// http://fyndiq.github.io/api-v1/#product-article-group
type Variation struct {
ID int `json: "id"`
Name string `json: "name"`
NumInStock int `json: "num_in_stock"`
Location string `json: "location"`
ItemNo string `json: "item_no"`
PlatformItemNo string `json: "platform_item_no"`
}
// ArticleGroup for product
// http://fyndiq.github.io/api-v1/#product-article
type ArticleGroup struct {
Name string `json: "name"`
Variations []Variation `json: "variations"`
}
// Product represents single product
// http://fyndiq.github.io/api-v1/#product
type Product struct {
Title string `json: "title,omitempty"`
Description string `json: "description,omitempty"`
Oldprice float32 `json: "oldprice,omitempty"`
Price float32 `json: "price,omitempty"`
MomsPercent int `json: "moms_percent,omitempty"`
NumInStock int `json: "num_in_stock,omitempty"`
State string `json: "state,omitempty"`
IsBlockedByFyndiq bool `json: "is_blocked_by_fyndiq,omitempty"`
ItemNo string `json: "item_no,omitempty"`
PlatformItemNo string `json: "platform_item_no,omitempty"`
Location string `json: "location,omitempty"`
URL string `json: "url,omitempty"`
VariationGroup ArticleGroup `json: "variation_group,omitempty"`
Images []string `json: "images,omitempty"`
}
// ProductList represents list of products with meta data
type ProductList struct {
MetaResponse
Objects []Product `json: "objects"`
}
func New(tr transport.Transport) *API {
return &API{tr}
}
// GetProducts fetches list of all products
// http://developers.fyndiq.com/api-v1/#get-read-products
func (a *API) GetProducts(url string) (*ProductList, error) {
var productList ProductList
var err error
var b []byte
if b, err = a.tr.Get(url); err != nil {
return nil, err
}
err = json.Unmarshal(b, productList)
return &productList, err
}
// GetProduct fetches single product by ID
// http://fyndiq.github.io/api-v1/#get-read-products
func (a *API) GetProduct(id int) (*Product, error) {
var product Product
var err error
var url string
if url, err = a.tr.URL("product/"+strconv.Itoa(id), map[string]string{}); err != nil {
return nil, err
}
var b []byte
if b, err = a.tr.Get(url); err != nil {
return nil, err
}
err = json.Unmarshal(b, product)
return &product, err
}
// DeleteProduct deletes single product by ID
// http://fyndiq.github.io/api-v1/#delete-delete-products
func (a *API) DeleteProduct(id int) error {
var err error
var url string
if url, err = a.tr.URL("product/", map[string]string{}); err != nil {
return err
}
return a.tr.Delete(url)
}
// CreateProduct creates new product
// http://fyndiq.github.io/api-v1/#post-create-products
func (a *API) CreateProduct(product *Product) error {
var err error
var url string
var post []byte
if post, err = json.Marshal(product); err != nil {
return err
}
if url, err = a.tr.URL("product/", map[string]string{}); err != nil {
return err
}
return a.tr.Post(url, bytes.NewBuffer(post))
}
// UpdateProduct updates existing product
// http://fyndiq.github.io/api-v1/#post-create-products
func (a *API) UpdateProduct(id int, product *Product) error {
var err error
var url string
var post []byte
if post, err = json.Marshal(product); err != nil {
return err
}
if url, err = a.tr.URL("product/"+strconv.Itoa(id), map[string]string{}); err != nil {
return err
}
return a.tr.Put(url, bytes.NewBuffer(post))
}
|
package main
import (
"time"
"github.com/mattermost/mattermost-plugin-api/cluster"
"github.com/pkg/errors"
)
// OnActivate register the plugin command
func (p *Plugin) OnActivate() error {
p.router = p.InitAPI()
job, cronErr := cluster.Schedule(
p.API,
"BackgroundJob",
cluster.MakeWaitForRoundedInterval(1*time.Minute),
p.sendBroadcast,
)
if cronErr != nil {
return errors.Wrap(cronErr, "failed to schedule background job")
}
p.backgroundJob = job
return nil
}
|
/**
* All Rights Reserved
* This software is proprietary information of Akurey
* Use is subject to license terms.
* Filename: common.go
*
* Author: rnavarro@akurey.com
* Description: Common functions used in several places
*/
package common
import (
"strconv"
"net/url"
"errors"
)
/**
* Takes URL params and assigns them to a variable
* @param {url.Values} pParams Params array
* @param {string} pValueToGet Parameter name to get
* @param {*int} pVariable Variable to change
* @return {error} If any
*/
func SetParamToVar(pParams url.Values, pValueToGet string, pVariable *int) error{
param, ok := pParams[pValueToGet]
if ok {
result, err := strconv.Atoi(param[0])
if err == nil {
*pVariable = result
return nil
}
return errors.New("could not assign value to int")
}
return nil
} |
package palindrome
import (
"errors"
"math"
)
// Product structure
type Product struct {
Product int // palindromic, of course
Factorizations [][2]int //list of all possible two-factor factorizations of Product, within given limits, in order
}
func reverseNumber(x int) int {
res := 0
for x > 0 {
res = res*10 + x%10
x = x / 10
}
return res
}
func isPalindrome(x int) bool {
if x < 0 {
x = -x
}
return reverseNumber(x) == x
}
// Products finds the largest and smallest palindromes
// which are products of numbers within the range fmin to fmax.
func Products(fmin, fmax int) (pmin, pmax Product, err error) {
min := math.MaxInt32
max := -min
for i := fmin; i <= fmax; i++ {
for j := i; j <= fmax; j++ {
p := i * j
if p < max {
continue
}
if isPalindrome(p) {
if p > max {
max = p
pmax.Product = max
pmax.Factorizations = [][2]int{{i, j}}
} else if p == max {
pmax.Factorizations = append(pmax.Factorizations, [2]int{i, j})
}
}
}
}
for i := fmin; i <= fmax; i++ {
for j := i; j <= fmax; j++ {
p := i * j
if p > min {
continue
}
if isPalindrome(p) {
if p < min {
min = p
pmin.Product = min
pmin.Factorizations = [][2]int{{i, j}}
} else if p == min {
pmin.Factorizations = append(pmin.Factorizations, [2]int{i, j})
}
}
}
}
if min == fmax*fmax+1 {
err = errors.New("no palindromes")
if fmin > fmax {
err = errors.New("fmin > fmax")
}
}
return
}
|
package problem0003
func lengthOfLongestSubstring(s string) int {
table := [128]int{}
start, maxLen := 0, 0
for i := range table {
table[i] = -1
}
for i, c := range s {
if table[c] >= start {
start = table[c] + 1
}
table[c] = i
maxLen = maxInt(maxLen, i-start+1)
}
return maxLen
}
func maxInt(a, b int) int {
if a > b {
return a
}
return b
}
|
package main
import (
"encoding/json"
"flag"
"fmt"
"github.com/futurehomeno/fimpgo"
log "github.com/sirupsen/logrus"
"github.com/thingsplex/tpflow"
fapi "github.com/thingsplex/tpflow/api"
"github.com/thingsplex/tpflow/flow"
"github.com/thingsplex/tpflow/registry/integration/fimpcore"
"github.com/thingsplex/tpflow/registry/storage"
"gopkg.in/natefinch/lumberjack.v2"
"io/ioutil"
//_ "net/http/pprof"
"runtime"
)
// SetupLog configures default logger
// Supported levels : info , degug , warn , error
func SetupLog(logfile string, level string, logFormat string) {
if logFormat == "json" {
log.SetFormatter(&log.JSONFormatter{TimestampFormat: "2006-01-02 15:04:05.999"})
} else {
log.SetFormatter(&log.TextFormatter{FullTimestamp: true, ForceColors: true, TimestampFormat: "2006-01-02T15:04:05.999"})
}
logLevel, err := log.ParseLevel(level)
if err == nil {
log.SetLevel(logLevel)
} else {
log.SetLevel(log.DebugLevel)
}
if logfile != "" {
l := lumberjack.Logger{
Filename: logfile,
MaxSize: 5, // megabytes
MaxBackups: 2,
}
log.SetOutput(&l)
}
}
func InitApiMqttTransport(config tpflow.Configs) (*fimpgo.MqttTransport,error) {
log.Info("<main> Initializing fimp MQTT client.")
clientId := config.MqttClientIdPrefix + "tpflow_api"
msgTransport := fimpgo.NewMqttTransport(config.MqttServerURI, clientId, config.MqttUsername, config.MqttPassword, true, 1, 1)
msgTransport.SetGlobalTopicPrefix(config.MqttTopicGlobalPrefix)
err := msgTransport.Start()
log.Info("<main> Mqtt transport connected")
if err != nil {
log.Error("<main> Error connecting to broker : ", err)
} else {
}
return msgTransport,err
}
func main() {
configs := tpflow.Configs{}
var configFile string
flag.StringVar(&configFile, "c", "", "Config file")
flag.Parse()
if configFile == "" {
configFile = "./config.json"
} else {
fmt.Println("Loading configs from file ", configFile)
}
configFileBody, err := ioutil.ReadFile(configFile)
err = json.Unmarshal(configFileBody, &configs)
if err != nil {
fmt.Print(err)
panic("Can't load config file.")
}
registryBackend := "vinculum"
SetupLog(configs.LogFile, configs.LogLevel, configs.LogFormat)
log.Info("--------------Starting Thingsplex-Flow----------------")
var registry storage.RegistryStorage
//---------THINGS REGISTRY-------------
if registryBackend == "vinculum" {
registry = storage.NewVinculumRegistryStore(&configs)
registry.Connect()
}else if registryBackend == "local" {
log.Info("<main>-------------- Starting service registry ")
registry = storage.NewThingRegistryStore(configs.RegistryDbFile)
log.Info("<main> Started ")
}
log.Info("<main>-------------- Starting service registry integration ")
regMqttIntegr := fimpcore.NewMqttIntegration(&configs, registry)
regMqttIntegr.InitMessagingTransport()
log.Info("<main> Started ")
//---------FLOW------------------------
log.Info("<main> Starting Flow manager")
flowManager, err := flow.NewManager(configs)
if err != nil {
log.Error("Can't Init Flow manager . Error :", err)
}
flowManager.GetConnectorRegistry().AddConnection("thing_registry", "thing_registry", "thing_registry", registry)
err = flowManager.LoadAllFlowsFromStorage()
if err != nil {
log.Error("Can't load Flows from storage . Error :", err)
}
ctxApi := fapi.NewContextApi(flowManager.GetGlobalContext())
flowApi := fapi.NewFlowApi(flowManager, &configs)
regApi := fapi.NewRegistryApi(registry)
apiMqttTransport,err := InitApiMqttTransport(configs)
if err == nil {
flowApi.RegisterMqttApi(apiMqttTransport)
regApi.RegisterMqttApi(apiMqttTransport)
ctxApi.RegisterMqttApi(apiMqttTransport)
}
log.Info("<main> Started")
//<< PPPROF >>
//if configs.EnableProfiler {
// go func() {
// // http://cube.local:6060/debug/pprof/
// // go tool pprof http://cube.local:6060/debug/pprof/heap
// http.ListenAndServe(":6060", nil)
// }()
//}
//e.Logger.Debug(e.Start(":8083"))
//c := make(chan os.Signal, 1)
//signal.Notify(c)
//_ = <-c
runtime.GC()
select {}
registry.Disconnect()
log.Info("<main> Application is terminated")
}
|
package controller
import (
"database/sql"
"fmt"
"strconv"
"local.packages/models"
"local.packages/service"
"net/http"
"github.com/gin-gonic/gin"
)
type OutputForm struct {
CategoryIds []string `json:"category_ids"`
Achievement models.OutputAchievement `json:"achievement"`
}
func FindOutputByUser(c *gin.Context) {
userID, _ := strconv.Atoi(c.Query("user_id"))
outputService := service.NewOutputService()
ou, err := outputService.FindByUser(userID)
switch {
case err == sql.ErrNoRows:
c.JSON(http.StatusOK, gin.H{
"message": "OK",
"output": ou,
"categories": "",
})
return
case err != nil:
fmt.Println(err)
c.JSON(http.StatusBadRequest, gin.H{
"message": "ng",
"err": err,
})
return
default:
}
categories, err2 := outputService.FindCategoriesBy(ou.OutputAchievementID)
switch {
case err2 == sql.ErrNoRows:
c.JSON(http.StatusOK, gin.H{
"message": "OK",
"output": ou,
"categories": "",
})
return
case err2 != nil:
fmt.Println(err2)
c.JSON(http.StatusBadRequest, gin.H{
"message": "ng",
"err": err2,
})
default:
}
c.JSON(http.StatusOK, gin.H{
"message": "OK",
"output": ou,
"categories": categories,
})
}
func AddOrEditOutput(c *gin.Context) {
var outputForm OutputForm
c.ShouldBindJSON(&outputForm)
outputService := service.NewOutputService()
out, err := outputService.FindByUser(outputForm.Achievement.UserID)
var err2 error
switch {
case err == sql.ErrNoRows:
// まだ本日のoutputが登録されていない場合
err2 = outputService.Create(outputForm.Achievement, outputForm.CategoryIds)
case err != nil:
fmt.Println(err)
c.JSON(http.StatusBadRequest, gin.H{
"message": "ng",
"err": err,
})
return
default:
// 既に登録されている場合
err2 = outputService.Update(outputForm.Achievement, outputForm.CategoryIds, out.OutputAchievementID)
}
if err2 != nil {
fmt.Println(err2)
c.JSON(http.StatusBadRequest, gin.H{
"message": "ng",
"err": err2,
})
return
}
c.JSON(http.StatusOK, gin.H{
"message": "ok",
"output": out,
})
}
|
package main
import (
"bufio"
"fmt"
"io"
"net"
"os"
"strings"
)
func main() {
//addr := os.Args[1]
addr := "localhost:8088"
conn, err := net.Dial("tcp", addr)
if err != nil {
fmt.Errorf("%v", err)
os.Exit(1)
}
defer conn.Close()
info := bufio.NewScanner(conn)
info.Scan()
pwd := info.Text()
fmt.Printf("ftp:%s>", pwd)
cmdline := bufio.NewScanner(os.Stdin)
var cmd string
for {
cmdline.Scan()
cmd = cmdline.Text()
_, err := io.WriteString(conn, cmd+"\n")
if err != nil {
fmt.Errorf("%v\n", err)
fmt.Printf("ftp:%s>", pwd)
continue
}
cmdInfo := strings.Fields(cmd)
switch cmdInfo[0] {
case "cd":
info.Scan()
if info.Text() == "err" {
fmt.Println("erro!")
fmt.Printf("ftp:%s>", pwd)
continue
}
pwd = info.Text()
case "ls":
info.Scan()
if info.Text() == "err" {
fmt.Println("erro!")
fmt.Printf("ftp:%s>", pwd)
continue
}
for info.Text() != "EOF" {
fmt.Println(info.Text())
info.Scan()
}
case "exit":
fmt.Println("exit!")
os.Exit(0)
}
fmt.Printf("ftp:%s>", pwd)
}
}
|
package t1time
// Copyright 2016-2017 MediaMath
//
// 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.
import (
"time"
)
const (
// T1Fmt is the time layout used by Adama. It is most similar to
// RFC3339, which is the standard used by encoding/json for encoding and
// decoding of time.Time values. it differs in that it doesn't have a
// colon in the time zone specifier, which is mandated by RFC3339, but
// not by ISO8601 (which this does adhere to).
T1Fmt = "\"2006-01-02T15:04:05Z0700\""
)
// T1Time is a time.Time type with a different JSON-parsing format.
type T1Time time.Time
// UnmarshalJSON implements the json.Unmarshaler interface.
// The time is expected to be a quoted string in RFC 3339 format,
// except without the colon in the time zone specifier.
func (t *T1Time) UnmarshalJSON(data []byte) error {
// Fractional seconds are handled implicitly by Parse
val, err := time.Parse(T1Fmt, string(data))
*t = T1Time(val)
return err
}
// String fulfills the Stringer interface.
func (t T1Time) String() string {
return time.Time(t).Format("2006-01-02 15:04:05.999999999 -0700 MST")
}
// MarshalJSON fulfills the Marshaler interface for T1Time.
func (t T1Time) MarshalJSON() ([]byte, error) {
// T1 *accepts* times as RFC3339 (that is, with the colon in the time
// zone specifier). So we can just delegate to the standard.
return time.Time(t).MarshalJSON()
}
|
package _2_Null_Object_Pattern
//步骤 1
//创建一个抽象类。
type AbstractCustomer interface {
isNil() bool
getName() string
}
//步骤 2
//创建扩展了上述类的实体类。
type RealCustomer struct {
name string
}
func (receiver *RealCustomer) isNil() bool {
return false
}
func (receiver *RealCustomer) getName() string {
return receiver.name
}
type NullCustomer struct{}
func (receiver *NullCustomer) isNil() bool {
return true
}
func (receiver *NullCustomer) getName() string {
return "Not Available in Customer Database"
}
//步骤 3
//创建 CustomerFactory 类。
var names = [3]string{"Rob", "Joe", "Julie"}
func getCustomer(name string) AbstractCustomer {
for _, v := range names {
if v == name {
return &RealCustomer{name}
}
}
return &NullCustomer{}
}
|
package repositories
import (
"countdown/countdown-api/requests"
"fmt"
"log"
"os"
"time"
_ "github.com/jinzhu/gorm/dialects/postgres"
"github.com/jinzhu/gorm"
)
var DB *gorm.DB
var err error
func init() {
DB, err = DBInit()
if err != nil {
log.Fatal(err)
}
}
func DBInit() (*gorm.DB, error) {
dbinfo := fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s sslmode=disable",
os.Getenv("PG_USER"),
os.Getenv("PG_PASSWORD"),
os.Getenv("PG_HOST"),
os.Getenv("PG_PORT"),
os.Getenv("PG_DB"),
)
for i := 0; i < 10; i++ {
DB, err = gorm.Open("postgres", dbinfo) // gorm checks Ping on Open
if err == nil {
break
}
log.Printf("Error while connecting to DB : %s", err.Error())
log.Println("Trying to connect ... waiting 5 seconds")
time.Sleep(5 * time.Second)
}
if err != nil {
return DB, err
}
//create tables at start
err = DB.AutoMigrate(&requests.Task{}).Error
if err != nil {
log.Fatal(err)
}
return DB, err
}
func CreateTask(t *requests.Task) error {
if err := DB.Create(t).Error; err != nil {
return err
}
return nil
}
func GetTasks() ([]requests.Task, error) {
var tasks []requests.Task
if err := DB.Order("timestamp asc").Find(&tasks).Error; err != nil {
return tasks, err
}
return tasks, err
}
func GetTask(taskID uint) (*requests.Task, error) {
var task requests.Task
if err := DB.Where("id = ?", taskID).First(&task).Error; err != nil {
return nil, err
}
return &task, nil
}
func DeleteTask(t *requests.DeleteTask) error {
task, err := GetTask(t.TaskID)
if err != nil {
return err
}
if err := DB.Delete(&task).Error; err != nil {
return err
}
return err
}
|
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package typec
import (
"context"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"time"
"chromiumos/tast/ctxutil"
"chromiumos/tast/errors"
"chromiumos/tast/local/audio"
"chromiumos/tast/local/audio/crastestclient"
"chromiumos/tast/local/chrome"
"chromiumos/tast/local/chrome/display"
"chromiumos/tast/local/chrome/uiauto"
"chromiumos/tast/local/chrome/uiauto/faillog"
"chromiumos/tast/local/chrome/uiauto/filesapp"
"chromiumos/tast/local/chrome/uiauto/nodewith"
"chromiumos/tast/local/chrome/uiauto/quicksettings"
"chromiumos/tast/local/chrome/uiauto/role"
"chromiumos/tast/local/cryptohome"
"chromiumos/tast/local/cswitch"
"chromiumos/tast/local/input"
"chromiumos/tast/testing"
"chromiumos/tast/testing/hwdep"
)
// AudioSwitchOnboardSpeakerToHDMIHotplug test requires the following H/W topology to run.
// DUT ------> C-Switch(device that performs hot plug-unplug) ----> External Type-C HDMI display.
// Command to execute: tast run -var=typec.cSwitchPort=<cswitch_port_ID> \
// -var=typec.domainIP=localhost:9000 <DUT_IP> typec.AudioSwitchOnboardSpeakerToHDMIHotplug.quick
func init() {
testing.AddTest(&testing.Test{
Func: AudioSwitchOnboardSpeakerToHDMIHotplug,
LacrosStatus: testing.LacrosVariantUnneeded,
Desc: "Verifies local audio playback through default app, switch audio playback between internal-speaker and HDMI display",
Contacts: []string{"ambalavanan.m.m@intel.com", "intel-chrome-system-automation-team@intel.com"},
SoftwareDeps: []string{"chrome"},
Attr: []string{"group:typec"},
Vars: []string{"typec.cSwitchPort", "typec.domainIP"},
HardwareDeps: hwdep.D(hwdep.Speaker(), hwdep.InternalDisplay()),
Fixture: "chromeLoggedIn",
Params: []testing.Param{{
Name: "quick",
Val: 1,
}, {
Name: "bronze",
Val: 10,
Timeout: 6 * time.Minute,
}, {
Name: "silver",
Val: 15,
Timeout: 8 * time.Minute,
}, {
Name: "gold",
Val: 20,
Timeout: 12 * time.Minute,
}},
})
}
// AudioSwitchOnboardSpeakerToHDMIHotplug performs typec HDMI external display hotplug
// and does audio switching from internal-speaker to HDMI display via quicksettings.
func AudioSwitchOnboardSpeakerToHDMIHotplug(ctx context.Context, s *testing.State) {
// Shorten deadline to leave time for cleanup.
cleanupCtx := ctx
ctx, cancel := ctxutil.Shorten(ctx, 20*time.Second)
defer cancel()
cr := s.FixtValue().(*chrome.Chrome)
tconn, err := cr.TestAPIConn(ctx)
if err != nil {
s.Fatal("Failed to create test API connection: ", err)
}
defer faillog.DumpUITreeOnError(cleanupCtx, s.OutDir(), s.HasError, tconn)
// Config file which contains expected values of USB4/TBT parameters.
const testConfig = "test_config.json"
// cswitch port ID.
cSwitchON := s.RequiredVar("typec.cSwitchPort")
// IP address of Tqc server hosting device.
domainIP := s.RequiredVar("typec.domainIP")
downloadsPath, err := cryptohome.DownloadsPath(ctx, cr.NormalizedUser())
if err != nil {
s.Fatal("Failed to retrieve users Downloads path: ", err)
}
// Generate sine raw input file.
rawFileName := "audioTestFile.raw"
rawFilePath := filepath.Join(downloadsPath, rawFileName)
rawFile := audio.TestRawData{
Path: rawFilePath,
BitsPerSample: 16,
Channels: 2,
Rate: 48000,
Frequencies: []int{440, 440},
Volume: 0.05,
Duration: 720,
}
if err := audio.GenerateTestRawData(ctx, rawFile); err != nil {
s.Fatal("Failed to generate audio test data: ", err)
}
defer os.Remove(rawFile.Path)
wavFileName := "audioTestFile.wav"
wavFile := filepath.Join(downloadsPath, wavFileName)
if err := audio.ConvertRawToWav(ctx, rawFilePath, wavFile, 48000, 2); err != nil {
s.Fatal("Failed to convert raw to wav: ", err)
}
defer os.Remove(wavFile)
kb, err := input.VirtualKeyboard(ctx)
if err != nil {
s.Fatal("Failed to find keyboard: ", err)
}
defer kb.Close()
files, err := filesapp.Launch(ctx, tconn)
if err != nil {
s.Fatal("Failed to launch the Files App: ", err)
}
defer files.Close(cleanupCtx)
if err := files.OpenDownloads()(ctx); err != nil {
s.Fatal("Failed to open Downloads folder in files app: ", err)
}
if err := files.OpenFile(wavFileName)(ctx); err != nil {
s.Fatalf("Failed to open the audio file %q: %v", wavFileName, err)
}
// Closing the audio player.
defer kb.Accel(cleanupCtx, "Ctrl+W")
// Create C-Switch session that performs hot plug-unplug on TBT device.
sessionID, err := cswitch.CreateSession(ctx, domainIP)
if err != nil {
s.Fatal("Failed to create sessionID: ", err)
}
const cSwitchOFF = "0"
defer func(ctx context.Context) {
s.Log("Performing cleanup")
if err := cswitch.ToggleCSwitchPort(ctx, sessionID, cSwitchOFF, domainIP); err != nil {
s.Fatal("Failed to disable c-switch port at cleanup: ", err)
}
if err := cswitch.CloseSession(ctx, sessionID, domainIP); err != nil {
s.Log("Failed to close sessionID: ", err)
}
}(cleanupCtx)
cras, err := audio.NewCras(ctx)
if err != nil {
s.Fatal("Failed to create Cras object: ", err)
}
playPauseButton := nodewith.Name("Toggle play pause").Role(role.Button)
ui := uiauto.New(tconn)
infoBeforePause, err := ui.Info(ctx, playPauseButton)
if err != nil {
s.Fatal("Failed to get UI node info during audio playback: ", err)
}
iter := s.Param().(int)
for i := 1; i <= iter; i++ {
s.Logf("Iteration: %d/%d", i, iter)
if err := cswitch.ToggleCSwitchPort(ctx, sessionID, cSwitchON, domainIP); err != nil {
s.Fatal("Failed to enable c-switch port: ", err)
}
if err := performAudioSwitching(ctx, ui, tconn, cras, playPauseButton, infoBeforePause); err != nil {
s.Fatal("Failed to perform audio switching: ", err)
}
if err := cswitch.ToggleCSwitchPort(ctx, sessionID, cSwitchOFF, domainIP); err != nil {
s.Fatal("Failed to disable c-switch port: ", err)
}
}
}
// verifyFirstRunningDevice verifies whether audio is routing through audioDeviceName or not.
func verifyFirstRunningDevice(ctx context.Context, audioDeviceName string) error {
return testing.Poll(ctx, func(ctx context.Context) error {
devName, err := crastestclient.FirstRunningDevice(ctx, audio.OutputStream)
if err != nil {
return errors.Wrap(err, "failed to detect running output device")
}
if audioDeviceName != devName {
return errors.Wrapf(err, "unexpected audio node: got %q; want %q", devName, audioDeviceName)
}
return nil
}, &testing.PollOptions{Timeout: 10 * time.Second})
}
// selectedAudioNodeViaUI selects audio node from quick-settings, returns audioDeviceName and audioDeviceType.
func selectedAudioNodeViaUI(ctx context.Context, cras *audio.Cras, tconn *chrome.TestConn, audioNodeUIElement string) (string, string, error) {
// Select output device.
if err := quicksettings.Show(ctx, tconn); err != nil {
return "", "", errors.Wrap(err, "failed to show Quick Settings")
}
if err := quicksettings.SelectAudioOption(ctx, tconn, audioNodeUIElement); err != nil {
return "", "", errors.Wrap(err, "failed to select audio option")
}
// Get Current active node.
audioDeviceName, audioDeviceType, err := cras.SelectedOutputDevice(ctx)
if err != nil {
return "", "", errors.Wrap(err, "failed to get the selected audio device")
}
if err := quicksettings.Hide(ctx, tconn); err != nil {
return "", "", errors.Wrap(err, "failed to hide quick settings")
}
return audioDeviceName, audioDeviceType, nil
}
// typecHDMIDisplayDetection checks for detection of typec HDMI external display.
func typecHDMIDisplayDetection(ctx context.Context, tconn *chrome.TestConn) (string, error) {
var displayName string
if err := testing.Poll(ctx, func(ctx context.Context) error {
displayInfo, err := display.GetInfo(ctx, tconn)
if err != nil {
return errors.Wrap(err, "failed to get external display name")
}
if len(displayInfo) < 2 {
return errors.New("failed to find external display")
}
displayName = displayInfo[1].Name
const displayInfoFile = "/sys/kernel/debug/dri/0/i915_display_info"
out, err := ioutil.ReadFile(displayInfoFile)
if err != nil {
return errors.Wrap(err, "failed to read i915_display_info file")
}
displayInfoRe := regexp.MustCompile(`.*pipe\s+[BCD]\]:\n.*active=yes, mode=.[0-9]+x[0-9]+.: [0-9]+.*\s+[hw: active=yes]+`)
matches := displayInfoRe.FindAllString(string(out), -1)
if len(matches) != 1 {
return errors.New("failed to check external display info")
}
typecHDMIRe := regexp.MustCompile(`.*DP branch device present.*yes\n.*Type.*HDMI`)
if !typecHDMIRe.MatchString(string(out)) {
return errors.New("failed to detect external typec HDMI display")
}
return nil
}, &testing.PollOptions{Timeout: 15 * time.Second}); err != nil {
return "", errors.Wrap(err, "timeout to get external display info")
}
return displayName, nil
}
// resumeAudioPlayback will resumes the audio playback.
func resumeAudioPlayback(ctx context.Context, ui *uiauto.Context, playPauseButton *nodewith.Finder, infoBeforePause *uiauto.NodeInfo) error {
infoAtPause, err := ui.Info(ctx, playPauseButton)
if err != nil {
return errors.Wrap(err, "failed to get UI playPauseButton node info")
}
if infoBeforePause != infoAtPause {
testing.ContextLog(ctx, "Resuming audio play")
if err := ui.LeftClick(playPauseButton)(ctx); err != nil {
return errors.Wrap(err, "failed to play audio")
}
}
return nil
}
func performAudioSwitching(ctx context.Context, ui *uiauto.Context, tconn *chrome.TestConn, cras *audio.Cras, playPauseButton *nodewith.Finder, infoBeforePause *uiauto.NodeInfo) error {
// Check whether external typec HDMI display is detected.
displayName, err := typecHDMIDisplayDetection(ctx, tconn)
if err != nil {
return errors.Wrap(err, "failed to detect connected typec HDMI display")
}
// From quick-settigs select internal-speaker as output audio node.
audioNodeInternalSpeaker := "Speaker (internal)"
audioDeviceName, audioDeviceType, err := selectedAudioNodeViaUI(ctx, cras, tconn, audioNodeInternalSpeaker)
if err != nil {
return errors.Wrapf(err, "failed to select %q as audio output node", audioDeviceType)
}
// Check whether audio routing device is internal-speaker.
if err := verifyFirstRunningDevice(ctx, audioDeviceName); err != nil {
if err := resumeAudioPlayback(ctx, ui, playPauseButton, infoBeforePause); err != nil {
return errors.Wrap(err, "failed to resume audio playback after selecting internal-speaker")
}
if err := verifyFirstRunningDevice(ctx, audioDeviceName); err != nil {
return errors.Wrapf(err, "failed to route audio through %q audio device", audioDeviceName)
}
}
// From quick-settigs select external HDMI as output audio node.
audioNodeHDMI := displayName + " (HDMI/DP)"
audioDeviceName, audioDeviceType, err = selectedAudioNodeViaUI(ctx, cras, tconn, audioNodeHDMI)
if err != nil {
return errors.Wrapf(err, "failed to select %q as audio output node", audioDeviceType)
}
// Check whether audio routing device is external HDMI.
if err := verifyFirstRunningDevice(ctx, audioDeviceName); err != nil {
if err := resumeAudioPlayback(ctx, ui, playPauseButton, infoBeforePause); err != nil {
return errors.Wrap(err, "failed to resume audio playback after selecting exteranl HDMI")
}
if err := verifyFirstRunningDevice(ctx, audioDeviceName); err != nil {
return errors.Wrapf(err, "failed to route audio through %q audio device", audioDeviceType)
}
}
return nil
}
|
//Go 语言循环语句
// 循环控制语句
//循环控制语句可以控制循环体内语句的执行过程。
//
//GO 语言支持以下几种循环控制语句:
//
//控制语句 描述
//break 语句 经常用于中断当前 for 循环或跳出 switch 语句
//continue 语句 跳过当前循环的剩余语句,然后继续进行下一轮循环。
//goto 语句 将控制转移到被标记的语句。
package main
import "fmt"
func main() {
var num int = 1
for true {
fmt.Printf("%d test \n", num)
num += 1
}
}
|
package store
// Provider creates a Persister for given string key
type Provider func(string) Store
// Store can load and store data
type Store interface {
Load(any) error
Save(any) error
}
|
package ravendb
import (
"bytes"
"crypto/md5"
"encoding/binary"
"fmt"
"io"
"reflect"
"sort"
"time"
)
type HashCalculator struct {
_buffer bytes.Buffer
}
func (h *HashCalculator) getHash() string {
data := h._buffer.Bytes()
return fmt.Sprintf("%x", md5.Sum(data))
}
func (h *HashCalculator) write(v interface{}) {
if v == nil {
io.WriteString(&h._buffer, "null")
return
}
switch v2 := v.(type) {
case string:
io.WriteString(&h._buffer, v2)
case []string:
if len(v2) == 0 {
io.WriteString(&h._buffer, "null-list-str")
return
}
must(binary.Write(&h._buffer, binary.LittleEndian, int64(len(v2))))
for _, s := range v2 {
io.WriteString(&h._buffer, s)
}
case []interface{}:
for _, v := range v2 {
h.write(v)
}
case map[string]string:
if len(v2) == 0 {
io.WriteString(&h._buffer, "null-dic<string,string>")
return
}
must(binary.Write(&h._buffer, binary.LittleEndian, int64(len(v2))))
// in Go iteration over map is not stable, so need to manually sort keys
var keys []string
for k := range v2 {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
v := v2[k]
io.WriteString(&h._buffer, k)
io.WriteString(&h._buffer, v)
}
case map[string]interface{}:
// this is Parameters
if len(v2) == 0 {
io.WriteString(&h._buffer, "null-dic<string,object>")
return
}
must(binary.Write(&h._buffer, binary.LittleEndian, int64(len(v2))))
// in Go iteration over map is not stable, so need to manually sort keys
var keys []string
for k := range v2 {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
v = v2[k]
io.WriteString(&h._buffer, k)
if v == nil {
io.WriteString(&h._buffer, "null")
return
}
tp := reflect.TypeOf(v)
if _, ok := isPtrStruct(tp); ok || tp.Kind() == reflect.Struct {
// when value of parameter is a struct or pointer to struct
// it could be our param like SuggestionOptions or
// param that is custom type used by the user
s := fmt.Sprintf("%#v", v)
io.WriteString(&h._buffer, s)
return
}
h.write(v)
}
case bool:
var toWrite int32 = 1
if v2 {
toWrite = 2
}
must(binary.Write(&h._buffer, binary.LittleEndian, toWrite))
case time.Time:
t := v2.UTC().Unix()
must(binary.Write(&h._buffer, binary.LittleEndian, t))
case int:
must(binary.Write(&h._buffer, binary.LittleEndian, int64(v2)))
default:
//fmt.Printf("Writing value '%v' of type %T\n", v, v)
// binary.Write handles all primitive types, except string and int
must(binary.Write(&h._buffer, binary.LittleEndian, v))
}
}
|
package main
import (
"flag"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/spf13/viper"
"xiamiToLastfm/app"
"xiamiToLastfm/lastfm"
"xiamiToLastfm/xiami"
)
var debug bool
var frequency = time.Minute
var config string
func main() {
if f, _ := app.Logger(debug); f != nil {
defer f.Close()
}
prepare()
delayStart()
run()
}
func run() {
ticker := time.NewTicker(frequency)
fmt.Println("start scrobbling...")
nowPlayingChan := make(chan xiami.Track)
playedChan := make(chan xiami.Track, 10)
quitChan := make(chan struct{})
lastfm.QuitChan = quitChan
stop(quitChan)
go func() {
if err := app.TempRead(playedChan); err != nil {
log.Println(err)
}
for {
select {
case xm := <-nowPlayingChan:
if err := lastfm.UpdateNowPlaying(xm); err != nil {
fmt.Println("last.fm: updateNowPlaying sent failed.")
log.Println("last.fm: ", err)
}
case xm := <-playedChan:
if err := lastfm.Scrobble(xm); err != nil {
playedChan <- xm
fmt.Println("last.fm: scrobble sent failed. Try again in 5 seconds.")
log.Println("last.fm: ", err)
time.Sleep(time.Second * 5)
}
//write the execute time while channel's empty. To avoid duplicate request to last.fm.
if len(playedChan) < 1 {
viper.Set("xiami.checked_at", time.Now().Truncate(time.Minute).Unix())
viper.WriteConfig()
}
case <-quitChan:
return
}
}
}()
for {
select {
case <-ticker.C:
xiami.Tracks(nowPlayingChan, playedChan)
case <-quitChan:
ticker.Stop()
close(nowPlayingChan)
windUp(playedChan)
close(playedChan)
return
}
}
}
func init() {
flag.BoolVar(&debug, "d", false, "debug mode, will export logs to file")
minute := flag.Uint64("m", 1, "how often to check the xiami page. unit: minute")
flag.StringVar(&config, "c", "config.toml", "config name and path")
flag.Parse()
frequency *= time.Duration(*minute)
app.InitConfig(config)
}
func prepare() {
xiami.Init()
lastfm.Auth()
}
// delayStart will delay the program a few seconds and start at exact next minute,
// to ensure time calculated from xiami page will be relatively accurate.
func delayStart() {
now := time.Now()
start := now.Truncate(time.Minute).Add(time.Minute)
fmt.Println("will start at", start.Format("2006-01-02 15:04:05"))
sleep := start.UnixNano() - now.UnixNano()
time.Sleep(time.Duration(sleep))
}
// Detect Ctrl+C keyboard interruption and set quit signal to quitChan.
func stop(quit chan struct{}) {
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
fmt.Println("\r- Ctrl+C pressed in Terminal")
close(quit)
fmt.Println("Stopped.")
}()
}
// Before the program quit, if scrobble play chan is not empty, save to a temp file.
func windUp(playedChan chan xiami.Track) {
if len(playedChan) > 0 {
if err := app.TempStore(playedChan); err != nil {
log.Println(err)
}
}
}
|
package main
import (
"fmt"
"reflect"
)
type Person struct {
FirstName string
LastName string
Sex string
Age int
}
type Lawer struct {
Person
hasOAB bool
OABnumber int
}
type Medic struct {
Person
CrmNumber int
Field string
}
type Programmer struct {
Person
StackOverFlow bool
ProgrammingLanguages []string
Coffees []string
MeaningOfLifeUiverseAndMore int
}
type People interface {
read() string
speak(say string) string
fight(action string) string
}
func (l Lawer) read() string {
return "Lawer needs a lot of reader"
}
func (l Lawer) speak(say string) string {
// Lawer can change what you say
say = "You said this: ..."
return say
}
func (l Lawer) fight(action string) string {
return "Lawer does not. Lawer run from fight."
}
func (l Lawer) sayMyName() string {
return l.FirstName + " " + l.LastName
}
func main() {
var person People
lawer1 := Lawer{
Person: Person{
FirstName: "Leo",
LastName: "Fonteles",
},
hasOAB: true,
OABnumber: 101,
}
person = lawer1
fmt.Printf("%T\n", person)
fmt.Printf("%v\n", person)
fullName := lawer1.sayMyName()
fmt.Println(fullName)
var lawer2 People = Lawer{
Person: Person{
FirstName: "Leo",
LastName: "Fonteles",
},
hasOAB: true,
OABnumber: 101,
}
fmt.Println(reflect.TypeOf(lawer2).PkgPath(), reflect.TypeOf(lawer2).Name())
fmt.Println(reflect.TypeOf(lawer2).String())
var i People
fmt.Printf("--------------------------------\n")
fmt.Printf("%T\n", i)
fmt.Printf("%v\n", i)
var lawer3 Lawer
fmt.Printf("%T\n", lawer3)
fmt.Printf("%v\n", lawer3)
i = lawer3
fmt.Printf("--------------------------------\n")
fmt.Printf("%T\n", i)
fmt.Printf("%v\n", i)
}
|
package db
import (
"errors"
"fmt"
"os"
"bitbucket.org/bridce/go_exercise2/config"
"github.com/jinzhu/gorm"
"github.com/qor/validations"
)
// DB Global DB connection
var DB *gorm.DB
func init() {
if DB != nil {
return
}
var err error
dbConfig := config.Config.DB
if dbConfig.Adapter == "mysql" {
DB, err = gorm.Open("mysql", fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?parseTime=True&loc=Local", dbConfig.User, dbConfig.Password, dbConfig.Host, dbConfig.Port, dbConfig.Name))
} else if dbConfig.Adapter == "cockroach" {
if dbConfig.SslMode == "disable" {
DB, err = gorm.Open("postgres", fmt.Sprintf("postgresql://%v%v@%v:%v/%v?application_name=cockroach&sslmode=disable", dbConfig.User, dbConfig.Password, dbConfig.Host, dbConfig.Port, dbConfig.Name))
} else if dbConfig.SslMode == "verify-ca" {
DB, err = gorm.Open("postgres", fmt.Sprintf("postgresql://%v%v@%v:%v/%v?application_name=cockroach&sslmode=verify-ca&sslrootcert=certs/ca.crt", dbConfig.User, dbConfig.Password, dbConfig.Host, dbConfig.Port, dbConfig.Name))
} else {
panic(fmt.Errorf("Unsupported SSL Mode: ", dbConfig.SslMode))
}
} else if dbConfig.Adapter == "postgres" {
if dbConfig.SslMode == "disable" {
DB, err = gorm.Open("postgres", fmt.Sprintf("postgres://%v:%v@%v/%v?sslmode=disable", dbConfig.User, dbConfig.Password, dbConfig.Host, dbConfig.Name))
} else {
panic(fmt.Errorf("Unsupported SSL Mode: ", dbConfig.SslMode))
}
} else if dbConfig.Adapter == "sqlite" {
DB, err = gorm.Open("sqlite3", fmt.Sprintf("%v/%v", os.TempDir(), dbConfig.Name))
} else {
panic(errors.New("not supported database adapter"))
}
if err == nil {
if os.Getenv("DEBUG") == "TRUE" {
DB.LogMode(true)
}
validations.RegisterCallbacks(DB)
} else {
panic(err)
}
}
|
package main
// Best: O(n^2) time | O(1) space
// Average: O(n^2) time | O(1) space
// Worst: O(n^2) time | O(1) space
func SelectionSort(array []int) []int {
currentIndex := 0
for currentIndex < len(array)-1 {
smallestIndex := currentIndex
for i := currentIndex + 1; i < len(array); i++ {
if array[smallestIndex] > array[i] {
smallestIndex = i
}
}
array[currentIndex], array[smallestIndex] = array[smallestIndex], array[currentIndex]
currentIndex += 1
}
return array
} |
package routes
import (
"log-collector/app/entity"
"log-collector/config"
"log-collector/middleware"
"github.com/gin-gonic/contrib/gzip"
"github.com/gin-gonic/gin"
)
var (
eventEntity entity.EventInterface
)
type Router struct {
}
func GetEngine() *gin.Engine {
eventEntity = entity.NewEventEntity()
// Set up gin
gin.SetMode(config.AppMode)
app := gin.New()
app.Use(gzip.Gzip(gzip.DefaultCompression))
app.Use(middleware.CORS())
// Setup router
router := &Router{}
group := app.Group("/logs")
group.POST("", router.ReciveEventLog)
return app
}
|
package certifacte
import (
"bytes"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"math/big"
"os"
"time"
"crypto/sha256"
"github.com/Sirupsen/logrus"
)
var log = logrus.New()
type ecdsaGen struct {
curve elliptic.Curve
}
func (e *ecdsaGen) KeyGen() (key *ecdsa.PrivateKey, err error) {
privKey, err := ecdsa.GenerateKey(e.curve, rand.Reader)
if err != nil {
return nil, err
}
return privKey, nil
}
func encode(privateKey *ecdsa.PrivateKey, publicKey *ecdsa.PublicKey) (string, string) {
x509Encoded, _ := x509.MarshalECPrivateKey(privateKey)
pemEncoded := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: x509Encoded})
x509EncodedPub, _ := x509.MarshalPKIXPublicKey(publicKey)
pemEncodedPub := pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: x509EncodedPub})
// 将ec 密钥写入到 pem文件里
keypem, _ := os.OpenFile("ec-key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
pem.Encode(keypem, &pem.Block{Type: "EC PRIVATE KEY", Bytes: x509Encoded})
return string(pemEncoded), string(pemEncodedPub)
}
func decode(pemEncoded string, pemEncodedPub string) (*ecdsa.PrivateKey, *ecdsa.PublicKey) {
block, _ := pem.Decode([]byte(pemEncoded))
x509Encoded := block.Bytes
privateKey, _ := x509.ParseECPrivateKey(x509Encoded)
blockPub, _ := pem.Decode([]byte(pemEncodedPub))
x509EncodedPub := blockPub.Bytes
genericPublicKey, _ := x509.ParsePKIXPublicKey(x509EncodedPub)
publicKey := genericPublicKey.(*ecdsa.PublicKey)
return privateKey, publicKey
}
func checkError(err error) {
if err != nil {
log.Panic(err)
}
}
// 根据ecdsa密钥生成特征标识码
func priKeyHash(priKey *ecdsa.PrivateKey) []byte {
hash := sha256.New()
hash.Write(elliptic.Marshal(priKey.Curve, priKey.PublicKey.X, priKey.PublicKey.Y))
return hash.Sum(nil)
}
//生成根证书
func CA() {
// 生成ecdsa
e := &ecdsaGen{curve: elliptic.P256()}
priKey, _ := e.KeyGen()
priKeyEncode, err := x509.MarshalECPrivateKey(priKey)
checkError(err)
// 保存到pem文件
f, err := os.Create("ec.pem")
checkError(err)
pem.Encode(f, &pem.Block{Type: "EC PRIVATE KEY", Bytes: priKeyEncode})
f.Close()
pubKey := priKey.Public()
// Encode public key
//raw, err := x509.MarshalPKIXPublicKey(pubKey)
//checkError(err)
//log.Info(raw)
// 自签
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, _ := rand.Int(rand.Reader, serialNumberLimit)
expiry := 365 * 24 * time.Hour
notBefore := time.Now().Add(-5 * time.Minute).UTC()
template := x509.Certificate{
SerialNumber: serialNumber,
NotBefore: notBefore,
NotAfter: notBefore.Add(expiry).UTC(),
BasicConstraintsValid: true,
IsCA: true,
KeyUsage: x509.KeyUsageDigitalSignature |
x509.KeyUsageKeyEncipherment | x509.KeyUsageCertSign |
x509.KeyUsageCRLSign,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
Subject: pkix.Name{
Country: []string{"CN"},
Locality: []string{"zhongguancun"},
Province: []string{"Beijing"},
OrganizationalUnit: []string{"tect"},
Organization: []string{"paradise"},
StreetAddress: []string{"street", "address", "demo"},
PostalCode: []string{"310000"},
CommonName: "demo.example.com",
},
}
template.SubjectKeyId = priKeyHash(priKey)
x509certEncode, err := x509.CreateCertificate(rand.Reader, &template, &template, pubKey, priKey)
checkError(err)
crt, err := os.Create("cert.crt")
checkError(err)
pem.Encode(crt, &pem.Block{Type: "CERTIFICATE", Bytes: x509certEncode})
crt.Close()
}
//生成私钥
//func Client(x509certEncode []byte,priKey *ecdsa.PrivateKey,
func Client(clientKey string,
country, locality, province, orgunit, org, street, postalcode []string,
commonName string) string {
// 使用bob的密钥进行证书签名
bobf, err := os.Create("bob.pem")
bobf.Write([]byte(clientKey))
checkError(err)
block, _ := pem.Decode([]byte(clientKey))
bobPriKey, err := x509.ParseECPrivateKey(block.Bytes)
bobPubKey := bobPriKey.Public()
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
//serialNumber, _ := rand.Int(rand.Reader, serialNumberLimit)
expiry := 365 * 24 * time.Hour
notBefore := time.Now().Add(-5 * time.Minute).UTC()
bobSerialNumber, _ := rand.Int(rand.Reader, serialNumberLimit)
notBefore = time.Now().Add(-5 * time.Minute).UTC()
bobTemplate := x509.Certificate{
SerialNumber: bobSerialNumber,
NotBefore: notBefore,
NotAfter: notBefore.Add(expiry).UTC(),
BasicConstraintsValid: true,
IsCA: false,
KeyUsage: x509.KeyUsageDigitalSignature |
x509.KeyUsageKeyEncipherment | x509.KeyUsageCertSign |
x509.KeyUsageCRLSign,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
Subject: pkix.Name{
Country: country,
Locality: locality,
Province: province,
OrganizationalUnit: orgunit,
Organization: org,
StreetAddress: street,
PostalCode: postalcode,
CommonName: commonName,
},
}
bobTemplate.SubjectKeyId = priKeyHash(bobPriKey)
crt, err := os.Open("cert.crt")
defer crt.Close()
buf := make([]byte, 2048)
n, err := crt.Read(buf)
//fmt.Println(string(buf[:n]))
block, _ = pem.Decode([]byte(buf[:n]))
//here
x509certEncode := block.Bytes
//priKey, _ := x509.ParseECPrivateKey(x509certEncode)
parent, err := x509.ParseCertificate(x509certEncode)
checkError(err)
pri, err := os.Open("ec.pem")
defer pri.Close()
n, err = pri.Read(buf)
//fmt.Println(string(buf[:n]))
block, _ = pem.Decode([]byte(buf[:n]))
priKey, err := x509.ParseECPrivateKey(block.Bytes)
/*
e := &ecdsaGen{curve: elliptic.P256()}
priKey, _ := e.KeyGen()
priKeyEncode, err := x509.MarshalECPrivateKey(priKey)
*/
checkError(err)
//pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
log.Fatal(err)
}
bobCertEncode, err := x509.CreateCertificate(rand.Reader, &bobTemplate, parent, bobPubKey, priKey)
checkError(err)
bcrt, _ := os.Create("bob.crt")
bufcrt := new(bytes.Buffer)
pem.Encode(bufcrt, &pem.Block{Type: "CERTIFICATE", Bytes: bobCertEncode})
bcrt.Write(bufcrt.Bytes())
bcrt.Close()
log.Println("new crt:\n", bufcrt)
return bufcrt.String()
}
//验证证书
func Verify(rootPEM, certPEM string) (bool, error) {
// Verifying with a custom list of root certificates.
log.Println("verifying")
roots := x509.NewCertPool()
ok := roots.AppendCertsFromPEM([]byte(rootPEM))
if !ok {
return false, errors.New("failed to parse root certificate")
}
block, _ := pem.Decode([]byte(certPEM))
if block == nil {
return false, errors.New("failed to parse root certificate")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return false, errors.New("failed to parse certificate: " + err.Error())
}
opts := x509.VerifyOptions{
Roots: roots,
}
if _, err := cert.Verify(opts); err != nil {
return false, errors.New("failed to verify certificate: " + err.Error())
}
return true, nil
}
|
package main
import (
"bufio"
"bytes"
"fmt"
"os"
"unicode"
"unicode/utf8"
)
func main() {
reader := bufio.NewReader(os.Stdin)
line, err := reader.ReadBytes('\n')
if err != nil {
panic(err)
}
line = bytes.TrimRight(line, "\r\n")
input := string(line)
// fmt.Println(input)
fmt.Println("number of bytes", len(input))
fmt.Println("number of runes", utf8.RuneCountInString(input))
letterCounter, spaceCounter, digitCounter, chineseCounter, otherCounter := 0, 0, 0, 0, 0
for _, r := range input {
// fmt.Printf("%d %v %T %s\n", i, r, r, string(r))
if 'a' <= r && r <= 'z' || 'A' <= r && r <= 'Z' {
letterCounter++
} else if unicode.IsSpace(r) {
spaceCounter++
} else if unicode.IsDigit(r) {
digitCounter++
} else if unicode.Is(unicode.Scripts["Han"], r) {
chineseCounter++
} else {
otherCounter++
}
}
total := letterCounter + spaceCounter + digitCounter + chineseCounter + otherCounter
if total != utf8.RuneCountInString(input) {
panic("error")
}
fmt.Printf("total %d, letter %d, space %d, digit %d, chinese %d, other %d\n", total, letterCounter, spaceCounter, digitCounter, chineseCounter, otherCounter)
}
|
package main
import (
"fmt"
"strconv"
)
func main() {
data := "Golang"
sv, err := strconv.Atoi(data)
if err == nil {
fmt.Printf("%T, %v", sv, sv)
} else {
fmt.Println(err)
}
}
|
package resolv
import (
"testing"
"github.com/miekg/dns"
)
func TestDo(t *testing.T) {
r := New()
rrs, _, dnssec, err := r.Do("example.org.", dns.TypeSOA)
if err != nil {
t.Fatal(err)
}
if len(rrs) != 1 {
t.Errorf("expected 1 SOA RR, got %d", len(rrs))
}
soa := rrs[0]
if _, ok := soa.(*dns.SOA); !ok {
t.Errorf("expected SOA record, got %t", soa)
}
if !dnssec {
t.Errorf("expected RRSIG, got none")
}
}
|
package cmd
import (
"fmt"
"generate/version"
"github.com/spf13/cobra"
"os"
)
var rootCmd = &cobra.Command{
Use: "generate",
Short: "generate is a very fast code generator for webtable",
Long: `generate is a very fast code generator for webtable`,
Run: func(cmd *cobra.Command, args []string) {
version.ShowVersion()
fmt.Println("please use child Command. -h your will get more detail")
},
}
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
|
package messages
import (
"encoding/json"
"fmt"
log "github.com/sirupsen/logrus"
"net/http"
"strconv"
"time"
)
type MessageSender interface {
SendMessage(title string, message string) error
}
type CountsReceiver interface {
GetCountsByTimeFrame(from time.Time, to time.Time) ([]StatusCount, error)
}
type MessageSenderController struct {
MessageSender MessageSender
}
func NewMessageSenderController(ms MessageSender) *MessageSenderController {
return &MessageSenderController{MessageSender: ms}
}
type CountsReceiverController struct {
CountsReceiver CountsReceiver
}
func NewCountsReceiverController(cr CountsReceiver) *CountsReceiverController {
return &CountsReceiverController{CountsReceiver: cr}
}
type postMessageRequest struct {
Title string `json:"title"`
Message string `json:"message"`
}
func (msc MessageSenderController) PostMessage(w http.ResponseWriter, req *http.Request) {
req.Body = http.MaxBytesReader(w, req.Body, 1048576)
dec := json.NewDecoder(req.Body)
dec.DisallowUnknownFields()
var pmr postMessageRequest
err := dec.Decode(&pmr)
if err != nil {
log.Info(fmt.Sprintf("Error when decoding json from client: %v", err))
http.Error(w, fmt.Sprintf("Invalid json received"), http.StatusBadRequest)
return
}
err = msc.MessageSender.SendMessage(pmr.Title, pmr.Message)
if err != nil {
log.Warn(fmt.Sprintf("Error when sending message: %v", err))
http.Error(w, fmt.Sprintf("Error when sending message"), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Successfully sent message")
}
func (crc CountsReceiverController) GetStatusCounts(w http.ResponseWriter, req *http.Request) {
queries := req.URL.Query()
from, errFrom := timeFromTimeStampStr(queries.Get("from"))
to, errTo := timeFromTimeStampStr(queries.Get("to"))
if errFrom != nil || errTo != nil {
log.Info(fmt.Sprintf("Error when parsing query values from from client: %v, %v", errFrom, errTo))
http.Error(w, fmt.Sprintf("No `from` or `to` query params receieved"), http.StatusBadRequest)
return
}
counts, err := crc.CountsReceiver.GetCountsByTimeFrame(from, to)
if err != nil {
log.Warn(fmt.Sprintf("Error when querying db for counts: %v", err))
http.Error(w, fmt.Sprintf("Failed to query counts"), http.StatusInternalServerError)
return
}
jData, err := json.Marshal(counts)
if err != nil {
log.Warn(fmt.Sprintf("Error when encoding counst: %v", err))
http.Error(w, fmt.Sprintf("Failed to create json"), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
w.Write(jData)
}
func timeFromTimeStampStr(stamp string) (time.Time, error) {
integer, err := strconv.ParseInt(stamp, 10, 64)
if err != nil {
return time.Now(), err
}
return time.Unix(integer/1000, (integer%1000)*1000000), nil
}
|
package aliyunfcgoruntime
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
)
type Credentials struct {
AccessKeyID string
AccessKeySecret string
SecurityToken string
}
type FunctionMeta struct {
Name string
Handler string
Memory int
Timeout int
Initializer string
InitializationTimeout int
}
type ServiceMeta struct {
ServiceName string
LogProject string
LogStore string
Qualifier string
VersionID string
}
type FCContext struct {
RequestID string
Credentials Credentials
Function FunctionMeta
Service ServiceMeta
Region string
AccountID string
RetryCount int
Req *http.Request
Log func(map[string]interface{})
}
func log(data map[string]interface{}) {
j, _ := json.Marshal(data)
if j != nil {
fmt.Println(string(j))
}
}
func NewFromContext(req *http.Request) *FCContext {
mStr := req.Header.Get(fcFunctionMemory)
m, err := strconv.Atoi(mStr)
if err != nil {
m = -1
}
tStr := req.Header.Get(fcFunctionTimeout)
t, err := strconv.Atoi(tStr)
if err != nil {
t = -1
}
itStr := req.Header.Get(fcInitializationTimeout)
it, err := strconv.Atoi(itStr)
if err != nil {
it = -1
}
retryStr := req.Header.Get(fcRetryCount)
retryCount, err := strconv.Atoi(retryStr)
if err != nil {
retryCount = 0
}
ctx := &FCContext{
RequestID: req.Header.Get(fcRequestID),
Credentials: Credentials{
AccessKeyID: req.Header.Get(fcAccessKeyID),
AccessKeySecret: req.Header.Get(fcAccessKeySecret),
SecurityToken: req.Header.Get(fcSecurityToken),
},
Function: FunctionMeta{
Name: req.Header.Get(fcFunctionName),
Handler: req.Header.Get(fcFunctionHandler),
Memory: m,
Timeout: t,
Initializer: req.Header.Get(fcFunctionInitializer),
InitializationTimeout: it,
},
Service: ServiceMeta{
ServiceName: req.Header.Get(fcServiceName),
LogProject: req.Header.Get(fcServiceLogProject),
LogStore: req.Header.Get(fcServiceLogstore),
Qualifier: req.Header.Get(fcQualifier),
VersionID: req.Header.Get(fcVersionID),
},
Region: req.Header.Get(fcRegion),
AccountID: req.Header.Get(fcAccountID),
RetryCount: retryCount,
Req: req,
Log: log,
}
return ctx
}
|
package goforce
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
type Requester interface {
URL() string
RequestBody() map[string]interface{}
}
type Response struct {
Status string
ErrorCode string
Message string
Data interface{}
}
type ResponseError struct {
ErrorCode string
Message string
}
// Represents a request
type Request struct {
ServiceURL string
Fields map[string]interface{}
}
// Get request body from Request struct
func (r *Request) RequestBody() map[string]interface{} {
return r.Fields
}
func (r *Request) URL() string {
return r.ServiceURL
}
func (force *ForceAPI) Request(method string, requester Requester) (*Response, error) {
if method == "GET" {
req, err := force.createGETRequest(requester)
if err != nil {
return nil, err
}
resp, err := force.createResponse(req)
if err != nil {
return nil, err
}
return resp, nil
} else if method == "POST" {
req, err := force.createPostRequest(requester)
if err != nil {
return nil, err
}
resp, err := force.createResponse(req)
if err != nil {
return nil, err
}
return resp, nil
} else if method == "PUT" {
req, err := force.createPutRequest(requester)
if err != nil {
return nil, err
}
resp, err := force.createResponse(req)
if err != nil {
return nil, err
}
return resp, nil
} else {
return nil, fmt.Errorf("Method is not supported")
}
}
func (force *ForceAPI) createGETRequest(requester Requester) (*http.Request, error) {
v := url.Values{}
var q string
for key, val := range requester.RequestBody() {
fmt.Println(key, val)
v.Add(key, fmt.Sprintf("%v", val))
q = v.Encode()
}
url := force.instanceURL + requester.URL() + "?" + q
fmt.Println(url)
request, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, fmt.Errorf("createGETRequest, Error on request: %v", err)
}
request.Header.Add("Accept", "application/json")
request.Header.Add("Content-Type", "application/json")
return request, nil
}
func (force *ForceAPI) createPostRequest(requester Requester) (*http.Request, error) {
url := force.instanceURL + requester.URL()
body, err := json.Marshal(requester.RequestBody())
if err != nil {
return nil, err
}
request, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(body))
if err != nil {
return nil, err
}
request.Header.Add("Accept", "application/json")
request.Header.Add("Content-Type", "application/json")
// r.dml.session.AuthorizationHeader(request)
return request, nil
}
func (force *ForceAPI) createPutRequest(requester Requester) (*http.Request, error) {
url := force.instanceURL + requester.URL()
body, err := json.Marshal(requester.RequestBody())
if err != nil {
return nil, err
}
request, err := http.NewRequest(http.MethodPut, url, bytes.NewReader(body))
if err != nil {
return nil, err
}
request.Header.Add("Accept", "application/json")
request.Header.Add("Content-Type", "application/json")
// r.dml.session.AuthorizationHeader(request)
return request, nil
}
func (force *ForceAPI) createResponse(request *http.Request) (*Response, error) {
response, err := force.client.Do(request)
data, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
if response.StatusCode != http.StatusOK {
var respErr ResponseError
err = json.Unmarshal(data, &respErr)
var errMsg error
if err == nil {
errMsg = fmt.Errorf("request response err: %s: %s", respErr.ErrorCode, respErr.Message)
} else {
errMsg = fmt.Errorf("request response err: %d %s", response.StatusCode, response.Status)
}
return nil, errMsg
}
var resp Response
err = json.Unmarshal(data, &resp)
if err != nil {
return nil, err
}
return &resp, nil
}
|
package anagrams
import (
"fmt"
"sort"
"strings"
)
// Sherlock finds all pairs of substrings in the string that are anagrams of each other
// string is between 2 and 100 chars
func Sherlock(s string) int32 {
// Naive approach:
// Find all substrings of s
// if this substring exists in the map already, increase the count
count := 0
for l := 1; l < len(s); l++ {
// Start with small substrings
matches := map[string]int{}
for i := 0; i < len(s)+1-l; i++ {
sub := s[i : i+l]
// Sort the characters in this substring alphabetically
// so it will match any anagrams
splitSub := strings.Split(sub, "")
sort.Strings(splitSub)
sortedSub := strings.Join(splitSub, "")
if n, ok := matches[sortedSub]; ok {
// If 2 matches already exist, we have 2 new possible pairs
// and so on
count += n
matches[sortedSub]++
} else {
matches[sortedSub] = 1
}
}
}
return int32(count)
}
// 31619 ns/op 5920 B/op 180 allocs/op
// outer loop n times
// inner loop n-1 times
// inner loop includes a sort which is O(n log n)
// So approach is probably n^2 log n
// Is there a better way to account for anagrams?
// Signature creates an alphabetic signature (hash) for a substring
// Rather than sorting it.
func Signature(s string) int32 {
// Naive approach:
// Find all substrings of s
// if this substring exists in the map already, increase the count
count := 0
for l := 1; l < len(s); l++ {
// Start with small substrings
matches := map[string]int{}
for i := 0; i < len(s)+1-l; i++ {
sub := s[i : i+l]
// Sort the characters in this substring alphabetically
// so it will match any anagrams
sig := signature(sub)
if n, ok := matches[sig]; ok {
// If 2 matches already exist, we have 2 new possible pairs
// and so on
count += n
matches[sig]++
} else {
matches[sig] = 1
}
}
}
return int32(count)
}
// Signature version is even slower than the sort version
func signature(s string) string {
alpha := make([]int, 26)
for _, ch := range s {
ord := int(ch) - int('a')
alpha[ord]++
}
return fmt.Sprint(alpha)
}
|
package main
import (
"io"
"log"
"net"
"os"
)
// net包提供了可移植的网络I/O接口,包括TCP/IP、UDP、域名解析和Unix域socket
// 虽然本包提供了对网络原语的访问,大部分使用者只需要Dial、Listen和Accept函数提供的基本接口;以及相关的Conn和Listener接口
// crypto/tls包提供了相同的接口和类似的Dial和Listen函数
func main() {
// 创建服务
exampleServer()
// 客户端请求
exampleClient()
}
func exampleServer() {
// 创建tcp监听
// network必须是"tcp", "tcp4", "tcp6", "unix", "unixpacket".
l, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatal(err)
}
defer l.Close()
for {
// 等待连接
conn, err := l.Accept()
if err != nil {
log.Fatal(err)
}
go func(c net.Conn) {
// 拷贝接收内容并输出
io.Copy(os.Stdout, c)
// 关闭链接
c.Close()
}(conn)
}
}
func exampleClient() {
// 创建tcp连接
conn, err := net.Dial("tcp", ":8080")
if err != nil {
log.Fatal(err)
}
// 写入内容
if _, err := conn.Write([]byte("Hello World!")); err != nil {
log.Fatal(err)
}
// 关闭连接
if err := conn.Close(); err != nil {
log.Fatal(err)
}
}
|
package main
import (
"github.com/thesephist/xin/cmd"
)
// Xin CLI
func main() {
cmd.Execute()
}
|
package app
import (
"github.com/Unknwon/com"
"gopkg.in/ini.v1"
"os"
)
const CONFIG_FILE = "config.ini"
type Config struct {
Name string
Version string
Date string
Http ConfigHttp
Db ConfigDb
IsNew bool `ini:"-"`
}
type ConfigHttp struct {
Host string
Port string
Protocol string
}
type ConfigDb struct {
Driver string
DSN string
}
func NewConfig() *Config {
config := &Config{
Name: "PUGO",
Version: "2.0",
Date: "20151018",
Http: ConfigHttp{
Host: "0.0.0.0",
Port: "9999",
Protocol: "http",
},
Db: ConfigDb{
Driver: "tidb",
DSN: "boltdb://data.db/tidb",
},
}
return config
}
// Sync saves config to file.
// If config file is not exist, it creates new file and marks *Config is new file.
func (c *Config) Sync() error {
// if config file exist, read it
if com.IsFile(CONFIG_FILE) {
file, err := ini.Load(CONFIG_FILE)
if err != nil {
return err
}
return file.MapTo(c)
}
// create file
c.IsNew = true
file := ini.Empty()
if err := file.ReflectFrom(c); err != nil {
return err
}
f, err := os.OpenFile(CONFIG_FILE, os.O_CREATE|os.O_RDWR|os.O_TRUNC, os.ModePerm)
if err != nil {
return err
}
_, err = file.WriteToIndent(f, " ")
return err
}
|
package timer
import (
"strings"
"fmt"
"strconv"
"math"
"time"
)
// Field name | Mandatory? | Allowed values | Allowed special characters
// ---------- | ---------- | -------------- | --------------------------
// Seconds | No | 0-59 | * / , -
// Minutes | Yes | 0-59 | * / , -
// Hours | Yes | 0-23 | * / , -
// Day of month | Yes | 1-31 | * / , -
// Month | Yes | 1-12 | * / , -
// Day of week | Yes | 0-6 | * / , -
type CronExpr struct {
sec uint64
min uint64
hour uint64
dom uint64
month uint64
dow uint64
}
func NewCronExpr(expr string)(cronExpr *CronExpr,err error){
fields := strings.Fields(expr)
if len(fields) != 5 && len(fields) != 6{
err = fmt.Errorf("invalid expr %v:expected 5 or 6 fields, got %v",expr,len(fields))
return
}
//add sec 0
if len(fields) == 5 {
fields = append([]string{"0"},fields...)
}
cronExpr = new(CronExpr)
//Seconds
cronExpr.sec,err = parseCronField(fields[0],0,59)
if err != nil {
goto onError
}
//Minutes
cronExpr.min,err = parseCronField(fields[1],0,59)
if err != nil {
goto onError
}
//Hours
cronExpr.hour,err = parseCronField(fields[2],0,23)
if err != nil {
goto onError
}
//Day of month
cronExpr.dom,err = parseCronField(fields[3],1,31)
if err != nil {
goto onError
}
//Month
cronExpr.month,err = parseCronField(fields[4],1,12)
if err != nil{
goto onError
}
//Day of week
cronExpr.dow,err = parseCronField(fields[5],0,6)
if err != nil {
goto onError
}
return
onError:
err = fmt.Errorf("invalid expr %v: %v",expr, err)
return
}
// 1. *
// 2. num
// 3. num-num
// 4. */num
// 5. num/num (means num-max/num)
// 6. num-num/num
func parseCronField(field string,min,max int)(cronField uint64,err error){
fields := strings.Split(field,",")
for _, field := range fields {
rangeAndIncr := strings.Split(field,"/")
if len(rangeAndIncr) > 2 {
err = fmt.Errorf("too many slashes:%v",field)
return
}
//range
startAndEnd := strings.Split(rangeAndIncr[0],"-")
if len(startAndEnd) > 2 {
err = fmt.Errorf("too many hyphens: %v",rangeAndIncr[0])
return
}
var start,end int
if startAndEnd[0] == "*" {
if len(startAndEnd) != 1 {
err =fmt.Errorf("invalid range: %v",rangeAndIncr[0])
return
}
start = min
end = max
}else {
//start
start,err = strconv.Atoi(startAndEnd[0])
if err != nil {
err = fmt.Errorf("invalid range: %v",rangeAndIncr[0])
return
}
//end
if len(startAndEnd) == 1 {
if len(rangeAndIncr) == 2 {
end = max
}else{
end = start
}
}else{
end,err = strconv.Atoi(startAndEnd[1])
if err != nil {
err = fmt.Errorf("invalid range: %v",rangeAndIncr[0])
return
}
}
}
if start > end {
err = fmt.Errorf("invalid range: %v",rangeAndIncr[0])
return
}
if start < min {
fmt.Println(start,min)
err = fmt.Errorf("out of range [%v, %v]: %v",min,max,rangeAndIncr[0])
return
}
if end > max {
err = fmt.Errorf("out of range [%v, %v]: %v",min,max,rangeAndIncr[0])
return
}
//increment
var incr int
if len(rangeAndIncr) == 1 {
incr = 1
}else{
incr,err = strconv.Atoi(rangeAndIncr[1])
if err != nil {
err = fmt.Errorf("invalid increment: %v",rangeAndIncr[1])
return
}
if incr <= 0 {
err = fmt.Errorf("invalid increment: %v",rangeAndIncr[1])
return
}
}
//cronField
if incr == 1 {
cronField |= ^(math.MaxUint64<< uint(end+1)) & (math.MaxUint64 << uint(start))
}else{
for i:= start;i<=end;i += incr {
cronField |= 1<<uint(i)
}
}
}
return
}
func (e *CronExpr)matchDay(t time.Time)bool{
// day-of-month blank
if e.dom == 0xfffffffe {
return 1<<uint(t.Weekday())&e.dow != 0
}
// day-of-week blank
if e.dow == 0x7f {
return 1<<uint(t.Day())&e.dom != 0
}
return 1<<uint(t.Weekday())&e.dow != 0 ||
1<<uint(t.Day())&e.dom != 0
}
// goroutine safe
func (e *CronExpr) Next(t time.Time) time.Time {
// the upcoming second
t = t.Truncate(time.Second).Add(time.Second)
year := t.Year()
initFlag := false
retry:
// Year
if t.Year() > year+1 {
return time.Time{}
}
// Month
for 1<<uint(t.Month())&e.month == 0 {
if !initFlag {
initFlag = true
t = time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location())
}
t = t.AddDate(0, 1, 0)
if t.Month() == time.January {
goto retry
}
}
// Day
for !e.matchDay(t) {
if !initFlag {
initFlag = true
t = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
}
t = t.AddDate(0, 0, 1)
if t.Day() == 1 {
goto retry
}
}
// Hours
for 1<<uint(t.Hour())&e.hour == 0 {
if !initFlag {
initFlag = true
t = t.Truncate(time.Hour)
}
t = t.Add(time.Hour)
if t.Hour() == 0 {
goto retry
}
}
// Minutes
for 1<<uint(t.Minute())&e.min == 0 {
if !initFlag {
initFlag = true
t = t.Truncate(time.Minute)
}
t = t.Add(time.Minute)
if t.Minute() == 0 {
goto retry
}
}
// Seconds
for 1<<uint(t.Second())&e.sec == 0 {
if !initFlag {
initFlag = true
}
t = t.Add(time.Second)
if t.Second() == 0 {
goto retry
}
}
return t
}
//time.Truncate和time.Round类似,都是四舍五入
//但是前者返回的是早于t时间的,后者返回的是晚于t时间的 |
// Copyright (C) 2015 Miquel Sabaté Solà <mikisabate@gmail.com>
// This file is licensed under the MIT license.
// See the LICENSE file.
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestHighlightSvn(t *testing.T) {
// Empty.
s := svn{}
r := s.highlight("")
assert.Empty(t, r)
// Same string.
r = s.highlight("This is some output")
assert.Equal(t, r, "This is some output")
// Revision.
r = s.highlight("At revision 1234.")
assert.Equal(t, r, "At revision <b>1234</b>.")
r = s.highlight("Updated to revision 228919.")
assert.Equal(t, r, "Updated to revision <b>228919</b>.")
// Changes.
r = s.highlight("A this/is/some/file.cpp")
expected := "<span class=\"green\">A </span>this/is/some/file.cpp"
assert.Equal(t, r, expected)
r = s.highlight("U this/is/some/file.cpp")
expected = "<span class=\"magenta\">U </span>this/is/some/file.cpp"
assert.Equal(t, r, expected)
r = s.highlight("D this/is/some/file.cpp")
expected = "<span class=\"red\">D </span>this/is/some/file.cpp"
assert.Equal(t, r, expected)
// Bad change
r = s.highlight("X this/is/some/file.cpp")
assert.Equal(t, r, "X this/is/some/file.cpp")
}
func TestHighlightGit(t *testing.T) {
// Empty.
g := git{}
r := g.highlight("")
assert.Empty(t, r)
// Same string.
r = g.highlight("This is some output")
assert.Equal(t, r, "This is some output")
// Pluses and minuses.
str := "file.rb | 14 ++++++++++++--"
r = g.highlight(str)
e := "file.rb | <b>14</b> <span class=\"green\">++++++++++++</span>" +
"<span class=\"red\">--</span>"
assert.Equal(t, r, e)
// Just pluses
str = "file.rb | 14 +++++"
e = "file.rb | <b>14</b> <span class=\"green\">+++++</span>"
r = g.highlight(str)
assert.Equal(t, r, e)
// Just minuses
str = "file.rb | 14 -----"
e = "file.rb | <b>14</b> <span class=\"red\">-----</span>"
r = g.highlight(str)
assert.Equal(t, r, e)
// Branches.
str = "9bdb083..3ffffcc master -> origin/master"
e = "9bdb083..3ffffcc <b>master</b> -> <b>origin/master</b>"
r = g.highlight(str)
assert.Equal(t, r, e)
}
|
// Copyright (C) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package value
import (
"math"
"github.com/google/gapid/core/math/interval"
"github.com/google/gapid/gapis/replay/protocol"
)
// Bool is a Value of type TypeBool.
type Bool bool
// Get returns TypeBool and 1 if the Bool is true, otherwise 0.
func (v Bool) Get(PointerResolver) (ty protocol.Type, val uint64, onStack bool) {
if v {
return protocol.Type_Bool, 1, false
} else {
return protocol.Type_Bool, 0, false
}
}
// U8 is a Value of type TypeUint8.
type U8 uint8
// Get returns TypeUint8 and the value zero-extended to a uint64.
func (v U8) Get(PointerResolver) (ty protocol.Type, val uint64, onStack bool) {
return protocol.Type_Uint8, uint64(v), false
}
// S8 is a Value of type TypeInt8.
type S8 int8
// Get returns TypeInt8 and the value sign-extended to a uint64.
func (v S8) Get(PointerResolver) (ty protocol.Type, val uint64, onStack bool) {
return protocol.Type_Int8, uint64(v), false
}
// U16 is a Value of type TypeUint16.
type U16 uint16
// Get returns TypeUint16 and the value zero-extended to a uint64.
func (v U16) Get(PointerResolver) (ty protocol.Type, val uint64, onStack bool) {
return protocol.Type_Uint16, uint64(v), false
}
// S16 is a Value of type TypeInt16.
type S16 int16
// Get returns TypeInt16 and the value sign-extended to a uint64.
func (v S16) Get(PointerResolver) (ty protocol.Type, val uint64, onStack bool) {
return protocol.Type_Int16, uint64(v), false
}
// F32 is a Value of type TypeFloat.
type F32 float32
// Get returns TypeFloat and the IEEE 754 representation of the value packed
// into the low part of a uint64.
func (v F32) Get(PointerResolver) (ty protocol.Type, val uint64, onStack bool) {
return protocol.Type_Float, uint64(math.Float32bits(float32(v))), false
}
// U32 is a Value of type TypeUint32.
type U32 uint32
// Get returns TypeUint32 and the value zero-extended to a uint64.
func (v U32) Get(PointerResolver) (ty protocol.Type, val uint64, onStack bool) {
return protocol.Type_Uint32, uint64(v), false
}
// S32 is a Value of type TypeInt32.
type S32 int32
// Get returns TypeInt32 and the value sign-extended to a uint64.
func (v S32) Get(PointerResolver) (ty protocol.Type, val uint64, onStack bool) {
return protocol.Type_Int32, uint64(v), false
}
// F64 is a Value of type TypeDouble.
type F64 float64
// Get returns TypeDouble and the IEEE 754 representation of the value packed
// into a uint64.
func (v F64) Get(PointerResolver) (ty protocol.Type, val uint64, onStack bool) {
return protocol.Type_Double, math.Float64bits(float64(v)), false
}
// U64 is a Value of type TypeUint64.
type U64 uint64
// Get returns TypeUint64 the value zero-extended to a uint64.
func (v U64) Get(PointerResolver) (ty protocol.Type, val uint64, onStack bool) {
return protocol.Type_Uint64, uint64(v), false
}
// S64 is a Value of type TypeInt64.
type S64 int64
// Get returns TypeInt64 and the value reinterpreted as a uint64.
func (v S64) Get(PointerResolver) (ty protocol.Type, val uint64, onStack bool) {
return protocol.Type_Int64, uint64(v), false
}
// AbsoluteStackPointer represents a pointer on the top of the stack in the
// absolute address-space that will not be altered before being passed to the
// protocol.
type AbsoluteStackPointer struct{}
// Get returns TypeAbsolutePointer and the uint64 value of the absolute pointer.
func (p AbsoluteStackPointer) Get(PointerResolver) (ty protocol.Type, val uint64, onStack bool) {
return protocol.Type_AbsolutePointer, 0, true
}
// Offset returns the sum of the pointer with offset.
func (p AbsoluteStackPointer) Offset(offset uint64) Pointer {
panic("AbsoluteStackPointer.Offset is not implemented")
}
// IsValid returns true for all absolute pointers.
func (p AbsoluteStackPointer) IsValid() bool { return true }
// AbsolutePointer is a pointer in the absolute address-space that will not be
// altered before being passed to the protocol.
type AbsolutePointer uint64
// Get returns TypeAbsolutePointer and the uint64 value of the absolute pointer.
func (p AbsolutePointer) Get(PointerResolver) (ty protocol.Type, val uint64, onStack bool) {
return protocol.Type_AbsolutePointer, uint64(p), false
}
// Offset returns the sum of the pointer with offset.
func (p AbsolutePointer) Offset(offset uint64) Pointer {
return p + AbsolutePointer(offset)
}
// IsValid returns true for all absolute pointers.
func (p AbsolutePointer) IsValid() bool { return true }
// ObservedPointer is a pointer that was observed at capture time.
// Pointers of this type are remapped to an equivalent volatile address-space
// pointer, or absolute address-space pointer before being passed to the
// protocol.
type ObservedPointer uint64
// Get returns the pointer type and the pointer translated to either an
// equivalent volatile address-space pointer or absolute pointer.
func (p ObservedPointer) Get(r PointerResolver) (ty protocol.Type, val uint64, onStack bool) {
ty, val = r.ResolveObservedPointer(p)
return ty, val, false
}
// Offset returns the sum of the pointer with offset.
func (p ObservedPointer) Offset(offset uint64) Pointer {
return p + ObservedPointer(offset)
}
// Anything very low in application address-space is extremely
// unlikely to be a valid pointer.
const FirstValidAddress = 0x1001
var ValidMemoryRanges = interval.U64RangeList{
interval.U64Range{First: FirstValidAddress, Count: math.MaxUint64 - FirstValidAddress},
}
// IsValid returns true if the pointer considered valid. Currently this is a
// test for the pointer being greater than 0x1000 as low addresses are likely
// to be a wrong interpretation of the value. This may change in the future.
func (p ObservedPointer) IsValid() bool {
return p >= FirstValidAddress
}
// PointerIndex is an index to a pointer in the pointer table.
type PointerIndex uint64
// Get returns TypeVolatilePointer and the volatile address of the pointer.
func (p PointerIndex) Get(r PointerResolver) (ty protocol.Type, val uint64, onStack bool) {
ty, val = r.ResolvePointerIndex(p)
return ty, val, false
}
// Offset returns the sum of the pointer index with offset.
func (p PointerIndex) Offset(offset uint64) Pointer {
return p + PointerIndex(offset)
}
// IsValid returns true.
func (p PointerIndex) IsValid() bool {
return true
}
// VolatilePointer is a pointer to the volatile address-space.
// Unlike ObservedPointer, there is no remapping.
type VolatilePointer uint64
// Get returns TypeVolatilePointer and the uint64 value of the pointer in
// volatile address-space.
func (p VolatilePointer) Get(PointerResolver) (ty protocol.Type, val uint64, onStack bool) {
return protocol.Type_VolatilePointer, uint64(p), false
}
// Offset returns the sum of the pointer with offset.
func (p VolatilePointer) Offset(offset uint64) Pointer {
return p + VolatilePointer(offset)
}
// IsValid returns true.
func (p VolatilePointer) IsValid() bool { return true }
// TemporaryPointer is a pointer to in temporary address-space.
// The temporary address-space sits within a reserved area of the the volatile
// address space and its offset is calculated dynamically.
// TODO: REMOVE
type TemporaryPointer uint64
// Get returns TypeVolatilePointer and the dynamically calculated offset of the
// temporary pointer within volatile address-space.
func (p TemporaryPointer) Get(r PointerResolver) (ty protocol.Type, val uint64, onStack bool) {
return protocol.Type_VolatilePointer, uint64(r.ResolveTemporaryPointer(p)), false
}
// Offset returns the sum of the pointer with offset.
func (p TemporaryPointer) Offset(offset uint64) Pointer {
return p + TemporaryPointer(offset)
}
// IsValid returns true.
func (p TemporaryPointer) IsValid() bool { return true }
// ConstantPointer is a pointer in the constant address-space that will not be
// altered before being passed to the protocol.
type ConstantPointer uint64
// Get returns TypeConstantPointer and the uint64 value of the pointer in constant address-space.
func (p ConstantPointer) Get(PointerResolver) (ty protocol.Type, val uint64, onStack bool) {
return protocol.Type_ConstantPointer, uint64(p), false
}
// Offset returns the sum of the pointer with offset.
func (p ConstantPointer) Offset(offset uint64) Pointer {
return p + ConstantPointer(offset)
}
// IsValid returns true.
func (p ConstantPointer) IsValid() bool { return true }
|
package diframeworks
import (
_ "github.com/google/wire/cmd/wire"
)
|
package main
type Weight struct {
val int
cur int
}
type SmoothWeightedRoundRobin struct {
weights []*Weight
}
func NewSmoothWeightedRoundRobin(ws []int) *SmoothWeightedRoundRobin {
var weights []*Weight
for _, w := range ws {
weights = append(weights, &Weight{
val: w,
})
}
return &SmoothWeightedRoundRobin{
weights: weights,
}
}
func (s *SmoothWeightedRoundRobin) NextIndex() int {
var w *Weight
var total int
best := -1
for i := 0; i < len(s.weights); i++ {
w = s.weights[i]
w.cur += w.val
total += w.val
if best == -1 || w.cur > s.weights[best].cur {
best = i
}
}
s.weights[best].cur -= total
return best
}
|
package xmodel
import "github.com/ionous/sashimi/util/ident"
type EnumProperty struct {
Id ident.Id `json:"id"` // property id
Name string `json:"name"` // property name
Enumeration
}
func (enum EnumProperty) GetId() ident.Id {
return enum.Id
}
func (enum EnumProperty) GetName() string {
return enum.Name
}
|
package controllers
import (
"encoding/json"
"github.com/gorilla/mux"
"go-contacts/models"
utility "go-contacts/utils"
"log"
"net/http"
"strconv"
)
var CreateContact = func(w http.ResponseWriter, r *http.Request) {
user := r.Context().Value("user").(uint) //getting value from interface{} type
contact := &models.Contact{}
err := json.NewDecoder(r.Body).Decode(contact)
if err != nil {
utility.Respond(w, utility.Message(false, "Error while decoding request body"))
return
}
contact.UserId = user
resp := contact.Create()
utility.Respond(w, resp)
}
//var BasicauthCreateContact = func(w http.ResponseWriter, r *http.Request) {
//
// user := r.Context().Value("user").(uint) //getting value from interface{} type
// contact := &models.Contact{}
//
// err := json.NewDecoder(r.Body).Decode(contact)
// if err != nil {
// utility.Respond(w, utility.Message(false, "Error while decoding request body"))
// return
// }
//
// contact.UserId = user
// resp := contact.Create()
// utility.Respond(w, resp)
//}
var GetContactsFor = func(w http.ResponseWriter, r *http.Request) {
//user_id := r.Context().Value("user").(uint) // getting value from interface{} type
log.Println(" GetContactsFor ....")
params := mux.Vars(r)
id, _ := strconv.ParseUint(params["id"], 10, 32)
data := models.GetContacts(uint(id))
resp := utility.Message(true, "success")
resp["data"] = data
utility.Respond(w, resp)
}
|
package ds
import (
"testing"
)
func TestQueue(t *testing.T) {
q := NewQueue()
if q == nil {
t.Fatal("can't create a queue")
}
for i := 0; i < 1000000; i++ {
q.Put(i)
if q.Size() != 1 {
t.Fatalf("Size() failed with error:%v, expected=%v", q.Size(), 1)
}
el, err := q.Get()
if err != nil {
t.Fatalf("Get() failed with error:empty queue i(%v)", i)
}
if el != i {
t.Fatalf("Get() failed with error:el(%v) not equal to i(%v)", el, i)
}
}
q.Put(1)
q.Put(2)
if q.Size() != 2 {
t.Fatalf("Size() failed with error:%v, expected=%v", q.Size(), 2)
}
q.Clear()
if q.Size() != 0 {
t.Fatalf("Size() failed with error:%v, expected=%v", q.Size(), 0)
}
el, err := q.Get()
if err == nil {
t.Fatalf("Get() failed with error:get element(%v) from empty queue", el)
}
// test struct queue
type testData struct {
name string
age int
}
td := testData{name: "n", age: 1}
q.Put(td)
el2, err := q.Get()
if err != nil {
t.Fatalf("Get() struct failed with error:%v", err)
}
data := el2.(testData)
if data.name != td.name || data.age != td.age {
t.Fatalf("Get() struct failed with error:got=%v, expected=%v", data, el2)
}
}
|
package main
import (
"fmt"
"time"
"./resources/product"
"./server"
)
func main() {
fmt.Println(time.Now(), "Shopping Manager api start")
loadResourceHandler()
server.Start()
}
// loadResourceHandler is unexported function
// which includes all resources
func loadResourceHandler() {
fmt.Println(time.Now(), "Load resource handler")
product.Handler()
}
|
package files
import (
"fmt"
"github.com/go-on/app"
"net/http"
"os"
"path/filepath"
"strings"
)
func noDirListing(h http.Handler) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/") {
http.NotFound(w, r)
return
}
h.ServeHTTP(w, r)
})
}
type Files struct {
mountPath app.MountPath
fsDir string
fileServer http.Handler
}
func New(mountPath app.MountPath, dir string) *Files {
var p = &Files{}
f, err := os.Stat(dir)
if err != nil {
panic(fmt.Sprintf("can't create fileserver for %#v: directory does not exist", dir))
}
if !f.IsDir() {
panic(fmt.Sprintf("can't create fileserver for %#v: no directory", dir))
}
p.fsDir = dir
p.mountPath = mountPath
p.fileServer = noDirListing(http.FileServer(http.Dir(dir)))
return p
}
// if the file does not exist or is a directory, path is an empty string
func (f *Files) Link(relPath string) (l app.AppLink) {
l.Method = app.GET
// fmt.Printf("path: %#v\n", filepath.Join(f.fsDir, relPath))
fi, err := os.Stat(filepath.Join(f.fsDir, relPath))
if err != nil {
l.Path = "#file-does-not-exist"
return
}
if fi.IsDir() {
l.Path = "#is-directory"
return
}
l.Path = "/" + filepath.Join(string(f.mountPath), relPath)
return
}
func (a *Files) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
a.fileServer.ServeHTTP(rw, r)
}
func (p Files) MountPath() app.MountPath {
return p.mountPath
}
func (p *Files) Protected(authorizer app.Authorizer, authenticator app.Authenticator) app.App {
var pt = &protected{}
pt.Files = p
pt.authorizer = authorizer
pt.authenticator = authenticator
return pt
}
type protected struct {
*Files
authorizer app.Authorizer
authenticator app.Authenticator
}
func (a *protected) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
user := a.authenticator.Authenticate(r)
if user == nil {
rw.WriteHeader(http.StatusForbidden)
return
}
user.Authorizer = a.authorizer
path := app.EndPath{app.Method(r), r.URL.Path}
if !user.Authorize(path) {
rw.WriteHeader(http.StatusForbidden)
return
}
a.Files.ServeHTTP(rw, r)
}
var _ app.App = &Files{}
var _ app.App = &protected{}
|
package main
import "fmt"
func main() {
var key_tmp = []string{"4", "5", "6", "7"}
add(key_tmp)
key_temp2 := key_tmp
key_temp2[0] = "1"
//key_temp2 =append(key_temp2,"456")
key_temp3 := key_tmp[2:]
fmt.Print(key_tmp, key_temp2, key_temp3)
key := []int{1, 2, 3, 4}
fmt.Println(key[len(key)-1])
//验证make 二维slice后,取出后的情况
sliceInt := make([][]int, 4)
firstSlice := sliceInt[0]
firstSlice = append(firstSlice, 2)
fmt.Println(firstSlice)
}
func add(l []string) {
l = append(l, "123")
} |
package helm
import (
"github.com/spf13/cobra"
)
var HelmCmds = &cobra.Command{
Use: "helm",
Aliases: []string{"h"},
Short: "helm command start",
Run: Helm,
}
func Helm(_ *cobra.Command, _ []string) {}
|
package main
import (
"log"
"os"
"os/exec"
"time"
"github.com/meyskens/k8s-openresty-ingress/controller/configgenerate"
"github.com/meyskens/k8s-openresty-ingress/controller/connector"
)
type retryableFunc func(*connector.Client) error
func main() {
log.Println("Starting OpenResty Ingress Controller...")
client, err := connector.NewClient()
if err != nil {
panic(err)
}
ingress, err := client.GetIngresses()
if err != nil {
panic(err)
}
services, err := client.GetServiceMap()
if err != nil {
panic(err)
}
conf := configgenerate.GenerateConfigFileValuesFromIngresses(ingress, services)
configgenerate.WriteFilesFromTemplate(conf, getTemplatePath(), getIngressPath())
log.Println("Starting NGINX")
startNginx()
go runReloadOnChange(client)
watchChanges(client)
}
func startNginx() *os.Process {
nginx := exec.Command("nginx", "-c", "/etc/nginx/nginx.conf")
nginx.Stderr = os.Stderr
nginx.Stdout = os.Stdout
go func() {
err := nginx.Run()
log.Printf("NGINX crashed: %s", err)
time.Sleep(300 * time.Millisecond)
startNginx()
}()
for {
_, err := os.OpenFile("/run/nginx.pid", 'r', 0755)
if err == nil {
break // nginx is running
}
time.Sleep(100 * time.Millisecond)
log.Println("Waiting on nginx.pid")
}
return nginx.Process
}
func getTemplatePath() string {
envPath := os.Getenv("OPENRESTY_TEMPLATEPATH")
if envPath != "" {
return envPath
}
return "../template/ingress.tpl" // Dev fallback
}
func getIngressPath() string {
envPath := os.Getenv("OPENRESTY_INGRESSATH")
if envPath != "" {
return envPath
}
return "../debug-out" // Dev fallback
}
func runAndRetry(fn retryableFunc, client *connector.Client) {
for {
err := fn(client)
if err == nil {
break
}
log.Println("Needs to retry because of", err)
time.Sleep(time.Second) // sleep before retry
}
}
func reload(client *connector.Client) error {
ingress, err := client.GetIngresses()
if err != nil {
return err
}
services, err := client.GetServiceMap()
if err != nil {
return err
}
conf := configgenerate.GenerateConfigFileValuesFromIngresses(ingress, services)
changed, err := configgenerate.WriteFilesFromTemplate(conf, getTemplatePath(), getIngressPath())
if err != nil {
return err
}
if !changed {
return nil
}
nginx := exec.Command("nginx", "-s", "reload")
nginx.Stderr = os.Stderr
nginx.Stdout = os.Stdout
nginx.Run()
return nil
}
|
package main
import "fmt"
//panic触发后之后的执行流不执行
//defer压栈处理
//panic和defer在同一个流程中,panic最后执行
func callPanic() {
defer func() {
fmt.Println("1")
}()
defer func() {
fmt.Println("2")
}()
defer func() {
fmt.Println("3")
}()
panic("call panic")
}
func main() {
defer func() {
fmt.Println("main")
}()
callPanic()
} |
package main
import(
"flag"
"fmt"
"sync"
"runtime"
)
// Variables that are set by CLI options
var(prefixFile string)
var(maxOutputSize int)
var(outputFile string)
var(threadedMode bool)
var(numCoreThread int)
// Terminate all threads if magic file found
var(foundMagicFile bool)
var checkmtx sync.Mutex
/**
* @Type: Function
* @Name: init
* @Purpose: Runs before main(), reads CLI options into variables
**/
func init() {
flag.StringVar(&prefixFile, "f", "", "Path to the prefix file")
flag.IntVar(&maxOutputSize, "m", 10000, "Maximum file size")
flag.StringVar(&outputFile, "o", "file.out", "Output file")
flag.BoolVar(&threadedMode, "t", false, "Use threaded mode")
flag.IntVar(&numCoreThread, "c", 1, "Number of threads to use per core")
flag.Parse()
}
/**
* @Type: Function
* @Name: checkRequiredFlags
* @Purpose: Check that mandatory options are set
**/
func checkRequiredFlags() bool {
if prefixFile == "" {
return false
}
return true
}
/**
* @Type: Function
* @Name: generateMagicFile
* @Purpose: Attempts to create a magic file - threaded by main()
**/
func generateMagicFile(prefix string) {
for {
/*
* Due to threading, we need to check if some other thread may have succeeded,
* if so, bail on all threads
*/
checkmtx.Lock()
if foundMagicFile {
break
}
checkmtx.Unlock()
// Let's try to create a magic file...
if md5CreateMagicFilePrefixed(prefix) {
break
}
}
}
/**
* @Type: Function
* @Name: main
**/
func main() {
foundMagicFile = false
if !checkRequiredFlags() {
fmt.Println("[*] The '-f' file option is required! Done.")
return
}
fmt.Printf("[+] Checking md5sum of file %s...\n", prefixFile)
md5hash, err := md5sumf(prefixFile)
if err != nil {
fmt.Println("[*] File could not be hashed! Done.\n")
return
}
fmt.Printf("[*] Hash: %s\n", md5hash)
fmt.Println("[+] Checking if file is already a magic file...")
if md5magic(md5hash) {
fmt.Println("[*] File is already magic! Done.")
return
}
fmt.Println("[+] File is not a magic file")
fmt.Println("[+] Generating a magic file - this may take some time...")
prefix, err := readFileContents(prefixFile)
if err != nil {
fmt.Println("[*] Error opening the prefix file! Done.")
return
}
// If threaded mode specified, launch some threads, otherwise, single-thread execution
if threadedMode {
// Get number of cores and multiply by specified option
numThreads := runtime.NumCPU() * numCoreThread
for i := 0; i < numThreads; i++ {
fmt.Printf("[*] Launching thread %d...\n", i)
go generateMagicFile(prefix)
}
// Wait until complete
for {
checkmtx.Lock()
if foundMagicFile {
break
}
checkmtx.Unlock()
}
} else {
generateMagicFile(prefix)
}
} |
/*
Copyright © 2019 NAME HERE <EMAIL ADDRESS>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"git.go-online.org.cn/lijb55/agenda/service"
"fmt"
"os"
"github.com/spf13/cobra"
)
// registerCmd represents the register command
var registerCmd = &cobra.Command{
Use: "register",
Short: "Sign up",
Long: `Sign up your account, so that you can use the agenda`,
Run: func(cmd *cobra.Command, args []string) {
username, _ := cmd.Flags().GetString("username")
password, _ := cmd.Flags().GetString("password")
email, _ := cmd.Flags().GetString("email")
phone, _ := cmd.Flags().GetString("phone")
service.Register(username, password, email, phone)
},
}
func init() {
fileptr, e := os.Open("entity/User.json")
defer fileptr.Close()
if e != nil && fileptr != nil {
fmt.Println(e)
}
if fileptr == nil {
fileptr, e := os.Create("entity/User.json")
defer fileptr.Close()
if e != nil {
fmt.Println(e)
}
}
rootCmd.AddCommand(registerCmd)
registerCmd.Flags().StringP("username", "", "", "")
registerCmd.Flags().StringP("password", "", "", "")
registerCmd.Flags().StringP("email", "", "", "")
registerCmd.Flags().StringP("phone", "", "", "")
}
|
/*
Copyright 2021.
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 v1alpha1
import (
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN!
// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized.
// ImageJobSpec defines the desired state of ImageJob
type ImageJobSpec struct {
// Specifies the job that will be created when executing an ImageJob.
JobTemplate v1.PodTemplateSpec `json:"template"`
ImageListName string `json:"imageListName"`
}
// JobPhase defines the phase of an ImageJob status
type JobPhase string
const (
PhaseRunning JobPhase = "Running"
PhaseCompleted JobPhase = "Completed"
PhaseFailed JobPhase = "Failed"
)
// ImageJobStatus defines the observed state of ImageJob
type ImageJobStatus struct {
// number of pods that failed
Failed int `json:"failed"`
// number of pods that completed successfully
Succeeded int `json:"succeeded"`
// desired number of pods
Desired int `json:"desired"`
// job running, successfully completed, or failed
Phase JobPhase `json:"phase"`
}
//+kubebuilder:object:root=true
//+kubebuilder:subresource:status
//+kubebuilder:resource:scope="Cluster"
// ImageJob is the Schema for the imagejobs API
type ImageJob struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec ImageJobSpec `json:"spec,omitempty"`
Status ImageJobStatus `json:"status,omitempty"`
}
//+kubebuilder:object:root=true
// ImageJobList contains a list of ImageJob
type ImageJobList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []ImageJob `json:"items"`
}
func init() {
SchemeBuilder.Register(&ImageJob{}, &ImageJobList{})
}
|
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
//go:build !race
// +build !race
package testcontext
const raceEnabled = false
|
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
package v2alpha1
import (
"fmt"
"github.com/DataDog/datadog-operator/apis/datadoghq/common"
commonv1 "github.com/DataDog/datadog-operator/apis/datadoghq/common/v1"
apiutils "github.com/DataDog/datadog-operator/apis/utils"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// GetConfName get the name of the Configmap for a CustomConfigSpec
func GetConfName(owner metav1.Object, conf *CustomConfig, defaultName string) string {
// `configData` and `configMap` can't be set together.
// Return the default if the conf is not overridden or if it is just overridden with the ConfigData.
if conf != nil && conf.ConfigMap != nil {
return conf.ConfigMap.Name
}
return fmt.Sprintf("%s-%s", owner.GetName(), defaultName)
}
// GetClusterAgentServiceAccount return the cluster-agent serviceAccountName
func GetClusterAgentServiceAccount(dda *DatadogAgent) string {
saDefault := fmt.Sprintf("%s-%s", dda.Name, common.DefaultClusterAgentResourceSuffix)
if dda.Spec.Override[ClusterAgentComponentName] != nil && dda.Spec.Override[ClusterAgentComponentName].ServiceAccountName != nil {
return *dda.Spec.Override[ClusterAgentComponentName].ServiceAccountName
}
return saDefault
}
// GetAgentServiceAccount returns the agent service account name
func GetAgentServiceAccount(dda *DatadogAgent) string {
saDefault := fmt.Sprintf("%s-%s", dda.Name, common.DefaultAgentResourceSuffix)
if dda.Spec.Override[NodeAgentComponentName] != nil && dda.Spec.Override[NodeAgentComponentName].ServiceAccountName != nil {
return *dda.Spec.Override[NodeAgentComponentName].ServiceAccountName
}
return saDefault
}
// GetClusterChecksRunnerServiceAccount return the cluster-checks-runner service account name
func GetClusterChecksRunnerServiceAccount(dda *DatadogAgent) string {
saDefault := fmt.Sprintf("%s-%s", dda.Name, common.DefaultClusterChecksRunnerResourceSuffix)
if dda.Spec.Override[ClusterChecksRunnerComponentName] != nil && dda.Spec.Override[ClusterChecksRunnerComponentName].ServiceAccountName != nil {
return *dda.Spec.Override[ClusterChecksRunnerComponentName].ServiceAccountName
}
return saDefault
}
// ConvertCustomConfig use to convert a CustomConfig to a common.CustomConfig.
func ConvertCustomConfig(config *CustomConfig) *commonv1.CustomConfig {
if config == nil {
return nil
}
var configMap *commonv1.ConfigMapConfig
if config.ConfigMap != nil {
configMap = &commonv1.ConfigMapConfig{
Name: config.ConfigMap.Name,
Items: config.ConfigMap.Items,
}
}
return &commonv1.CustomConfig{
ConfigData: config.ConfigData,
ConfigMap: configMap,
}
}
// IsHostNetworkEnabled returns whether the pod should use the host's network namespace
func IsHostNetworkEnabled(dda *DatadogAgent, component ComponentName) bool {
if dda.Spec.Override != nil {
if c, ok := dda.Spec.Override[component]; ok {
return apiutils.BoolValue(c.HostNetwork)
}
}
return false
}
// IsClusterChecksEnabled returns whether the DDA should use cluster checks
func IsClusterChecksEnabled(dda *DatadogAgent) bool {
return dda.Spec.Features.ClusterChecks != nil && apiutils.BoolValue(dda.Spec.Features.ClusterChecks.Enabled)
}
// IsCCREnabled returns whether the DDA should use Cluster Checks Runners
func IsCCREnabled(dda *DatadogAgent) bool {
return dda.Spec.Features.ClusterChecks != nil && apiutils.BoolValue(dda.Spec.Features.ClusterChecks.UseClusterChecksRunners)
}
// GetLocalAgentServiceName returns the name used for the local agent service
func GetLocalAgentServiceName(dda *DatadogAgent) string {
if dda.Spec.Global.LocalService != nil && dda.Spec.Global.LocalService.NameOverride != nil {
return *dda.Spec.Global.LocalService.NameOverride
}
return fmt.Sprintf("%s-%s", dda.Name, common.DefaultAgentResourceSuffix)
}
// IsNetworkPolicyEnabled returns whether a network policy should be created and which flavor to use
func IsNetworkPolicyEnabled(dda *DatadogAgent) (bool, NetworkPolicyFlavor) {
if dda.Spec.Global != nil && dda.Spec.Global.NetworkPolicy != nil && apiutils.BoolValue(dda.Spec.Global.NetworkPolicy.Create) {
if dda.Spec.Global.NetworkPolicy.Flavor != "" {
return true, dda.Spec.Global.NetworkPolicy.Flavor
}
return true, NetworkPolicyFlavorKubernetes
}
return false, ""
}
// ShouldCreateSCC returns whether a scc should be created for a component
func ShouldCreateSCC(dda *DatadogAgent, componentName ComponentName) bool {
if dda.Spec.Override[componentName] != nil && dda.Spec.Override[componentName].SecurityContextConstraints != nil {
return apiutils.BoolValue(dda.Spec.Override[componentName].SecurityContextConstraints.Create)
}
return false
}
|
package cmd
import (
"context"
"github.com/loft-sh/devspace/cmd/flags"
devspacecontext "github.com/loft-sh/devspace/pkg/devspace/context"
"github.com/loft-sh/devspace/pkg/devspace/hook"
"github.com/loft-sh/devspace/pkg/devspace/kubectl"
"github.com/loft-sh/devspace/pkg/devspace/plugin"
"github.com/loft-sh/devspace/pkg/devspace/services/attach"
"github.com/loft-sh/devspace/pkg/devspace/services/targetselector"
"github.com/loft-sh/devspace/pkg/util/factory"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
// AttachCmd is a struct that defines a command call for "enter"
type AttachCmd struct {
*flags.GlobalFlags
LabelSelector string
ImageSelector string
Container string
Pod string
Pick bool
}
// NewAttachCmd creates a new attach command
func NewAttachCmd(f factory.Factory, globalFlags *flags.GlobalFlags) *cobra.Command {
cmd := &AttachCmd{GlobalFlags: globalFlags}
attachCmd := &cobra.Command{
Use: "attach",
Short: "Attaches to a container",
Long: `
#######################################################
################# devspace attach #####################
#######################################################
Attaches to a running container
devspace attach
devspace attach --pick # Select pod to enter
devspace attach -c my-container
devspace attach -n my-namespace
#######################################################`,
RunE: func(cobraCmd *cobra.Command, args []string) error {
plugin.SetPluginCommand(cobraCmd, args)
return cmd.Run(f, cobraCmd, args)
},
}
attachCmd.Flags().StringVarP(&cmd.Container, "container", "c", "", "Container name within pod where to execute command")
attachCmd.Flags().StringVar(&cmd.Pod, "pod", "", "Pod to open a shell to")
attachCmd.Flags().StringVar(&cmd.ImageSelector, "image-selector", "", "The image to search a pod for (e.g. nginx, nginx:latest, ${runtime.images.app}, nginx:${runtime.images.app.tag})")
attachCmd.Flags().StringVarP(&cmd.LabelSelector, "label-selector", "l", "", "Comma separated key=value selector list (e.g. release=test)")
attachCmd.Flags().BoolVar(&cmd.Pick, "pick", true, "Select a pod")
return attachCmd
}
// Run executes the command logic
func (cmd *AttachCmd) Run(f factory.Factory, cobraCmd *cobra.Command, args []string) error {
// Set config root
log := f.GetLog()
configOptions := cmd.ToConfigOptions()
configLoader, err := f.NewConfigLoader(cmd.ConfigPath)
if err != nil {
return err
}
configExists, err := configLoader.SetDevSpaceRoot(log)
if err != nil {
return err
}
// Get kubectl client
client, err := f.NewKubeClientFromContext(cmd.KubeContext, cmd.Namespace)
if err != nil {
return errors.Wrap(err, "new kube client")
}
// Load generated config if possible
if configExists {
localCache, err := configLoader.LoadLocalCache()
if err != nil {
return err
}
// If the current kube context or namespace is different from old,
// show warnings and reset kube client if necessary
client, err = kubectl.CheckKubeContext(client, localCache, cmd.NoWarn, cmd.SwitchContext, false, log)
if err != nil {
return err
}
}
// create the context
ctx := devspacecontext.NewContext(context.Background(), nil, log).WithKubeClient(client)
// Execute plugin hook
err = hook.ExecuteHooks(ctx, nil, "attach")
if err != nil {
return err
}
// get image selector if specified
imageSelector, err := getImageSelector(ctx, configLoader, configOptions, cmd.ImageSelector)
if err != nil {
return err
}
// Build params
options := targetselector.NewOptionsFromFlags(cmd.Container, cmd.LabelSelector, imageSelector, cmd.Namespace, cmd.Pod).
WithPick(cmd.Pick).
WithWait(false).
WithQuestion("Which pod do you want to attach to?")
// Start attach
return attach.StartAttachFromCMD(ctx, targetselector.NewTargetSelector(options))
}
|
package channel
import (
"fmt"
"testing"
"time"
)
func service() string {
time.Sleep(50 * time.Millisecond)
return "Done 3333"
}
func otherTask() {
fmt.Println("working on someting else 2222")
time.Sleep(100 * time.Millisecond)
fmt.Println("Task is done 2222")
}
func TestService(t *testing.T) {
fmt.Println(service())
otherTask()
}
func AsyncService() chan string {
retCh := make(chan string, 1)
//retCh := make(chan string)
go func() {
ret := service()
fmt.Println("returned result 1111")
retCh <-ret // 1
fmt.Println("如果是缓冲channel, 则这里不会阻塞到最后才执行 service exited 1111")
}()
return retCh
}
func TestAsyncService(t *testing.T) {
retCh := AsyncService()
otherTask()
fmt.Println(<-retCh) // 2
}
|
package app
import (
"net/http"
"html/template"
"google.golang.org/appengine"
"google.golang.org/appengine/urlfetch"
)
func init() {
http.HandleFunc("/", handleStationName)
}
func handleStationName(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
ctx := appengine.NewContext(r)
client := urlfetch.Client(ctx)
resp, err := client.Get("http://lotr.fantasy-transit.appspot.com/net?format=json")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func bfs() {
}
|
package demo
import (
"github.com/fncodr/remento"
)
func InitDb(cx *remento.Cx) error {
db := cx.Db().(*remento.Db)
systemName, err := cx.Settings.SystemName();
if err != nil {
return err
}
if _, err := systemName.SetVal(cx, "reservo demo"); err != nil {
return err
}
user := remento.NewUser(cx)
db.Name.Set(user, "sys")
if _, err := db.UserTbl.Upsert(cx, user); err != nil {
return err
}
cx.SetUser(user)
user = remento.NewUser(cx)
db.Name.Set(user, "adm")
db.UserPassword.Set(user, "adm")
if _, err := db.UserTbl.Upsert(cx, user); err != nil {
return err
}
rc := remento.NewRc(cx)
db.Name.Set(rc, "room")
db.Summary.Set(rc, "any room")
db.RcCapacType.Set(rc, &remento.FixedCapac)
if _, err := db.RcTbl.Upsert(cx, rc); err != nil {
return err
}
rc = remento.NewRc(cx)
db.Name.Set(rc, "conf")
db.Summary.Set(rc, "any conference room")
db.RcCapacType.Set(rc, &remento.FixedCapac)
if _, err := db.RcTbl.Upsert(cx, rc); err != nil {
return err
}
rc = remento.NewRc(cx)
db.Name.Set(rc, "double")
db.Summary.Set(rc, "any double room")
db.RcCapacType.Set(rc, &remento.FixedCapac)
if _, err := db.RcTbl.Upsert(cx, rc); err != nil {
return err
}
rc = remento.NewRc(cx)
db.Name.Set(rc, "single")
db.Summary.Set(rc, "any single room")
db.RcCapacType.Set(rc, &remento.FixedCapac)
if _, err = db.RcTbl.Upsert(cx, rc); err != nil {
return err
}
return nil
}
|
package main
import (
"server/application/usercase"
"server/infrastructure/auth"
"server/infrastructure/store/mysql"
"server/interfaces/api"
)
//func getProjectId() string {
// PROJECT_ID := os.Getenv("GOOGLE_CLOUD_PROJECT")
// if PROJECT_ID == "" {
// log.Fatalln("Failed to Get PROJECT_ID 'GOOGLE_CLOUD_PROJECT'\n If this is local test, Set 'appname-local' as GOOGLE_CLOUD_PROJECT")
// }
// log.Println("PROJECT_ID: ", PROJECT_ID)
// return PROJECT_ID
//}
func getApiConfig() api.Config {
projectID := "sample"
// infra
sqlHandler := store.NewSqlHandler(projectID)
authCient := auth.NewClient(projectID)
// repository & service
authService := auth.NewAuthService(*authCient)
todoRepository := store.NewTodoRepository(*sqlHandler)
toggleRepository := store.NewToggleRepository(*sqlHandler)
userRepository := store.NewUserRepository(*sqlHandler)
// usecase
authUsecase := usecase.NewAuthUsecase(authService)
todoUsecase := usecase.NewTodoUsecase(todoRepository)
toggleUsecase := usecase.NewToggleUsecase(toggleRepository)
userUsecase := usecase.NewUserUsecase(userRepository)
config := api.Config{
AuthUsecase: authUsecase,
TodoUsecase: todoUsecase,
ToggleUsecase: toggleUsecase,
UserUsecase: userUsecase,
}
return config
}
|
package main
//862. 和至少为 K 的最短子数组
//给你一个整数数组 nums 和一个整数 k ,找出 nums 中和至少为 k 的 最短非空子数组 ,并返回该子数组的长度。如果不存在这样的 子数组 ,返回 -1 。
//
//子数组 是数组中 连续 的一部分。
//
//
//
//示例 1:
//
//输入:nums = [1], k = 1
//输出:1
//示例 2:
//
//输入:nums = [1,2], k = 4
//输出:-1
//示例 3:
//
//输入:nums = [2,-1,2], k = 3
//输出:3
//
//
//提示:
//
//1 <= nums.length <= 10^5
//-10^5 <= nums[i] <= 10^5
//1 <= k <= 10^9
func shortestSubarray(nums []int, k int) int {
n := len(nums)
preSum := make([]int, n+1)
for i, v := range nums {
preSum[i+1] = preSum[i] + v
}
result := n + 1
var q []int
for i, v := range preSum {
for len(q) > 0 && v-preSum[q[0]] >= k {
result = min(result, i-q[0])
q = q[1:]
}
for len(q) > 0 && preSum[q[len(q)-1]] >= v {
q = q[:len(q)-1]
}
q = append(q, i)
}
if result < n+1 {
return result
}
return -1
}
|
package main
import "fmt"
func main() {
var input int
fmt.Print("Please enter an integer: ")
fmt.Scan(&input)
div2, oddOrEven := half(input)
fmt.Printf("half(%d) returns (%d, %t)", input, div2, oddOrEven)
}
func half(z int) (int, bool) {
return z / 2, z%2 == 0
}
|
package convert
import (
"bytes"
"encoding/binary"
"log"
"math/rand"
"net"
"puck-server/db-server/user"
"puck-server/reward-server/rating"
"puck-server/shared-server"
"unsafe"
)
// #include "../../../laidoff/src/puckgamepacket.h"
import "C"
/////////////////////////////////////////////////////////////////////////////////////
// SECTION: Receiving Packet Enums
/////////////////////////////////////////////////////////////////////////////////////
//noinspection ALL
const (
LPGPLWPQUEUE2 = C.LPGP_LWPQUEUE2
LPGPLWPQUEUE3 = C.LPGP_LWPQUEUE3
LPGPLWPCANCELQUEUE = C.LPGP_LWPCANCELQUEUE
LPGPLWPSUDDENDEATH = C.LPGP_LWPSUDDENDEATH
LPGPLWPNEWUSER = C.LPGP_LWPNEWUSER
LPGPLWPQUERYNICK = C.LPGP_LWPQUERYNICK
LPGPLWPPUSHTOKEN = C.LPGP_LWPPUSHTOKEN
LPGPLWPGETLEADERBOARD = C.LPGP_LWPGETLEADERBOARD
LPGPLWPGETLEADERBOARDREVEALPLAYER = C.LPGP_LWPGETLEADERBOARDREVEALPLAYER
LPGPLWPSETNICKNAME = C.LPGP_LWPSETNICKNAME
LPGPLWPBATTLERESULT = C.LPGP_LWPBATTLERESULT
LWPUCKGAMEQUEUETYPEFIFO = C.LW_PUCK_GAME_QUEUE_TYPE_FIFO
LWPUCKGAMEQUEUETYPENEARESTSCORE = C.LW_PUCK_GAME_QUEUE_TYPE_NEAREST_SCORE
LWPUCKGAMEQUEUETYPENEARESTSCOREWITHOCTAGONSUPPORT = C.LW_PUCK_GAME_QUEUE_TYPE_NEAREST_SCORE_WITH_OCTAGON_SUPPORT
LWNICKNAMEMAXLEN = C.LW_NICKNAME_MAX_LEN
LWSETNICKNAMERESULTOK = C.LW_SET_NICKNAME_RESULT_OK
LWSETNICKNAMERESULTTOOSHORT = C.LW_SET_NICKNAME_RESULT_TOO_SHORT
LWSETNICKNAMERESULTTOOLONG = C.LW_SET_NICKNAME_RESULT_TOO_LONG
LWSETNICKNAMERESULTTOONOTALLOWED = C.LW_SET_NICKNAME_RESULT_TOO_NOT_ALLOWED
LWSETNICKNAMERESULTINTERNALERROR = C.LW_SET_NICKNAME_RESULT_INTERNAL_ERROR
LPGMSQUARE = C.LPGM_SQUARE
LPGMOCTAGON = C.LPGM_OCTAGON
LPGMCOUNT = C.LPGM_COUNT
)
/////////////////////////////////////////////////////////////////////////////////////
// SECTION: Packet Wrappers
/////////////////////////////////////////////////////////////////////////////////////
type CreateBattleOk struct {
S C.LWPCREATEBATTLEOK
}
type BattleResult struct {
S C.LWPBATTLERESULT
}
/////////////////////////////////////////////////////////////////////////////////////
// SECTION: Packets
/////////////////////////////////////////////////////////////////////////////////////
func NewLwpBattleValid() (*C.LWPBATTLEVALID, int) {
return &C.LWPBATTLEVALID{}, int(C.LPGP_LWPBATTLEVALID)
}
func NewLwpCreateBattleOk() (*C.LWPCREATEBATTLEOK, int) {
return &C.LWPCREATEBATTLEOK{}, int(C.LPGP_LWPCREATEBATTLEOK)
}
func NewLwpBattleResult() (*BattleResult, int) {
return &BattleResult{}, int(C.LPGP_LWPBATTLERESULT)
}
func LwpBattleResultPlayer(battleResult *C.LWPBATTLERESULT, i int) *C.LWPBATTLERESULT_PLAYER {
return &battleResult.Player[i]
}
func LwpBattleResultPlayerStat(battleResult *C.LWPBATTLERESULT, i int) *C.LWPBATTLERESULT_STAT {
player := LwpBattleResultPlayer(battleResult, i)
return &player.Stat
}
func NewLwpRetryQueueLater() *C.LWPRETRYQUEUELATER {
return &C.LWPRETRYQUEUELATER{
C.ushort(unsafe.Sizeof(C.LWPRETRYQUEUELATER{})),
C.LPGP_LWPRETRYQUEUELATER,
}
}
func NewLwpRetryQueue() *C.LWPRETRYQUEUE {
return &C.LWPRETRYQUEUE{
C.ushort(unsafe.Sizeof(C.LWPRETRYQUEUE{})),
C.LPGP_LWPRETRYQUEUE,
}
}
func NewLwpRetryQueue2(queueType int) *C.LWPRETRYQUEUE2 {
return &C.LWPRETRYQUEUE2{
C.ushort(unsafe.Sizeof(C.LWPRETRYQUEUE2{})),
C.LPGP_LWPRETRYQUEUE2,
C.int(queueType),
}
}
func NewLwpCancelQueueOk() *C.LWPCANCELQUEUEOK {
return &C.LWPCANCELQUEUEOK{
C.ushort(unsafe.Sizeof(C.LWPCANCELQUEUEOK{})),
C.LPGP_LWPCANCELQUEUEOK,
}
}
func NewLwpMaybeMatched() *C.LWPMAYBEMATCHED {
return &C.LWPMAYBEMATCHED{
C.ushort(unsafe.Sizeof(C.LWPMAYBEMATCHED{})),
C.LPGP_LWPMAYBEMATCHED,
}
}
func NewLwpNick(nick string, scoreRankItem *shared_server.ScoreRankItem) *C.LWPNICK {
cNewNickBytes := NicknameToCArray(nick)
return &C.LWPNICK{
C.ushort(unsafe.Sizeof(C.LWPNICK{})),
C.LPGP_LWPNICK,
cNewNickBytes,
C.int(scoreRankItem.Score),
C.int(scoreRankItem.Rank),
}
}
func NewLwpQueueOk() *C.LWPQUEUEOK {
return &C.LWPQUEUEOK{
C.ushort(unsafe.Sizeof(C.LWPQUEUEOK{})),
C.LPGP_LWPQUEUEOK,
}
}
func NewLwpSetNicknameResult(request *C.LWPSETNICKNAME, result int) *C.LWPSETNICKNAMERESULT {
return &C.LWPSETNICKNAMERESULT{
C.ushort(unsafe.Sizeof(C.LWPSETNICKNAMERESULT{})),
C.LPGP_LWPSETNICKNAMERESULT,
request.Id,
request.Nickname,
C.int(result),
}
}
func NewLwpMatched2(port int, ipv4 net.IP, battleId int, token uint, playerNo, playerScore, targetScore int, targetNickname string, gameMap int) *C.LWPMATCHED2 {
drawScore, _ := rating.CalculateNewRating(playerScore, targetScore, 0)
victoryScore, _ := rating.CalculateNewRating(playerScore, targetScore, 1)
defeatScore, _ := rating.CalculateNewRating(playerScore, targetScore, 2)
return &C.LWPMATCHED2{
C.ushort(unsafe.Sizeof(C.LWPMATCHED2{})),
C.LPGP_LWPMATCHED2,
C.ushort(port), // createBattleOk.Port
C.ushort(gameMap),
[4]C.uchar{C.uchar(ipv4[0]), C.uchar(ipv4[1]), C.uchar(ipv4[2]), C.uchar(ipv4[3])},
C.int(battleId),
C.uint(token),
C.int(playerNo),
C.int(targetScore),
NicknameToCArray(targetNickname),
C.int(victoryScore),
C.int(defeatScore),
C.int(drawScore),
}
}
func NewLwpLeaderboard(leaderboardReply *shared_server.LeaderboardReply) *C.LWPLEADERBOARD {
var nicknameList [C.LW_LEADERBOARD_ITEMS_IN_PAGE][C.LW_NICKNAME_MAX_LEN]C.char
var scoreList [C.LW_LEADERBOARD_ITEMS_IN_PAGE]C.int
for i, item := range leaderboardReply.Items {
GoStringToCCharArray(&item.Nickname, &nicknameList[i])
scoreList[i] = C.int(item.Score)
}
return &C.LWPLEADERBOARD{
C.ushort(unsafe.Sizeof(C.LWPLEADERBOARD{})),
C.LPGP_LWPLEADERBOARD,
C.int(len(leaderboardReply.Items)),
C.int(leaderboardReply.FirstItemRank),
C.int(leaderboardReply.FirstItemTieCount),
nicknameList,
scoreList,
C.int(leaderboardReply.RevealIndex),
C.int(leaderboardReply.CurrentPage),
C.int(leaderboardReply.TotalPage),
}
}
func NewLwpNewUserData(uuid user.Id, newNick string, score, rank int) *C.LWPNEWUSERDATA {
cNewNickBytes := NicknameToCArray(newNick)
return &C.LWPNEWUSERDATA{
C.ushort(unsafe.Sizeof(C.LWPNEWUSERDATA{})),
C.LPGP_LWPNEWUSERDATA,
[4]C.uint{C.uint(binary.BigEndian.Uint32(uuid[0:4])), C.uint(binary.BigEndian.Uint32(uuid[4:8])), C.uint(binary.BigEndian.Uint32(uuid[8:12])), C.uint(binary.BigEndian.Uint32(uuid[12:16]))},
cNewNickBytes,
C.int(score),
C.int(rank),
}
}
func NewLwpSysMsg(sysMsg []byte) *C.LWPSYSMSG {
return &C.LWPSYSMSG{
C.ushort(unsafe.Sizeof(C.LWPSYSMSG{})),
C.LPGP_LWPSYSMSG,
ByteArrayToCcharArray256(sysMsg),
}
}
/////////////////////////////////////////////////////////////////////////////////////
// SECTION: Convert Utility Functions
/////////////////////////////////////////////////////////////////////////////////////
func GoStringToCCharArray(strIn *string, strOut *[C.LW_NICKNAME_MAX_LEN]C.char) {
for i, b := range []byte(*strIn) {
(*strOut)[i] = C.char(b)
}
}
func CCharArrayToGoString(strIn *[C.LW_NICKNAME_MAX_LEN]C.char, strOut *string) {
b := make([]byte, len(strIn))
lastIndex := 0
for i, ch := range strIn {
b[i] = byte(ch)
if b[i] == 0 {
lastIndex = i
break
}
}
*strOut = string(b[:lastIndex])
}
func ByteArrayToCcharArray256(b []byte) [256]C.char {
var ret [256]C.char
bLen := len(b)
if bLen > 255 {
bLen = 255
}
for i := 0; i < bLen; i++ {
ret[i] = C.char(b[i])
}
return ret
}
func UserIdToCuint(id user.Id) [4]C.uint {
var b [4]C.uint
b[0] = C.uint(binary.BigEndian.Uint32(id[0:4]))
b[1] = C.uint(binary.BigEndian.Uint32(id[4:8]))
b[2] = C.uint(binary.BigEndian.Uint32(id[8:12]))
b[3] = C.uint(binary.BigEndian.Uint32(id[12:16]))
return b
}
func IdCuintToByteArray(id [4]C.uint) user.Id {
var b user.Id
binary.BigEndian.PutUint32(b[0:], uint32(id[0]))
binary.BigEndian.PutUint32(b[4:], uint32(id[1]))
binary.BigEndian.PutUint32(b[8:], uint32(id[2]))
binary.BigEndian.PutUint32(b[12:], uint32(id[3]))
return b
}
func IdIntToByteArray(id [4]int) user.Id {
var b user.Id
binary.BigEndian.PutUint32(b[0:], uint32(id[0]))
binary.BigEndian.PutUint32(b[4:], uint32(id[1]))
binary.BigEndian.PutUint32(b[8:], uint32(id[2]))
binary.BigEndian.PutUint32(b[12:], uint32(id[3]))
return b
}
func NicknameToCArray(nickname string) [C.LW_NICKNAME_MAX_LEN]C.char {
var nicknameCchar [C.LW_NICKNAME_MAX_LEN]C.char
for i, v := range []byte(nickname) {
if i >= C.LW_NICKNAME_MAX_LEN {
break
}
nicknameCchar[i] = C.char(v)
}
nicknameCchar[C.LW_NICKNAME_MAX_LEN-1] = 0
return nicknameCchar
}
func NewCreateBattle(id1, id2 user.Id, nickname1, nickname2 string, bot bool, gameMap int) *C.LWPCREATEBATTLE {
var c1Nickname [C.LW_NICKNAME_MAX_LEN]C.char
var c2Nickname [C.LW_NICKNAME_MAX_LEN]C.char
GoStringToCCharArray(&nickname1, &c1Nickname)
GoStringToCCharArray(&nickname2, &c2Nickname)
var isBot C.int
if bot {
isBot = 1
} else {
isBot = 0
}
return &C.LWPCREATEBATTLE{
C.ushort(unsafe.Sizeof(C.LWPCREATEBATTLE{})),
C.LPGP_LWPCREATEBATTLE,
isBot,
UserIdToCuint(id1),
UserIdToCuint(id2),
c1Nickname,
c2Nickname,
C.int(gameMap),
}
}
func NewCheckBattleValid(battleId int) *C.LWPCHECKBATTLEVALID {
return &C.LWPCHECKBATTLEVALID{
C.ushort(unsafe.Sizeof(C.LWPCHECKBATTLEVALID{})),
C.LPGP_LWPCHECKBATTLEVALID,
C.int(battleId),
}
}
func Packet2Buf(packet interface{}) []byte {
buf := &bytes.Buffer{}
binary.Write(buf, binary.LittleEndian, packet)
return buf.Bytes()
}
func PushTokenBytes(recvPacket *C.LWPPUSHTOKEN) []byte {
return C.GoBytes(unsafe.Pointer(&recvPacket.Push_token), C.LW_PUSH_TOKEN_LENGTH)
}
/////////////////////////////////////////////////////////////////////////////////////
// SECTION: Parse Packets
/////////////////////////////////////////////////////////////////////////////////////
func ParsePushToken(buf []byte) (*C.LWPPUSHTOKEN, error) {
bufReader := bytes.NewReader(buf)
recvPacket := &C.LWPPUSHTOKEN{}
err := binary.Read(bufReader, binary.LittleEndian, recvPacket)
if err != nil {
log.Printf("binary.Read fail: %v", err.Error())
return nil, err
}
return recvPacket, nil
}
func ParseQueryNick(buf []byte) (*C.LWPQUERYNICK, error) {
bufReader := bytes.NewReader(buf)
recvPacket := &C.LWPQUERYNICK{}
err := binary.Read(bufReader, binary.LittleEndian, recvPacket)
if err != nil {
log.Printf("binary.Read fail: %v", err.Error())
return nil, err
}
return recvPacket, nil
}
func ParseQueue2(buf []byte) (*C.LWPQUEUE2, error) {
bufReader := bytes.NewReader(buf)
recvPacket := &C.LWPQUEUE2{}
err := binary.Read(bufReader, binary.LittleEndian, recvPacket)
if err != nil {
log.Printf("binary.Read fail: %v", err.Error())
return nil, err
}
return recvPacket, nil
}
func ParseQueue3(buf []byte) (*C.LWPQUEUE3, error) {
bufReader := bytes.NewReader(buf)
recvPacket := &C.LWPQUEUE3{}
err := binary.Read(bufReader, binary.LittleEndian, recvPacket)
if err != nil {
log.Printf("binary.Read fail: %v", err.Error())
return nil, err
}
return recvPacket, nil
}
func ParseCancelQueue(buf []byte) (*C.LWPCANCELQUEUE, error) {
bufReader := bytes.NewReader(buf)
recvPacket := &C.LWPCANCELQUEUE{}
err := binary.Read(bufReader, binary.LittleEndian, recvPacket)
if err != nil {
log.Printf("binary.Read fail: %v", err.Error())
return nil, err
}
return recvPacket, nil
}
func ParseSetNickname(buf []byte) (*C.LWPSETNICKNAME, error) {
bufReader := bytes.NewReader(buf)
recvPacket := &C.LWPSETNICKNAME{}
err := binary.Read(bufReader, binary.LittleEndian, recvPacket)
if err != nil {
log.Printf("binary.Read fail: %v", err.Error())
return nil, err
}
return recvPacket, nil
}
func ParseGetLeaderboard(buf []byte) (*C.LWPGETLEADERBOARD, error) {
bufReader := bytes.NewReader(buf)
recvPacket := &C.LWPGETLEADERBOARD{}
err := binary.Read(bufReader, binary.LittleEndian, recvPacket)
if err != nil {
log.Printf("binary.Read fail: %v", err.Error())
return nil, err
}
return recvPacket, nil
}
func ParseGetLeaderboardRevealPlayer(buf []byte) (*C.LWPGETLEADERBOARDREVEALPLAYER, error) {
bufReader := bytes.NewReader(buf)
recvPacket := &C.LWPGETLEADERBOARDREVEALPLAYER{}
err := binary.Read(bufReader, binary.LittleEndian, recvPacket)
if err != nil {
log.Printf("binary.Read fail: %v", err.Error())
return nil, err
}
return recvPacket, nil
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func GetRandomGameMap(supportedGameMap1, rating1, supportedGameMap2, rating2 int) int {
gameMap := int(C.LPGM_SQUARE)
if rating1 > 1600 || rating2 > 1600 {
gameMap = rand.Intn(min(supportedGameMap1, supportedGameMap2) + 1)
}
return gameMap
}
|
package sonobi
import (
"encoding/json"
"fmt"
"net/http"
"github.com/prebid/openrtb/v19/openrtb2"
"github.com/prebid/prebid-server/adapters"
"github.com/prebid/prebid-server/config"
"github.com/prebid/prebid-server/errortypes"
"github.com/prebid/prebid-server/openrtb_ext"
)
// SonobiAdapter - Sonobi SonobiAdapter definition
type SonobiAdapter struct {
URI string
}
// Builder builds a new instance of the Sonobi adapter for the given bidder with the given config.
func Builder(bidderName openrtb_ext.BidderName, config config.Adapter, server config.Server) (adapters.Bidder, error) {
bidder := &SonobiAdapter{
URI: config.Endpoint,
}
return bidder, nil
}
// MakeRequests Makes the OpenRTB request payload
func (a *SonobiAdapter) MakeRequests(request *openrtb2.BidRequest, reqInfo *adapters.ExtraRequestInfo) ([]*adapters.RequestData, []error) {
var errs []error
var sonobiExt openrtb_ext.ExtImpSonobi
var err error
var adapterRequests []*adapters.RequestData
// Sonobi currently only supports 1 imp per request to sonobi.
// Loop over the imps from the initial bid request to form many adapter requests to sonobi with only 1 imp.
for _, imp := range request.Imp {
// Make a copy as we don't want to change the original request
reqCopy := *request
reqCopy.Imp = append(make([]openrtb2.Imp, 0, 1), imp)
var bidderExt adapters.ExtImpBidder
if err = json.Unmarshal(reqCopy.Imp[0].Ext, &bidderExt); err != nil {
errs = append(errs, err)
continue
}
if err = json.Unmarshal(bidderExt.Bidder, &sonobiExt); err != nil {
errs = append(errs, err)
continue
}
reqCopy.Imp[0].TagID = sonobiExt.TagID
adapterReq, errors := a.makeRequest(&reqCopy)
if adapterReq != nil {
adapterRequests = append(adapterRequests, adapterReq)
}
errs = append(errs, errors...)
}
return adapterRequests, errs
}
// makeRequest helper method to crete the http request data
func (a *SonobiAdapter) makeRequest(request *openrtb2.BidRequest) (*adapters.RequestData, []error) {
var errs []error
reqJSON, err := json.Marshal(request)
if err != nil {
errs = append(errs, err)
return nil, errs
}
headers := http.Header{}
headers.Add("Content-Type", "application/json;charset=utf-8")
headers.Add("Accept", "application/json")
return &adapters.RequestData{
Method: "POST",
Uri: a.URI,
Body: reqJSON,
Headers: headers,
}, errs
}
// MakeBids makes the bids
func (a *SonobiAdapter) MakeBids(internalRequest *openrtb2.BidRequest, externalRequest *adapters.RequestData, response *adapters.ResponseData) (*adapters.BidderResponse, []error) {
var errs []error
if response.StatusCode == http.StatusNoContent {
return nil, nil
}
if response.StatusCode == http.StatusBadRequest {
return nil, []error{&errortypes.BadInput{
Message: fmt.Sprintf("Unexpected status code: %d. Run with request.debug = 1 for more info", response.StatusCode),
}}
}
if response.StatusCode != http.StatusOK {
return nil, []error{&errortypes.BadServerResponse{
Message: fmt.Sprintf("Unexpected status code: %d. Run with request.debug = 1 for more info", response.StatusCode),
}}
}
var bidResp openrtb2.BidResponse
if err := json.Unmarshal(response.Body, &bidResp); err != nil {
return nil, []error{err}
}
bidResponse := adapters.NewBidderResponseWithBidsCapacity(5)
for _, sb := range bidResp.SeatBid {
for i := range sb.Bid {
bidType, err := getMediaTypeForImp(sb.Bid[i].ImpID, internalRequest.Imp)
if err != nil {
errs = append(errs, err)
} else {
b := &adapters.TypedBid{
Bid: &sb.Bid[i],
BidType: bidType,
}
bidResponse.Bids = append(bidResponse.Bids, b)
}
}
}
return bidResponse, errs
}
func getMediaTypeForImp(impID string, imps []openrtb2.Imp) (openrtb_ext.BidType, error) {
mediaType := openrtb_ext.BidTypeBanner
for _, imp := range imps {
if imp.ID == impID {
if imp.Banner == nil && imp.Video != nil {
mediaType = openrtb_ext.BidTypeVideo
}
return mediaType, nil
}
}
// This shouldnt happen. Lets handle it just incase by returning an error.
return "", &errortypes.BadInput{
Message: fmt.Sprintf("Failed to find impression \"%s\" ", impID),
}
}
|
package main
const (
_ = 1 << (10 * iota)
KiB
MiB
GiB
TiB
PiB
)
|
//
// DISCLAIMER
//
// Copyright 2020-2021 ArangoDB GmbH, Cologne, Germany
//
// 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.
//
// Copyright holder is ArangoDB GmbH, Cologne, Germany
//
// Author Adam Janikowski
//
package reconcile
import (
"context"
"k8s.io/apimachinery/pkg/util/uuid"
api "github.com/arangodb/kube-arangodb/pkg/apis/deployment/v1"
"github.com/arangodb/kube-arangodb/pkg/util/errors"
"github.com/rs/zerolog"
)
func init() {
registerAction(api.ActionTypeMemberRIDUpdate, newMemberRIDUpdate)
}
func newMemberRIDUpdate(log zerolog.Logger, action api.Action, actionCtx ActionContext) Action {
a := &memberRIDUpdateAction{}
a.actionImpl = newActionImplDefRef(log, action, actionCtx, defaultTimeout)
return a
}
type memberRIDUpdateAction struct {
actionImpl
actionEmptyCheckProgress
}
func (a *memberRIDUpdateAction) Start(ctx context.Context) (bool, error) {
log := a.log
m, ok := a.actionCtx.GetMemberStatusByID(a.action.MemberID)
if !ok {
log.Error().Msg("No such member")
return true, nil
}
m.RID = uuid.NewUUID()
if err := a.actionCtx.UpdateMember(ctx, m); err != nil {
return false, errors.WithStack(err)
}
return true, nil
}
|
// Copyright 2018 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package main
import (
"io"
"strings"
"text/template"
)
const selectionOpsTmpl = "pkg/sql/colexec/colexecsel/selection_ops_tmpl.go"
func getSelectionOpsTmpl(inputFileContents string) (*template.Template, error) {
r := strings.NewReplacer(
"_LEFT_CANONICAL_TYPE_FAMILY", "{{.LeftCanonicalFamilyStr}}",
"_LEFT_TYPE_WIDTH", typeWidthReplacement,
"_RIGHT_CANONICAL_TYPE_FAMILY", "{{.RightCanonicalFamilyStr}}",
"_RIGHT_TYPE_WIDTH", typeWidthReplacement,
"_OP_CONST_NAME", "sel{{.Name}}{{.Left.VecMethod}}{{.Right.VecMethod}}ConstOp",
"_OP_NAME", "sel{{.Name}}{{.Left.VecMethod}}{{.Right.VecMethod}}Op",
"_NAME", "{{.Name}}",
"_R_GO_TYPE", "{{.Right.GoType}}",
"_L_TYP", "{{.Left.VecMethod}}",
"_R_TYP", "{{.Right.VecMethod}}",
)
s := r.Replace(inputFileContents)
assignCmpRe := makeFunctionRegex("_ASSIGN_CMP", 6)
s = assignCmpRe.ReplaceAllString(s, makeTemplateFunctionCall("Right.Assign", 6))
s = strings.ReplaceAll(s, "_L_UNSAFEGET", "execgen.UNSAFEGET")
s = replaceManipulationFuncsAmbiguous(".Left", s)
s = strings.ReplaceAll(s, "_R_UNSAFEGET", "execgen.UNSAFEGET")
s = replaceManipulationFuncsAmbiguous(".Right", s)
s = strings.ReplaceAll(s, "_HAS_NULLS", "$hasNulls")
selConstLoop := makeFunctionRegex("_SEL_CONST_LOOP", 1)
s = selConstLoop.ReplaceAllString(s, `{{template "selConstLoop" buildDict "Global" $ "HasNulls" $1 "Overload" .}}`)
selLoop := makeFunctionRegex("_SEL_LOOP", 1)
s = selLoop.ReplaceAllString(s, `{{template "selLoop" buildDict "Global" $ "HasNulls" $1 "Overload" .}}`)
return template.New("selection_ops").Funcs(template.FuncMap{"buildDict": buildDict}).Parse(s)
}
func genSelectionOps(inputFileContents string, wr io.Writer) error {
tmpl, err := getSelectionOpsTmpl(inputFileContents)
if err != nil {
return err
}
return tmpl.Execute(wr, twoArgsResolvedOverloadsInfo)
}
func init() {
registerGenerator(genSelectionOps, "selection_ops.eg.go", selectionOpsTmpl)
}
|
package input
import (
"github.com/hajimehoshi/ebiten"
"github.com/hajimehoshi/ebiten/inpututil"
)
const (
// TODO: This is duplicated with draw package's definitions.
ScreenWidth = 320
ScreenHeight = 240
)
var theInput = &Input{
pressed: map[ebiten.Key]struct{}{},
prevPressed: map[ebiten.Key]struct{}{},
}
func Current() *Input {
return theInput
}
type Direction int
const (
DirectionLeft Direction = iota
DirectionRight
DirectionDown
)
var keys = []ebiten.Key{
ebiten.KeyEnter,
ebiten.KeySpace,
ebiten.KeyLeft,
ebiten.KeyDown,
ebiten.KeyRight,
// Fullscreen
ebiten.KeyF,
// Profiling
ebiten.KeyP,
ebiten.KeyQ,
}
type Input struct {
pressed map[ebiten.Key]struct{}
prevPressed map[ebiten.Key]struct{}
touchEnabled bool
}
func (i *Input) IsTouchEnabled() bool {
if isTouchPrimaryInput() {
return true
}
return i.touchEnabled
}
func (i *Input) Update() {
const gamepadID = 0
i.prevPressed = map[ebiten.Key]struct{}{}
for k := range i.pressed {
i.prevPressed[k] = struct{}{}
}
i.pressed = map[ebiten.Key]struct{}{}
for _, k := range keys {
if ebiten.IsKeyPressed(k) {
i.pressed[k] = struct{}{}
}
}
// Emulates the keys by gamepad pressing
switch ebiten.GamepadAxis(gamepadID, 0) {
case -1:
i.pressed[ebiten.KeyLeft] = struct{}{}
case 1:
i.pressed[ebiten.KeyRight] = struct{}{}
}
if y := ebiten.GamepadAxis(gamepadID, 1); y == 1 {
i.pressed[ebiten.KeyDown] = struct{}{}
}
for b := ebiten.GamepadButton0; b <= ebiten.GamepadButtonMax; b++ {
if ebiten.IsGamepadButtonPressed(gamepadID, b) {
i.pressed[ebiten.KeyEnter] = struct{}{}
i.pressed[ebiten.KeySpace] = struct{}{}
break
}
}
// Emulates the keys by touching
touches := ebiten.TouchIDs()
for _, t := range touches {
x, y := ebiten.TouchPosition(t)
// TODO(hajimehoshi): 64 are magic numbers
if y < ScreenHeight-64 {
continue
}
switch {
case ScreenWidth <= x:
case ScreenWidth*3/4 <= x:
i.pressed[ebiten.KeyEnter] = struct{}{}
i.pressed[ebiten.KeySpace] = struct{}{}
case ScreenWidth*2/4 <= x:
i.pressed[ebiten.KeyDown] = struct{}{}
case ScreenWidth/4 <= x:
i.pressed[ebiten.KeyRight] = struct{}{}
default:
i.pressed[ebiten.KeyLeft] = struct{}{}
}
}
if 0 < len(touches) {
i.touchEnabled = true
}
}
func inLanguageSwitcher(x, y int) bool {
return ScreenWidth*3/4 <= x && y < ScreenHeight/4
}
func (i *Input) IsSpaceTouched() bool {
for _, t := range ebiten.TouchIDs() {
x, y := ebiten.TouchPosition(t)
if !inLanguageSwitcher(x, y) && y < ScreenHeight-64 {
return true
}
}
return false
}
func (i *Input) IsSpaceJustTouched() bool {
for _, t := range inpututil.JustPressedTouchIDs() {
x, y := ebiten.TouchPosition(t)
if !inLanguageSwitcher(x, y) && y < ScreenHeight-64 {
return true
}
}
return false
}
func (i *Input) IsKeyPressed(key ebiten.Key) bool {
_, ok := i.pressed[key]
return ok
}
func (i *Input) IsKeyJustPressed(key ebiten.Key) bool {
_, ok := i.pressed[key]
if !ok {
return false
}
_, ok = i.prevPressed[key]
return !ok
}
func (i *Input) IsActionKeyPressed() bool {
return i.IsKeyPressed(ebiten.KeyEnter) || i.IsKeyPressed(ebiten.KeySpace)
}
func (i *Input) IsActionKeyJustPressed() bool {
return i.IsKeyJustPressed(ebiten.KeyEnter) || i.IsKeyJustPressed(ebiten.KeySpace)
}
func (i *Input) IsDirectionKeyPressed(dir Direction) bool {
switch dir {
case DirectionLeft:
return i.IsKeyPressed(ebiten.KeyLeft)
case DirectionRight:
return i.IsKeyPressed(ebiten.KeyRight)
case DirectionDown:
return i.IsKeyPressed(ebiten.KeyDown)
default:
panic("not reach")
}
}
func (i *Input) IsLanguageSwitcherPressed() bool {
if inpututil.IsKeyJustPressed(ebiten.KeyL) {
return true
}
if inpututil.IsMouseButtonJustPressed(ebiten.MouseButtonLeft) {
if inLanguageSwitcher(ebiten.CursorPosition()) {
return true
}
}
for _, t := range inpututil.JustPressedTouchIDs() {
if inLanguageSwitcher(ebiten.TouchPosition(t)) {
return true
}
}
return false
}
|
package main
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"math/rand"
"reflect"
"regexp"
"runtime"
"testing"
proto "github.com/golang/protobuf/proto"
"github.com/hyperledger/fabric/core/chaincode/shim"
IOTRegistryTX "github.com/Trusted-IoT-Alliance/IOTRegistry/IOTRegistryTX"
"github.com/btcsuite/btcd/btcec"
)
/*
Notes from IOTRegistery tests
Private Key 1: 94d7fe7308a452fdf019a0424d9c48ba9b66bdbca565c6fa3b1bf9c646ebac20
Public Key 1: 02ca4a8c7dc5090f924cde2264af240d76f6d58a5d2d15c8c5f59d95c70bd9e4dc
Private Key 2: 246d4fa59f0baa3329d3908659936ac2ac9c3539dc925977759cffe3c6316e19
Public Key 2: 03442b817ad2154766a8f5192fc5a7506b7e52cdbf4fcf8e1bc33764698443c3c9
Private Key 3: 166cc93d9eadb573b329b5993b9671f1521679cea90fe52e398e66c1d6373abf
Public Key 3: 02242a1c19bc831cd95a9e5492015043250cbc17d0eceb82612ce08736b8d753a6
Private Key 4: 01b756f231c72747e024ceee41703d9a7e3ab3e68d9b73d264a0196bd90acedf
Public Key 4: 020f2b95263c4b3be740b7b3fda4c2f4113621c1a7a360713a2540eeb808519cd6
Unused:
Public Key: 02cb6d65b04c4b84502015f918fe549e95cad4f3b899359a170d4d7d438363c0ce
Private Key: 60977f22a920c9aa18d58d12cb5e90594152d7aa724bcce21484dfd0f4490b58
Hyperledger address hex 10734390011641497f489cb475743b8e50d429bb
Hyperledger address Base58: EHxhLN3Ft4p9jPkR31MJMEMee9G
Owner1 key
Public Key: 0278b76afbefb1e1185bc63ed1a17dd88634e0587491f03e9a8d2d25d9ab289ee7
Private Key: 7142c92e6eba38de08980eeb55b8c98bb19f8d417795adb56b6c4d25da6b26c5
Owner2 key
Public Key: 02e138b25db2e74c54f8ca1a5cf79e2d1ed6af5bd1904646e7dc08b6d7b0d12bfd
Private Key: b18b7d3082b3ff9438a7bf9f5f019f8a52fb64647ea879548b3ca7b551eefd65
*/
var hexChars = []rune("0123456789abcdef")
var alpha = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
/*
testing tool for creating randomized string with a certain character makeup
*/
func randString(n int, kindOfString string) string {
b := make([]rune, n)
if kindOfString == "hex" {
for i := range b {
b[i] = hexChars[rand.Intn(len(hexChars))]
}
} else if kindOfString == "alpha" {
for i := range b {
b[i] = alpha[rand.Intn(len(alpha))]
}
} else {
fmt.Println("randString() error: could not retrieve character list for random string generation")
return ""
}
return string(b)
}
/*
generates a signature for creating a registrant based on private key and message
*/
func createRegistrantSig(registrantName string, registrantPubkey string, data string, privateKeyStr string) (string, error) {
privKeyByte, err := hex.DecodeString(privateKeyStr)
if err != nil {
return "", fmt.Errorf("error decoding hex encoded private key (%s)", privateKeyStr)
}
privKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), privKeyByte)
message := registrantName + ":" + registrantPubkey + ":" + data
messageBytes := sha256.Sum256([]byte(message))
sig, err := privKey.Sign(messageBytes[:])
if err != nil {
return "", fmt.Errorf("error signing message (%s) with private key (%s)", message, privateKeyStr)
}
return hex.EncodeToString(sig.Serialize()), nil
}
/*
generates a signature for registering a thing based on private key and message
*/
func generateRegisterThingSig(registrantPubkey string, aliases []string, spec string, data string, privateKeyStr string) (string, error) {
privKeyByte, err := hex.DecodeString(privateKeyStr)
if err != nil {
return "", fmt.Errorf("error decoding hex encoded private key (%s)", privateKeyStr)
}
privKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), privKeyByte)
message := registrantPubkey
for _, identity := range aliases {
message += ":" + identity
}
message += ":" + data
message += ":" + spec
messageBytes := sha256.Sum256([]byte(message))
sig, err := privKey.Sign(messageBytes[:])
if err != nil {
return "", fmt.Errorf("error signing message (%s) with private key (%s)", message, privateKeyStr)
}
return hex.EncodeToString(sig.Serialize()), nil
}
/*
generates a signature for registering a spec based on private key and message
*/
func generateRegisterSpecSig(specName string, registrantPubkey string, data string, privateKeyStr string) (string, error) {
privKeyByte, err := hex.DecodeString(privateKeyStr)
if err != nil {
return "", fmt.Errorf("error decoding hex encoded private key (%s)", privateKeyStr)
}
privKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), privKeyByte)
message := specName + ":" + registrantPubkey + ":" + data
messageBytes := sha256.Sum256([]byte(message))
sig, err := privKey.Sign(messageBytes[:])
if err != nil {
return "", fmt.Errorf("error signing message (%s) with private key (%s)", message, privateKeyStr)
}
return hex.EncodeToString(sig.Serialize()), nil
}
func checkInit(t *testing.T, stub *shim.MockStub, args []string) {
_, err := stub.MockInit("1", "", args)
if err != nil {
fmt.Println("INIT", args, "failed", err)
t.FailNow()
}
}
/*
register a store type "Identites" to ledger by calling to Invoke()
*/
func createRegistrant(t *testing.T, stub *shim.MockStub, name string, data string,
privateKeyString string, pubKeyString string) error {
registrant := IOTRegistryTX.CreateRegistrantTX{}
registrant.RegistrantName = name
pubKeyBytes, err := hex.DecodeString(pubKeyString)
if err != nil {
return fmt.Errorf("%v", err)
}
registrant.RegistrantPubkey = pubKeyBytes
registrant.Data = data
//create signature
hexOwnerSig, err := createRegistrantSig(registrant.RegistrantName, hex.EncodeToString(registrant.RegistrantPubkey), registrant.Data, privateKeyString)
if err != nil {
return fmt.Errorf("%v", err)
}
registrant.Signature, err = hex.DecodeString(hexOwnerSig)
if err != nil {
return fmt.Errorf("%v", err)
}
registrantBytes, err := proto.Marshal(®istrant)
registrantBytesStr := hex.EncodeToString(registrantBytes)
_, err = stub.MockInvoke("3", "createRegistrant", []string{registrantBytesStr})
if err != nil {
return fmt.Errorf("%v", err)
}
return nil
}
/*
registers a store type "Things" to ledger and an "Alias" store type for each member of string slice aliases by calling to Invoke()
*/
func registerThing(t *testing.T, stub *shim.MockStub, nonce []byte, aliases []string,
registrantPubKey string, spec string, data string, privateKeyString string) error {
thing := IOTRegistryTX.RegisterThingTX{}
thing.Nonce = nonce
thing.Aliases = aliases
thing.RegistrantPubkey = registrantPubKey
thing.Spec = spec
//create signature
hexThingSig, err := generateRegisterThingSig(registrantPubKey, aliases, spec, data, privateKeyString)
if err != nil {
return fmt.Errorf("%v", err)
}
thing.Signature, err = hex.DecodeString(hexThingSig)
if err != nil {
return fmt.Errorf("%v", err)
}
thing.Data = data
thingBytes, err := proto.Marshal(&thing)
thingBytesStr := hex.EncodeToString(thingBytes)
_, err = stub.MockInvoke("3", "registerThing", []string{thingBytesStr})
if err != nil {
return fmt.Errorf("%v", err)
}
return nil
}
/*
registers a store type "Spec" to ledger by calling to Invoke()
*/
func registerSpec(t *testing.T, stub *shim.MockStub, specName string, registrantPubkey string,
data string, privateKeyString string) error {
registerSpec := IOTRegistryTX.RegisterSpecTX{}
registerSpec.SpecName = specName
registerSpec.RegistrantPubkey = registrantPubkey
registerSpec.Data = data
//create signature
hexSpecSig, err := generateRegisterSpecSig(specName, registrantPubkey, data, privateKeyString)
if err != nil {
return fmt.Errorf("%v", err)
}
registerSpec.Signature, err = hex.DecodeString(hexSpecSig)
if err != nil {
return fmt.Errorf("%v", err)
}
registerSpecBytes, err := proto.Marshal(®isterSpec)
registerSpecBytesStr := hex.EncodeToString(registerSpecBytes)
_, err = stub.MockInvoke("3", "registerSpec", []string{registerSpecBytesStr})
if err != nil {
return fmt.Errorf("%v", err)
}
return nil
}
/*
tests whether two string slices are identical, returning true or false
*/
func testEq(a, b []string) bool {
if a == nil && b == nil {
return true
}
if a == nil || b == nil {
return false
}
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
/*
Checks that different queries return expected values.
*/
func checkQuery(t *testing.T, stub *shim.MockStub, function string, index string, expected registryTest) error {
var err error = nil
var bytes []byte
bytes, err = stub.MockQuery(function, []string{index})
if err != nil {
return fmt.Errorf("Query (%s):%s failed\n", function, err.Error())
}
if bytes == nil {
return fmt.Errorf("Query (%s):%s failed to get value\n", function, err.Error())
}
var jsonMap map[string]interface{}
if err := json.Unmarshal(bytes, &jsonMap); err != nil {
return fmt.Errorf("error unmarshalling json string %s", bytes)
}
fmt.Printf("JSON: %s\n", jsonMap)
if function == "owner" {
if jsonMap["RegistrantName"] != expected.RegistrantName {
return fmt.Errorf("\nRegistrantName got (%s)\nRegistrantName expected: (%s)\n", jsonMap["RegistrantName"], expected.RegistrantName)
}
if jsonMap["Pubkey"] != expected.pubKeyString {
return fmt.Errorf("\nPubkey got (%s)\nPubkey expected: (%s)\n", jsonMap["Pubkey"], expected.pubKeyString)
}
} else if function == "thing" {
aliases := make([]string, len(jsonMap["Aliases"].([]interface{})))
for i, element := range jsonMap["Aliases"].([]interface{}) {
aliases[i] = element.(string)
}
if !(reflect.DeepEqual(aliases, expected.aliases)) {
return fmt.Errorf("\nAlias got (%x)\nAlias expected: (%x)\n", jsonMap["Aliases"], expected.aliases)
}
if jsonMap["RegistrantPubkey"] != expected.pubKeyString {
return fmt.Errorf("\nRegistrantPubkey got (%s)\nRegistrantPubkey expected: (%s)\n", jsonMap["RegistrantPubkey"], expected.pubKeyString)
}
if jsonMap["Data"] != expected.data {
return fmt.Errorf("\nData got (%s)\nData expected: (%s)\n", jsonMap["Data"], expected.data)
}
if jsonMap["SpecName"] != expected.specName {
return fmt.Errorf("\nSpecName got (%s)\nSpecName expected: (%s)\n", jsonMap["SpecName"], expected.specName)
}
} else if function == "spec" {
if jsonMap["RegistrantPubkey"] != expected.pubKeyString {
return fmt.Errorf("\nRegistrantPubkey got (%s)\nRegistrantPubkey expected: (%s)\n", jsonMap["RegistrantPubkey"], expected.pubKeyString)
}
if jsonMap["Data"] != expected.data {
return fmt.Errorf("\nData got (%s)\nData expected: (%s)\n", jsonMap["Data"], expected.data)
}
}
return nil
}
func HandleError(t *testing.T, err error) (b bool) {
if err != nil {
_, fn, line, _ := runtime.Caller(1)
re := regexp.MustCompile("[^/]+$")
t.Errorf("\x1b[32m\n[ERROR] in %s\tat line: %d\n%v\x1b[0m\n\n", re.FindAllString(fn, -1)[0], line, err)
b = true
}
return
}
type registryTest struct {
privateKeyString string
pubKeyString string
RegistrantName string
data string
nonce string
specName string
aliases []string
}
/*
runs tests for four different hypothetical users: Alice, Gerald, Bob, and Cassandra
*/
func TestIOTRegistryChaincode(t *testing.T) {
//declaring and initializing variables for all tests
bst := new(IOTRegistry)
stub := shim.NewMockStub("IOTRegistry", bst)
var registryTestsSuccess = []registryTest{
{ /*private key 1*/ "94d7fe7308a452fdf019a0424d9c48ba9b66bdbca565c6fa3b1bf9c646ebac20",
/*public key 1*/ "02ca4a8c7dc5090f924cde2264af240d76f6d58a5d2d15c8c5f59d95c70bd9e4dc",
"Alice", "test data" /*nonce:*/, "1f7b169c846f218ab552fa82fbf86758", "test spec", []string{"Foo", "Bar"}},
{ /*private key 2*/ "246d4fa59f0baa3329d3908659936ac2ac9c3539dc925977759cffe3c6316e19",
/*public key 2*/ "03442b817ad2154766a8f5192fc5a7506b7e52cdbf4fcf8e1bc33764698443c3c9",
"Gerald", "test data 1" /*nonce:*/, "bf5c97d2d2a313e4f95957818a7b3edc", "test spec 2", []string{"one", "two", "three"}},
{ /*private key 3*/ "166cc93d9eadb573b329b5993b9671f1521679cea90fe52e398e66c1d6373abf",
/*public key 3*/ "02242a1c19bc831cd95a9e5492015043250cbc17d0eceb82612ce08736b8d753a6",
"Bob", "test data 2" /*nonce:*/, "a492f2b8a67697c4f91d9b9332e82347", "test spec 3", []string{"ident4", "ident5", "ident6"}},
{ /*private key 4*/ "01b756f231c72747e024ceee41703d9a7e3ab3e68d9b73d264a0196bd90acedf",
/*public key 4*/ "020f2b95263c4b3be740b7b3fda4c2f4113621c1a7a360713a2540eeb808519cd6",
"Cassandra", "test data 3" /*nonce:*/, "83de17bd7a25e0a9f6813976eadf26de", "test spec 4", []string{"ident7", "ident8", "ident9"}},
}
for _, test := range registryTestsSuccess {
err := createRegistrant(t, stub, test.RegistrantName, test.data, test.privateKeyString, test.pubKeyString)
if err != nil {
HandleError(t, fmt.Errorf("%v\n", err))
return
}
index := test.pubKeyString
err = checkQuery(t, stub, "owner", index, test)
if err != nil {
HandleError(t, fmt.Errorf("%v\n", err))
}
nonceBytes, err := hex.DecodeString(test.nonce)
if err != nil {
HandleError(t, fmt.Errorf("Error decoding nonce bytes: %s", err.Error()))
}
err = registerThing(t, stub, nonceBytes, test.aliases, test.pubKeyString, test.specName, test.data, test.privateKeyString)
if err != nil {
HandleError(t, fmt.Errorf("%v\n", err))
}
for _, alias := range test.aliases {
err = checkQuery(t, stub, "thing", alias, test)
if err != nil {
HandleError(t, fmt.Errorf("%v\n", err))
}
}
err = registerSpec(t, stub, test.specName, test.pubKeyString, test.data, test.privateKeyString)
if err != nil {
HandleError(t, fmt.Errorf("%v\n", err))
}
index = test.specName
err = checkQuery(t, stub, "spec", index, test)
if err != nil {
HandleError(t, fmt.Errorf("%v\n", err))
}
}
}
|
package leetcode
import "sort"
func findKthNumber(m int, n int, k int) int {
// 给定一个数x,求矩阵中 <=x 的数的个数,利用右上角二分
lessEqual := func(x int) int {
i := 0
j := n - 1
count := 0
for i < m && j >= 0 {
num := (i + 1) * (j + 1)
if num <= x {
count += j + 1
i++
} else {
j--
}
}
return count
}
// 二分找到 [0, m*n] 中,第一个满足条件的x
return sort.Search(m*n+1, func(x int) bool {
return lessEqual(x) >= k
})
}
|
package orderbook
import (
"math/rand"
)
// OrderID is an order id.
type OrderID int
// Side is a side.
type Side bool
// Bid means you are buying.
const Bid Side = false
// Ask means you are selling.
const Ask Side = true
// order is a single order in the book.
type order struct {
id OrderID
side Side
price uint
size uint
next *order
prev *order
}
// genID returns a psuedo-random 8-digit order id.
func genID() OrderID {
return OrderID(10000000 + rand.Intn(99999999-10000000))
}
|
package db
import (
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
"log"
)
var db *sqlx.DB
func init() {
var err error
db, err = sqlx.Open("postgres", "dbname=govhack user=postgres password=iamagopher host=103.241.200.20 sslmode=disable")
if err != nil {
log.Fatal(err)
}
}
func Client() *sqlx.DB {
return db
}
|
package url_translater
type URL struct {
Id int
LongUrl string
ShortURL string
}
type ShortURL struct {
Id int `json:"-" db:"id"`
LinkUrl string `json:"url" db:"short_url" binding:"required"`
}
type LongURL struct {
Id int `json:"-" db:"id"`
LinkUrl string `json:"url" db:"long_url" binding:"required"`
}
|
package maccount
import (
"time"
"webserver/lib/jsonlib"
"webserver/models"
)
type Selection struct {
//RecordBase
Id int
UserId int
Type int
Value int
Info string
Image string
Extra string
Status int
CreatedAt time.Time //string
UpdatedAt time.Time //string
extra *jsonlib.ParsedJson
}
func FindSelectionByStatus(htype, status interface{}, offset, limit int) ([]Selection, error) {
var auth []Selection
err := models.GetDb().Where("`type` = ? and status = ?", htype, status).Order("id asc").Offset(offset).Limit(limit).Find(&auth).Error
return auth, err
}
func FindSelectionByUserId(userId, htype interface{}) ([]Selection, error) {
var auth []Selection
err := models.GetDb().Where("user_id = ? and `type` = ?", userId, htype).Order("id desc").Find(&auth).Error
return auth, err
}
func FindSelectionCount(htype, status interface{}) int {
var count int
models.GetDb().Table("authenticates").Where("`type` = ? and status = ?", htype, status).Count(&count)
return count
}
func (self *Selection) GetExtra() *jsonlib.ParsedJson {
if self.extra == nil {
self.extra, _ = jsonlib.NewJson(self.Extra)
}
return self.extra
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.