code
stringlengths 67
15.9k
| labels
listlengths 1
4
|
---|---|
package main
import "fmt"
func main() {
fmt.Println("Введите координату X:")
var x int
fmt.Scan(&x)
fmt.Println("Введите координату Y:")
var y int
fmt.Scan(&y)
if x == 0 && y == 0 {
fmt.Println("Точка лежит в начале координат")
} else if x == 0 || y == 0 {
fmt.Println("Точка находится на координатной оси")
} else if x < 0 && y > 0 {
fmt.Println("Точка находится в первой четверти")
} else if x > 0 && y > 0 {
fmt.Println("Точка находится во второй четверти")
} else if x > 0 && y < 0 {
fmt.Println("Точка находится в третьей четверти")
} else {
fmt.Println("Точка находится в четвертой четверти")
}
}
|
[
5
] |
package policy
import (
"strings"
"testing"
"github.com/mholt/caddy"
)
func TestPolicyConfigParse(t *testing.T) {
tests := []struct {
input string
endpoints []string
errContent string
}{
{
input: `.:53 {
log stdout
}`,
errContent: "Policy setup called without keyword 'policy' in Corefile",
},
{
input: `.:53 {
policy {
error option
}
}`,
errContent: "invalid policy plugin option",
},
{
input: `.:53 {
policy {
endpoint
}
}`,
errContent: "Wrong argument count or unexpected line ending",
},
{
input: `.:53 {
policy {
endpoint 10.2.4.1:5555
}
}`,
endpoints: []string{"10.2.4.1:5555"},
},
{
input: `.:53 {
policy {
endpoint 10.2.4.1:5555 10.2.4.2:5555
}
}`,
endpoints: []string{"10.2.4.1:5555", "10.2.4.2:5555"},
},
{
input: `.:53 {
policy {
endpoint 10.2.4.1:5555
edns0 0xfff0 uid hex string wrong_size 0 32
}
}`,
endpoints: []string{"10.2.4.1:5555"},
errContent: "Could not parse EDNS0 data size",
},
{
input: `.:53 {
policy {
endpoint 10.2.4.1:5555
edns0 0xfff0 uid hex string 32 0 32
}
}`,
endpoints: []string{"10.2.4.1:5555"},
},
{
input: `.:53 {
policy {
endpoint 10.2.4.1:5555
edns0 wrong_hex uid hex string
}
}`,
endpoints: []string{"10.2.4.1:5555"},
errContent: "Could not parse EDNS0 code",
},
{
input: `.:53 {
policy {
endpoint 10.2.4.1:5555
edns0 0xfff0 uid hex string 32 wrong_offset 32
}
}`,
endpoints: []string{"10.2.4.1:5555"},
errContent: "Could not parse EDNS0 start index",
},
{
input: `.:53 {
policy {
endpoint 10.2.4.1:5555
edns0 0xfff0 uid hex string 32 0 wrong_size
}
}`,
endpoints: []string{"10.2.4.1:5555"},
errContent: "Could not parse EDNS0 end index",
},
{
input: `.:53 {
policy {
endpoint 10.2.4.1:5555
edns0 0xfff0 uid hex string 32 0 16
edns0 0xfff0 id hex string 32 16 32
}
}`,
endpoints: []string{"10.2.4.1:5555"},
},
{
input: `.:53 {
policy {
endpoint 10.2.4.1:5555
edns0 0xfff0 uid hex string 32 16 15
}
}`,
endpoints: []string{"10.2.4.1:5555"},
errContent: "End index should be > start index",
},
{
input: `.:53 {
policy {
endpoint 10.2.4.1:5555
edns0 0xfff0 uid hex string 32 0 33
}
}`,
endpoints: []string{"10.2.4.1:5555"},
errContent: "End index should be <= size",
},
{
input: `.:53 {
policy {
endpoint 10.2.4.1:5555
edns0 0xfff1
}
}`,
endpoints: []string{"10.2.4.1:5555"},
errContent: "Invalid edns0 directive",
},
{
input: `.:53 {
policy {
endpoint 10.2.4.1:5555
edns0 0xfff1 guid bin bin
}
}`,
endpoints: []string{"10.2.4.1:5555"},
errContent: "Could not add EDNS0 map",
},
{
input: `.:53 {
policy {
endpoint 10.2.4.1:5555
debug_query_suffix
}
}`,
endpoints: []string{"10.2.4.1:5555"},
errContent: "Wrong argument count or unexpected line ending",
},
{
input: `.:53 {
policy {
endpoint 10.2.4.1:5555
debug_query_suffix debug.local.
}
}`,
endpoints: []string{"10.2.4.1:5555"},
},
{
input: `.:53 {
policy {
endpoint 10.2.4.1:5555
streams 10
}
}`,
endpoints: []string{"10.2.4.1:5555"},
},
{
input: `.:53 {
policy {
endpoint 10.2.4.1:5555
streams Ten
}
}`,
endpoints: []string{"10.2.4.1:5555"},
errContent: "Could not parse number of streams",
},
{
input: `.:53 {
policy {
endpoint 10.2.4.1:5555
streams
}
}`,
endpoints: []string{"10.2.4.1:5555"},
errContent: "Wrong argument count or unexpected line ending",
},
{
input: `.:53 {
policy {
endpoint 10.2.4.1:5555
streams -1
}
}`,
endpoints: []string{"10.2.4.1:5555"},
errContent: "Expected at least one stream got -1",
},
{
input: `.:53 {
policy {
endpoint 10.2.4.1:5555
streams 10 Round-Robin
}
}`,
endpoints: []string{"10.2.4.1:5555"},
},
{
input: `.:53 {
policy {
endpoint 10.2.4.1:5555
streams 10 Hot-Spot
}
}`,
endpoints: []string{"10.2.4.1:5555"},
},
{
input: `.:53 {
policy {
endpoint 10.2.4.1:5555
streams 10 Unknown-Balancer
}
}`,
endpoints: []string{"10.2.4.1:5555"},
errContent: "Expected round-robin or hot-spot balancing but got Unknown-Balancer",
},
{
input: `.:53 {
policy {
endpoint 10.2.4.1:5555
transfer policy_id
}
}`,
endpoints: []string{"10.2.4.1:5555"},
},
{
input: `.:53 {
policy {
endpoint 10.2.4.1:5555
transfer
}
}`,
endpoints: []string{"10.2.4.1:5555"},
errContent: "Wrong argument count or unexpected line ending",
},
}
for _, test := range tests {
c := caddy.NewTestController("dns", test.input)
mw, err := policyParse(c)
if err != nil {
if len(test.errContent) > 0 {
if !strings.Contains(err.Error(), test.errContent) {
t.Errorf("Expected error '%v' but got '%v'\n", test.errContent, err)
}
} else {
t.Errorf("Expected no error but got '%v'\n", err)
}
} else {
if len(test.errContent) > 0 {
t.Errorf("Expected error '%v' but got 'nil'\n", test.errContent)
} else if len(test.endpoints) != len(mw.endpoints) {
t.Errorf("Expected endpoints %v but got %v\n", test.endpoints, mw.endpoints)
} else {
for i := 0; i < len(test.endpoints); i++ {
if test.endpoints[i] != mw.endpoints[i] {
t.Errorf("Expected endpoint '%s' but got '%s'\n", test.endpoints[i], mw.endpoints[i])
}
}
}
}
}
}
|
[
5
] |
package P404
import (
"github.com/ssr66994053/go-leetcode/model"
)
func sumOfLeftLeaves(root *model.TreeNode) int {
if root == nil {
return 0
}
n := 0
if root.Left != nil {
root.Val = 0
left := root.Left
if left.Left == nil && left.Right == nil {
n = left.Val
} else {
n = sumOfLeftLeaves(left)
}
}
if root.Right != nil {
root.Val = 0
right := root.Right
if right.Left != nil || right.Right != nil {
n = n + sumOfLeftLeaves(right)
}
}
return n
}
|
[
0
] |
package common
import (
"fmt"
"errors"
"sync"
)
type LinkedList struct {
head *lNode
tail *lNode
length int64
lock sync.RWMutex
}
type lNode struct {
Value interface{}
next *lNode
pre *lNode
}
func CreateLinkedList() LinkedList{
return LinkedList{length:0}
}
func (this *LinkedList)IsEmpty() bool{
return this.length == 0
}
func (this *LinkedList)Lpush(v interface{})(error){
defer this.lock.Unlock()
this.lock.Lock()
if v == nil{
return errors.New("push an empty element")
}
node := &lNode{Value:v}
if(this.IsEmpty()){
this.tail = node
}else {
this.head.pre = node
node.next=this.head
}
this.head = node
this.length += 1
return nil
}
func (this *LinkedList)Lpop()(interface{}){
defer this.lock.Unlock()
this.lock.Lock()
if(this.IsEmpty()){
return nil
}
this.length-=1
v := this.head.Value
if (this.head == this.tail){
this.head = nil
this.tail = nil
return v
}
this.head = this.head.next
this.head.pre.next = nil
this.head.pre = nil
return v
}
func (this *LinkedList)Rpush(v interface{})(error){
defer this.lock.Unlock()
this.lock.Lock()
node := &lNode{Value:v}
if(this.IsEmpty()){
this.head = node
}else {
this.tail.next = node
node.pre = this.tail
}
this.tail = node
this.length += 1
return nil
}
func (this *LinkedList)Rpop()(interface{}){
if(this.IsEmpty()){
return nil
}
this.length-=1
v := this.tail.Value
if (this.head == this.tail){
this.head = nil
this.tail = nil
return v
}
this.tail = this.tail.pre
this.tail.next.pre = nil
this.tail.next = nil
return v
}
func (this *LinkedList)PrintList(){
if this.IsEmpty(){
fmt.Println("<nil>")
return
}
node := this.head
fmt.Print("[")
for node != this.tail{
fmt.Print(node.Value)
fmt.Print(",")
node = node.next
}
fmt.Print(this.tail.Value)
fmt.Print("]")
}
func (this *LinkedList)LpopN(n int64)([]interface{}){
defer this.lock.Unlock()
this.lock.Lock()
if(this.length == 0 || n <= 0){
return nil
}
if(this.length < n){
n = this.length
}
this.length = this.length-n
res := make([]interface{},n)
var i int64
node := this.head
res[0] = node.Value
for i = 1; i < n; i++{
res[i] = node.next.Value
node = node.next
node.pre.next = nil
node.pre = nil
}
this.head = node
if(node == nil){
this.tail = nil
}
return res
}
func (this *LinkedList)RpopN(n int64)([]interface{}){
defer this.lock.Unlock()
this.lock.Lock()
if(this.length == 0 || n <= 0){
return nil
}
if(this.length < n){
n = this.length
}
this.length = this.length-n
res := make([]interface{},n)
var i int64
node := this.tail
res[0] = node.Value
for i = 1; i < n; i++{
res[i] = node.pre.Value
node = node.pre
node.next.pre = nil
node.next = nil
}
this.tail = node
if(node == nil){
this.head = nil
}
return res
}
func (this *LinkedList)Add(v interface{}){
this.Rpush(v)
}
func (this *LinkedList)Set(index int64, v interface{}) error{
defer this.lock.Unlock()
this.lock.Lock()
if this.length <= index{
return errors.New("index of slide")
}
var i int64 = 0
var nodeP *lNode = this.head
for ;i < index; i++{
nodeP = nodeP.next
}
nodeP.Value = v
return nil
}
func (this *LinkedList)Remove(index int64) (interface{},error){
defer this.lock.Unlock()
this.lock.Lock()
if this.length <= index{
return nil,errors.New("index of slide")
}
var i int64 = 0
var nodeP *lNode = this.head
for ;i < index-1; i++{
nodeP = nodeP.next
}
rNode := nodeP.next
nodeP.next = rNode.next
nodeP.next.pre = nodeP
rNode.pre =nil
rNode.next = nil
return rNode.Value,nil
}
|
[
0
] |
package model
import "github.com/nlopes/slack"
type Text struct {
Text string `json:"text"`
}
func NewText(text string) Text {
return Text{Text: text}
}
func NewTextMessageRequest(Token, Sender, Channel, Receiver string, ephemeral bool, message Text) *MessageRequest {
return &MessageRequest{
Token: Token,
Sender: Sender,
Channel: Channel,
Receiver: Receiver,
Type: TEXT,
Ephemeral: ephemeral,
Message: &message,
}
}
func (obj *Text) getBlocks() []slack.Block {
text := slack.NewSectionBlock(
slack.NewTextBlockObject("plain_text", obj.Text, false, false),
nil,
nil)
return []slack.Block{text}
}
|
[
2
] |
package tdproxy
import (
"errors"
"github.com/refraction-networking/gotapdance/tapdance"
"io"
"net"
"strconv"
"strings"
"time"
)
// Connection-oriented state
type tapDanceFlow struct {
// tunnel index and start time
id uint64
startMs time.Time
// reference to global proxy
proxy *TapDanceProxy
servConn net.Conn // can cast to tapdance.Conn but don't need to
userConn net.Conn
splitFlows bool
}
// TODO: use dial() functor
func makeTapDanceFlow(proxy *TapDanceProxy, id uint64, splitFlows bool) *tapDanceFlow {
tdFlow := new(tapDanceFlow)
tdFlow.proxy = proxy
tdFlow.id = id
tdFlow.startMs = time.Now()
tdFlow.splitFlows = splitFlows
Logger.Debugf("Created new TD Flow: %#v\n", tdFlow)
return tdFlow
}
func (TDstate *tapDanceFlow) redirect() error {
dialer := tapdance.Dialer{SplitFlows: TDstate.splitFlows, DarkDecoy: true}
var err error
TDstate.servConn, err = dialer.DialProxy()
if err != nil {
TDstate.userConn.Close()
return err
}
errChan := make(chan error)
defer func() {
TDstate.userConn.Close()
TDstate.servConn.Close()
_ = <-errChan // wait for second goroutine to close
}()
forwardFromServerToClient := func() {
buf := make([]byte, 65536)
n, _err := io.CopyBuffer(TDstate.userConn, TDstate.servConn, buf)
Logger.Debugf("{tapDanceFlow} forwardFromServerToClient returns, bytes sent: " +
strconv.FormatUint(uint64(n), 10))
if _err == nil {
_err = errors.New("server returned without error")
}
errChan <- _err
return
}
forwardFromClientToServer := func() {
buf := make([]byte, 65536)
n, _err := io.CopyBuffer(TDstate.servConn, TDstate.userConn, buf)
Logger.Debugf("{tapDanceFlow} forwardFromClientToServer returns, bytes sent: " +
strconv.FormatUint(uint64(n), 10))
if _err == nil {
_err = errors.New("closed by application layer")
}
errChan <- _err
return
}
go forwardFromServerToClient()
go forwardFromClientToServer()
if err = <-errChan; err != nil {
if err.Error() == "MSG_CLOSE" || err.Error() == "closed by application layer" {
Logger.Debugln("[Session " + strconv.FormatUint(uint64(TDstate.id), 10) +
" Redirect function returns gracefully: " + err.Error())
TDstate.proxy.closedGracefully.Inc()
err = nil
} else {
str_err := err.Error()
// statistics
if strings.Contains(str_err, "TapDance station didn't pick up the request") {
TDstate.proxy.notPickedUp.Inc()
} else if strings.Contains(str_err, ": i/o timeout") {
TDstate.proxy.timedOut.Inc()
} else {
TDstate.proxy.unexpectedError.Inc()
}
}
}
return err
}
|
[
2,
5
] |
// Copyright © 2019 The Things Network Foundation, The Things Industries B.V.
//
// 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 lorawan
import (
"go.thethings.network/lorawan-stack/v3/pkg/errors"
)
var (
errDecode = errors.Define("decode", "could not decode `{lorawan_field}`")
errEncode = errors.Define("encode", "could not encode `{lorawan_field}`")
errEncodedFieldLengthBound = errors.DefineInvalidArgument("encoded_field_length_bound", "`{lorawan_field}` encoded length `{value}` should between `{min}` and `{max}`", valueKey)
errEncodedFieldLengthEqual = errors.DefineInvalidArgument("encoded_field_length_equal", "`{lorawan_field}` encoded length `{value}` should be `{expected}`", valueKey)
errEncodedFieldLengthTwoChoices = errors.DefineInvalidArgument("encoded_field_length_multiple_choices", "`{lorawan_field}` encoded length `{value}` should be equal to `{expected_1}` or `{expected_2}`", valueKey)
errFieldBound = errors.DefineInvalidArgument("field_bound", "`{lorawan_field}` should be between `{min}` and `{max}`", valueKey)
errFieldHasMax = errors.DefineInvalidArgument("field_with_max", "`{lorawan_field}` value `{value}` should be lower or equal to `{max}`", valueKey)
errFieldLengthEqual = errors.DefineInvalidArgument("field_length_equal", "`{lorawan_field}` length `{value}` should be equal to `{expected}`", valueKey)
errFieldLengthHasMax = errors.DefineInvalidArgument("field_length_with_max", "`{lorawan_field}` length `{value}` should be lower or equal to `{max}`", valueKey)
errFieldLengthHasMin = errors.DefineInvalidArgument("field_length_with_min", "`{lorawan_field}` length `{value}` should be higher or equal to `{min}`", valueKey)
errFieldLengthTwoChoices = errors.DefineInvalidArgument("field_length_with_multiple_choices", "`{lorawan_field}` length `{value}` should be equal to `{expected_1}` or `{expected_2}`", valueKey)
errUnknownField = errors.DefineInvalidArgument("unknown_field", "unknown `{lorawan_field}`", valueKey)
errProprietary = errors.DefineInvalidArgument("proprietary", "expected standard LoRaWAN frame")
)
const valueKey = "value"
type valueErr func(any) *errors.Error
func unexpectedValue(err interface {
WithAttributes(kv ...any) *errors.Error
},
) valueErr {
return func(value any) *errors.Error {
return err.WithAttributes(valueKey, value)
}
}
func errExpectedLowerOrEqual(lorawanField string, max any) valueErr {
return unexpectedValue(errFieldHasMax.WithAttributes("lorawan_field", lorawanField, "max", max))
}
func errExpectedLengthEqual(lorawanField string, expected any) valueErr {
return unexpectedValue(errFieldLengthEqual.WithAttributes("lorawan_field", lorawanField, "expected", expected))
}
func errExpectedLengthLowerOrEqual(lorawanField string, max any) valueErr {
return unexpectedValue(errFieldLengthHasMax.WithAttributes("lorawan_field", lorawanField, "max", max))
}
func errExpectedLengthHigherOrEqual(lorawanField string, min any) valueErr {
return unexpectedValue(errFieldLengthHasMin.WithAttributes("lorawan_field", lorawanField, "min", min))
}
func errExpectedLengthTwoChoices(lorawanField string, expected1, expected2 any) valueErr {
return unexpectedValue(errFieldLengthTwoChoices.WithAttributes("lorawan_field", lorawanField, "expected_1", expected1, "expected_2", expected2))
}
func errExpectedLengthEncodedBound(lorawanField string, min, max any) valueErr {
return unexpectedValue(errEncodedFieldLengthBound.WithAttributes("lorawan_field", lorawanField, "min", min, "max", max))
}
func errExpectedLengthEncodedEqual(lorawanField string, expected any) valueErr {
return unexpectedValue(errEncodedFieldLengthEqual.WithAttributes("lorawan_field", lorawanField, "expected", expected))
}
func errExpectedLengthEncodedTwoChoices(lorawanField string, expected1, expected2 any) valueErr {
return unexpectedValue(errEncodedFieldLengthTwoChoices.WithAttributes("lorawan_field", lorawanField, "expected_1", expected1, "expected_2", expected2))
}
func errFailedEncoding(lorawanField string) *errors.Error {
return errEncode.WithAttributes("lorawan_field", lorawanField)
}
func errFailedDecoding(lorawanField string) *errors.Error {
return errDecode.WithAttributes("lorawan_field", lorawanField)
}
func errUnknown(lorawanField string) valueErr {
return unexpectedValue(errUnknownField.WithAttributes("lorawan_field", lorawanField))
}
func errMissing(lorawanField string) *errors.Error {
return errUnknownField.WithAttributes("lorawan_field", lorawanField)
}
func errExpectedBetween(lorawanField string, min, max any) valueErr {
return unexpectedValue(errFieldBound.WithAttributes("lorawan_field", lorawanField, "min", min, "max", max))
}
|
[
1
] |
// Copyright 2019-present Open Networking Foundation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law 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 runner
import (
"bytes"
"encoding/json"
"fmt"
"strconv"
"time"
"k8s.io/apimachinery/pkg/labels"
"gopkg.in/yaml.v1"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
)
// setupOnosConfig sets up the onos-config Deployment
func (c *ClusterController) setupOnosConfig() error {
if err := c.createOnosConfigConfigMap(); err != nil {
return err
}
if err := c.createOnosConfigService(); err != nil {
return err
}
if err := c.createOnosConfigDeployment(); err != nil {
return err
}
if err := c.awaitOnosConfigDeploymentReady(); err != nil {
return err
}
return nil
}
// createOnosConfigConfigMap creates a ConfigMap for the onos-config Deployment
func (c *ClusterController) createOnosConfigConfigMap() error {
config, err := c.config.load()
if err != nil {
return err
}
// Serialize the change store configuration
changeStore, err := json.Marshal(config["changeStore"])
if err != nil {
return err
}
// Serialize the network store configuration
networkStore, err := json.Marshal(config["networkStore"])
if err != nil {
return err
}
// Serialize the device store configuration
deviceStore, err := json.Marshal(config["deviceStore"])
if err != nil {
return err
}
// Serialize the config store configuration
configStore, err := json.Marshal(config["configStore"])
if err != nil {
return err
}
cm := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "onos-config",
Namespace: c.clusterID,
},
Data: map[string]string{
"changeStore.json": string(changeStore),
"configStore.json": string(configStore),
"deviceStore.json": string(deviceStore),
"networkStore.json": string(networkStore),
},
}
_, err = c.kubeclient.CoreV1().ConfigMaps(c.clusterID).Create(cm)
return err
}
// addSimulatorToConfig adds a simulator to the onos-config configuration
func (c *ClusterController) addSimulatorToConfig(name string) error {
labelSelector := metav1.LabelSelector{MatchLabels: map[string]string{"app": "onos", "type": "config"}}
pods, err := c.kubeclient.CoreV1().Pods(c.clusterID).List(metav1.ListOptions{
LabelSelector: labels.Set(labelSelector.MatchLabels).String(),
})
if err != nil {
return err
}
for _, pod := range pods.Items {
if err = c.addSimulatorToPod(name, pod); err != nil {
return err
}
}
return nil
}
// addNetworkToConfig adds a network to the onos-config configuration
func (c *ClusterController) addNetworkToConfig(name string, config *NetworkConfig) error {
labelSelector := metav1.LabelSelector{MatchLabels: map[string]string{"app": "onos", "type": "config"}}
pods, err := c.kubeclient.CoreV1().Pods(c.clusterID).List(metav1.ListOptions{
LabelSelector: labels.Set(labelSelector.MatchLabels).String(),
})
if err != nil {
return err
}
for _, pod := range pods.Items {
var port = 50001
for i := 0; i < config.NumDevices; i++ {
var buf bytes.Buffer
buf.WriteString(name)
buf.WriteString("-s")
buf.WriteString(strconv.Itoa(i))
deviceName := buf.String()
if err = c.addNetworkToPod(deviceName, port, pod); err != nil {
return err
}
port = port + 1
}
}
return nil
}
// addSimulatorToPod adds the given simulator to the given pod's configuration
func (c *ClusterController) addSimulatorToPod(name string, pod corev1.Pod) error {
command := fmt.Sprintf("onos devices add \"id: '%s', address: '%s:10161' version: '1.0.0' devicetype: 'Devicesim'\" --address 127.0.0.1:5150 --keyPath /etc/onos-config/certs/client1.key --certPath /etc/onos-config/certs/client1.crt", name, name)
return c.execute(pod, []string{"/bin/bash", "-c", command})
}
// addNetworkToPod adds the given network to the given pod's configuration
func (c *ClusterController) addNetworkToPod(name string, port int, pod corev1.Pod) error {
command := fmt.Sprintf("onos devices add \"id: '%s', address: '%s:%s' version: '1.0.0' devicetype: 'Stratum'\" --address 127.0.0.1:5150 --keyPath /etc/onos-config/certs/client1.key --certPath /etc/onos-config/certs/client1.crt", name, name, strconv.Itoa(port))
return c.execute(pod, []string{"/bin/bash", "-c", command})
}
// removeSimulatorFromConfig removes a simulator from the onos-config configuration
func (c *ClusterController) removeSimulatorFromConfig(name string) error {
labelSelector := metav1.LabelSelector{MatchLabels: map[string]string{"app": "onos", "type": "config"}}
pods, err := c.kubeclient.CoreV1().Pods(c.clusterID).List(metav1.ListOptions{
LabelSelector: labels.Set(labelSelector.MatchLabels).String(),
})
if err != nil {
return err
}
for _, pod := range pods.Items {
if err = c.removeSimulatorFromPod(name, pod); err != nil {
return err
}
}
return nil
}
// removeNetworkFromConfig removes a network from the onos-config configuration
func (c *ClusterController) removeNetworkFromConfig(name string, configMap *corev1.ConfigMapList) error {
labelSelector := metav1.LabelSelector{MatchLabels: map[string]string{"app": "onos", "type": "config"}}
pods, err := c.kubeclient.CoreV1().Pods(c.clusterID).List(metav1.ListOptions{
LabelSelector: labels.Set(labelSelector.MatchLabels).String(),
})
if err != nil {
return err
}
dataMap := configMap.Items[0].BinaryData["config"]
m := make(map[string]interface{})
err = yaml.Unmarshal(dataMap, &m)
if err != nil {
return err
}
numDevices := m["numdevices"].(int)
for _, pod := range pods.Items {
for i := 0; i < numDevices; i++ {
var buf bytes.Buffer
buf.WriteString(name)
buf.WriteString("-s")
buf.WriteString(strconv.Itoa(i))
deviceName := buf.String()
if err = c.removeNetworkFromPod(deviceName, pod); err != nil {
return err
}
}
}
return nil
}
// removeSimulatorFromPod removes the given simulator from the given pod
func (c *ClusterController) removeSimulatorFromPod(name string, pod corev1.Pod) error {
command := fmt.Sprintf("onos devices remove %s --address 127.0.0.1:5150 --keyPath /etc/onos-config/certs/client1.key --certPath /etc/onos-config/certs/client1.crt", name)
return c.execute(pod, []string{"/bin/bash", "-c", command})
}
// removeNetworkFromPod removes the given network from the given pod
func (c *ClusterController) removeNetworkFromPod(name string, pod corev1.Pod) error {
command := fmt.Sprintf("onos devices remove %s --address 127.0.0.1:5150 --keyPath /etc/onos-config/certs/client1.key --certPath /etc/onos-config/certs/client1.crt", name)
return c.execute(pod, []string{"/bin/bash", "-c", command})
}
// createOnosConfigDeployment creates an onos-config Deployment
func (c *ClusterController) createOnosConfigDeployment() error {
nodes := int32(c.config.ConfigNodes)
zero := int64(0)
dep := &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: "onos-config",
Namespace: c.clusterID,
},
Spec: appsv1.DeploymentSpec{
Replicas: &nodes,
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"app": "onos",
"type": "config",
},
},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
"app": "onos",
"type": "config",
"resource": "onos-config",
},
Annotations: map[string]string{
"seccomp.security.alpha.kubernetes.io/pod": "unconfined",
},
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{
Name: "onos-config",
Image: "onosproject/onos-config:debug",
ImagePullPolicy: corev1.PullIfNotPresent,
Env: []corev1.EnvVar{
{
Name: "ATOMIX_CONTROLLER",
Value: fmt.Sprintf("atomix-controller.%s.svc.cluster.local:5679", c.clusterID),
},
{
Name: "ATOMIX_APP",
Value: "test",
},
{
Name: "ATOMIX_NAMESPACE",
Value: c.clusterID,
},
},
Args: []string{
"-caPath=/etc/onos-config/certs/onf.cacrt",
"-keyPath=/etc/onos-config/certs/onos-config.key",
"-certPath=/etc/onos-config/certs/onos-config.crt",
"-configStore=/etc/onos-config/configs/configStore.json",
"-changeStore=/etc/onos-config/configs/changeStore.json",
"-deviceStore=/etc/onos-config/configs/deviceStore.json",
"-networkStore=/etc/onos-config/configs/networkStore.json",
"-modelPlugin=/usr/local/lib/testdevice-debug.so.1.0.0",
"-modelPlugin=/usr/local/lib/testdevice-debug.so.2.0.0",
"-modelPlugin=/usr/local/lib/devicesim-debug.so.1.0.0",
},
Ports: []corev1.ContainerPort{
{
Name: "grpc",
ContainerPort: 5150,
},
{
Name: "debug",
ContainerPort: 40000,
Protocol: corev1.ProtocolTCP,
},
},
ReadinessProbe: &corev1.Probe{
Handler: corev1.Handler{
TCPSocket: &corev1.TCPSocketAction{
Port: intstr.FromInt(5150),
},
},
InitialDelaySeconds: 5,
PeriodSeconds: 10,
},
LivenessProbe: &corev1.Probe{
Handler: corev1.Handler{
TCPSocket: &corev1.TCPSocketAction{
Port: intstr.FromInt(5150),
},
},
InitialDelaySeconds: 15,
PeriodSeconds: 20,
},
VolumeMounts: []corev1.VolumeMount{
{
Name: "config",
MountPath: "/etc/onos-config/configs",
ReadOnly: true,
},
{
Name: "secret",
MountPath: "/etc/onos-config/certs",
ReadOnly: true,
},
},
SecurityContext: &corev1.SecurityContext{
Capabilities: &corev1.Capabilities{
Add: []corev1.Capability{
"SYS_PTRACE",
},
},
},
},
},
SecurityContext: &corev1.PodSecurityContext{
RunAsUser: &zero,
},
Volumes: []corev1.Volume{
{
Name: "config",
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: "onos-config",
},
},
},
},
{
Name: "secret",
VolumeSource: corev1.VolumeSource{
Secret: &corev1.SecretVolumeSource{
SecretName: c.clusterID,
},
},
},
},
},
},
},
}
_, err := c.kubeclient.AppsV1().Deployments(c.clusterID).Create(dep)
return err
}
// createOnosConfigService creates a Service to expose the onos-config Deployment to other pods
func (c *ClusterController) createOnosConfigService() error {
service := &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "onos-config",
Namespace: c.clusterID,
},
Spec: corev1.ServiceSpec{
Selector: map[string]string{
"app": "onos",
"type": "config",
},
Ports: []corev1.ServicePort{
{
Name: "grpc",
Port: 5150,
},
},
},
}
_, err := c.kubeclient.CoreV1().Services(c.clusterID).Create(service)
return err
}
// awaitOnosConfigDeploymentReady waits for the onos-config pods to complete startup
func (c *ClusterController) awaitOnosConfigDeploymentReady() error {
labelSelector := metav1.LabelSelector{MatchLabels: map[string]string{"app": "onos", "type": "config"}}
unblocked := make(map[string]bool)
for {
// Get a list of the pods that match the deployment
pods, err := c.kubeclient.CoreV1().Pods(c.clusterID).List(metav1.ListOptions{
LabelSelector: labels.Set(labelSelector.MatchLabels).String(),
})
if err != nil {
return err
}
// Iterate through the pods in the deployment and unblock the debugger
for _, pod := range pods.Items {
if _, ok := unblocked[pod.Name]; !ok && len(pod.Status.ContainerStatuses) > 0 && pod.Status.ContainerStatuses[0].State.Running != nil {
err := c.execute(pod, []string{"/bin/bash", "-c", "dlv --init <(echo \"exit -c\") connect 127.0.0.1:40000"})
if err != nil {
return err
}
unblocked[pod.Name] = true
}
}
// Get the onos-config deployment
dep, err := c.kubeclient.AppsV1().Deployments(c.clusterID).Get("onos-config", metav1.GetOptions{})
if err != nil {
return err
}
// Return once the all replicas in the deployment are ready
if int(dep.Status.ReadyReplicas) == c.config.ConfigNodes {
return nil
}
time.Sleep(100 * time.Millisecond)
}
}
// GetOnosConfigNodes returns a list of all onos-config nodes running in the cluster
func (c *ClusterController) GetOnosConfigNodes() ([]NodeInfo, error) {
configLabelSelector := metav1.LabelSelector{MatchLabels: map[string]string{"app": "onos", "type": "config"}}
pods, err := c.kubeclient.CoreV1().Pods(c.clusterID).List(metav1.ListOptions{
LabelSelector: labels.Set(configLabelSelector.MatchLabels).String(),
})
if err != nil {
return nil, err
}
onosConfigNodes := make([]NodeInfo, len(pods.Items))
for i, pod := range pods.Items {
var status NodeStatus
if pod.Status.Phase == corev1.PodRunning {
status = NodeRunning
} else if pod.Status.Phase == corev1.PodFailed {
status = NodeFailed
}
onosConfigNodes[i] = NodeInfo{
ID: pod.Name,
Status: status,
Type: OnosConfig,
}
}
return onosConfigNodes, nil
}
|
[
0
] |
package components
import (
"github.com/gdamore/tcell/v2"
"github.com/liamg/flinch/core"
)
type checkbox struct {
core.Sizer
label string
checked bool
selected bool
}
func NewCheckbox(label string, checked bool) *checkbox {
cb := &checkbox{
label: label,
checked: checked,
}
cb.SetSizeStrategy(core.SizeStrategyMaximumWidth())
return cb
}
func (t *checkbox) Text() string {
return t.label
}
func (t *checkbox) SetChecked(checked bool) {
t.checked = checked
}
func (t *checkbox) Render(canvas core.Canvas) {
st := core.StyleDefault
faint := core.StyleFaint
if t.selected {
st = core.StyleSelected
faint = st
}
canvas.Fill(' ', st)
canvas.Set(0, 0, '[', faint)
canvas.Set(2, 0, ']', faint)
if t.checked {
canvas.Set(1, 0, '✔', st)
} else {
canvas.Set(1, 0, ' ', st)
}
for i := 0; i < len(t.label); i++ {
canvas.Set(4+i, 0, rune(t.label[i]), st)
}
}
func (t *checkbox) MinimumSize() core.Size {
rw, rh := len(t.label)+4, 1
return core.Size{W: rw, H: rh}
}
func (l *checkbox) Deselect() {
l.selected = false
}
func (l *checkbox) Select() bool {
if l.selected {
return false
}
l.selected = true
return true
}
func (l *checkbox) HandleKeypress(key *tcell.EventKey) {
switch key.Key() {
case tcell.KeyRune:
switch key.Rune() {
case ' ':
l.checked = !l.checked
}
}
}
|
[
7
] |
package controller
import (
"fmt"
"github.com/eaciit/colony-core/v0"
"github.com/eaciit/colony-manager/helper"
"github.com/eaciit/dbox"
_ "github.com/eaciit/dbox/dbc/jsons"
"github.com/eaciit/hdc/hdfs"
"github.com/eaciit/knot/knot.v1"
"github.com/eaciit/live"
"github.com/eaciit/sshclient"
"github.com/eaciit/toolkit"
"golang.org/x/crypto/ssh"
"path/filepath"
"time"
)
type ServerController struct {
App
}
func CreateServerController(s *knot.Server) *ServerController {
fmt.Sprintln("test")
var controller = new(ServerController)
controller.Server = s
return controller
}
func (s *ServerController) GetServers(r *knot.WebContext) interface{} {
r.Config.OutputType = knot.OutputJson
payload := struct {
Search string `json:"search"`
ServerOS string `json:"serverOS"`
ServerType string `json:"serverType"`
SSHType string `json:"sshType"`
}{}
err := r.GetPayload(&payload)
if err != nil {
return helper.CreateResult(false, nil, err.Error())
}
filters := []*dbox.Filter{}
if payload.Search != "" {
filters = append(filters, dbox.Or(
dbox.Contains("_id", payload.Search),
dbox.Contains("os", payload.Search),
dbox.Contains("host", payload.Search),
dbox.Contains("serverType", payload.Search),
dbox.Contains("sshtype", payload.Search),
))
}
if payload.ServerOS != "" {
filters = append(filters, dbox.Eq("os", payload.ServerOS))
}
if payload.ServerType != "" {
filters = append(filters, dbox.Eq("serverType", payload.ServerType))
}
if payload.SSHType != "" {
filters = append(filters, dbox.Eq("sshtype", payload.SSHType))
}
var query *dbox.Filter
if len(filters) > 0 {
query = dbox.And(filters...)
}
cursor, err := colonycore.Find(new(colonycore.Server), query)
if err != nil {
return helper.CreateResult(false, nil, err.Error())
}
data := []colonycore.Server{}
err = cursor.Fetch(&data, 0, false)
if err != nil {
return helper.CreateResult(false, nil, err.Error())
}
defer cursor.Close()
return helper.CreateResult(true, data, "")
}
func (s *ServerController) SaveServers(r *knot.WebContext) interface{} {
r.Config.OutputType = knot.OutputJson
r.Request.ParseMultipartForm(32 << 20)
r.Request.ParseForm()
path := filepath.Join(EC_DATA_PATH, "server", "log")
log, _ := toolkit.NewLog(false, true, path, "log-%s", "20060102-1504")
data := new(colonycore.Server)
if r.Request.FormValue("sshtype") == "File" {
log.AddLog("Get forms", "INFO")
dataRaw := map[string]interface{}{}
err := r.GetForms(&dataRaw)
if err != nil {
log.AddLog(err.Error(), "ERROR")
return helper.CreateResult(false, nil, err.Error())
}
log.AddLog("Serding data", "INFO")
err = toolkit.Serde(dataRaw, &data, "json")
if err != nil {
log.AddLog(err.Error(), "ERROR")
return helper.CreateResult(false, nil, err.Error())
}
} else {
log.AddLog("Get payload", "INFO")
err := r.GetPayload(&data)
if err != nil {
log.AddLog(err.Error(), "ERROR")
return helper.CreateResult(false, nil, err.Error())
}
}
if data.SSHType == "File" {
log.AddLog("Fetching public key", "INFO")
reqFileName := "privatekey"
file, _, err := r.Request.FormFile(reqFileName)
if err != nil {
log.AddLog(err.Error(), "ERROR")
return helper.CreateResult(false, nil, err.Error())
}
if file != nil {
log.AddLog("Saving public key", "INFO")
data.SSHFile = filepath.Join(EC_DATA_PATH, "server", "privatekeys", data.ID)
_, _, err = helper.FetchThenSaveFile(r.Request, reqFileName, data.SSHFile)
if err != nil {
log.AddLog(err.Error(), "ERROR")
return helper.CreateResult(false, nil, err.Error())
}
}
}
oldData := new(colonycore.Server)
log.AddLog(fmt.Sprintf("Find server ID: %s", data.ID), "INFO")
cursor, err := colonycore.Find(new(colonycore.Server), dbox.Eq("_id", data.ID))
if err != nil {
log.AddLog(err.Error(), "ERROR")
return helper.CreateResult(false, nil, err.Error())
}
oldDataAll := []colonycore.Server{}
err = cursor.Fetch(&oldDataAll, 0, false)
if err != nil {
log.AddLog(err.Error(), "ERROR")
return helper.CreateResult(false, nil, err.Error())
}
defer cursor.Close()
if len(oldDataAll) > 0 {
oldData = &oldDataAll[0]
}
log.AddLog(fmt.Sprintf("Delete data ID: %s", data.ID), "INFO")
err = colonycore.Delete(data)
if err != nil {
log.AddLog(err.Error(), "ERROR")
return helper.CreateResult(false, nil, err.Error())
}
log.AddLog(fmt.Sprintf("Saving data ID: %s", data.ID), "INFO")
err = colonycore.Save(data)
if err != nil {
log.AddLog(err.Error(), "ERROR")
return helper.CreateResult(false, nil, err.Error())
}
if data.ServerType == "hadoop" {
log.AddLog(fmt.Sprintf("SSH Connect %v", data), "INFO")
hadeepes, err := hdfs.NewWebHdfs(hdfs.NewHdfsConfig(data.Host, data.SSHPass))
if err != nil {
log.AddLog(err.Error(), "ERROR")
return helper.CreateResult(false, nil, err.Error())
}
_, err = hadeepes.List("/")
if err != nil {
return helper.CreateResult(false, nil, err.Error())
}
hadeepes.Config.TimeOut = 5 * time.Millisecond
hadeepes.Config.PoolSize = 100
return helper.CreateResult(true, nil, "")
}
log.AddLog(fmt.Sprintf("SSH Connect %v", data), "INFO")
sshSetting, client, err := s.SSHConnect(data)
if err != nil {
log.AddLog(err.Error(), "ERROR")
return helper.CreateResult(false, nil, err.Error())
}
defer client.Close()
if data.OS == "linux" {
setEnvPath := func() interface{} {
cmd1 := `sed -i '/export EC_APP_PATH/d' ~/.bashrc`
log.AddLog(cmd1, "INFO")
sshSetting.GetOutputCommandSsh(cmd1)
cmd2 := `sed -i '/export EC_DATA_PATH/d' ~/.bashrc`
log.AddLog(cmd2, "INFO")
sshSetting.GetOutputCommandSsh(cmd2)
cmd3 := "echo 'export EC_APP_PATH=" + data.AppPath + "' >> ~/.bashrc"
log.AddLog(cmd3, "INFO")
sshSetting.GetOutputCommandSsh(cmd3)
cmd4 := "echo 'export EC_DATA_PATH=" + data.DataPath + "' >> ~/.bashrc"
log.AddLog(cmd4, "INFO")
sshSetting.GetOutputCommandSsh(cmd4)
return nil
}
if oldData.AppPath == "" || oldData.DataPath == "" {
cmds := []string{
fmt.Sprintf(`mkdir -p "%s"`, filepath.Join(data.AppPath, "bin")),
fmt.Sprintf(`mkdir -p "%s"`, filepath.Join(data.AppPath, "cli")),
fmt.Sprintf(`mkdir -p "%s"`, filepath.Join(data.AppPath, "config")),
fmt.Sprintf(`mkdir -p "%s"`, filepath.Join(data.AppPath, "daemon")),
fmt.Sprintf(`mkdir -p "%s"`, filepath.Join(data.AppPath, "src")),
fmt.Sprintf(`mkdir -p "%s"`, filepath.Join(data.AppPath, "web", "share")),
fmt.Sprintf(`mkdir -p "%s"`, filepath.Join(data.DataPath, "datagrabber", "log")),
fmt.Sprintf(`mkdir -p "%s"`, filepath.Join(data.DataPath, "datagrabber", "output")),
fmt.Sprintf(`mkdir -p "%s"`, filepath.Join(data.DataPath, "datasource", "upload")),
fmt.Sprintf(`mkdir -p "%s"`, filepath.Join(data.DataPath, "server", "privatekeys")),
fmt.Sprintf(`mkdir -p "%s"`, filepath.Join(data.DataPath, "webgrabber", "history")),
fmt.Sprintf(`mkdir -p "%s"`, filepath.Join(data.DataPath, "webgrabber", "historyrec")),
fmt.Sprintf(`mkdir -p "%s"`, filepath.Join(data.DataPath, "webgrabber", "log")),
fmt.Sprintf(`mkdir -p "%s"`, filepath.Join(data.DataPath, "webgrabber", "output")),
}
for _, each := range cmds {
log.AddLog(each, "INFO")
}
_, err := sshSetting.RunCommandSsh(cmds...)
if err != nil {
log.AddLog(err.Error(), "ERROR")
return helper.CreateResult(false, nil, err.Error())
}
if res := setEnvPath(); res != nil {
return res
}
} else if oldData.AppPath != data.AppPath {
moveDir := fmt.Sprintf(`mv %s %s`, oldData.AppPath, data.AppPath)
log.AddLog(moveDir, "INFO")
_, err := sshSetting.GetOutputCommandSsh(moveDir)
if err != nil {
log.AddLog(err.Error(), "ERROR")
return helper.CreateResult(false, nil, err.Error())
}
if res := setEnvPath(); res != nil {
return res
}
} else if oldData.DataPath != data.DataPath {
moveDir := fmt.Sprintf(`mv %s %s`, oldData.DataPath, data.DataPath)
log.AddLog(moveDir, "INFO")
_, err := sshSetting.GetOutputCommandSsh(moveDir)
if err != nil {
log.AddLog(err.Error(), "ERROR")
return helper.CreateResult(false, nil, err.Error())
}
if res := setEnvPath(); res != nil {
return res
}
}
} else {
// windows
}
return helper.CreateResult(true, nil, "")
}
func (s *ServerController) SelectServers(r *knot.WebContext) interface{} {
r.Config.OutputType = knot.OutputJson
payload := new(colonycore.Server)
err := r.GetPayload(payload)
if err != nil {
return helper.CreateResult(false, nil, err.Error())
}
err = colonycore.Get(payload, payload.ID)
if err != nil {
return helper.CreateResult(false, nil, err.Error())
}
return helper.CreateResult(true, payload, "")
}
func (s *ServerController) DeleteServers(r *knot.WebContext) interface{} {
r.Config.OutputType = knot.OutputJson
payload := new(colonycore.Server)
var data []string
err := r.GetPayload(&data)
if err != nil {
return helper.CreateResult(false, nil, err.Error())
}
for _, val := range data {
if val != "" {
payload.ID = val
err = colonycore.Delete(payload)
if err != nil {
return helper.CreateResult(false, nil, err.Error())
}
// delPath := filepath.Join(unzipDest, payload.ID)
// err = deleteDirectory(unzipDest, delPath, payload.ID)
// if err != nil {
// fmt.Println("Error : ", err)
// return err
// }
}
}
return helper.CreateResult(true, data, "")
}
func (s *ServerController) SSHConnect(payload *colonycore.Server) (sshclient.SshSetting, *ssh.Client, error) {
client := sshclient.SshSetting{}
client.SSHHost = payload.Host
if payload.SSHType == "File" {
client.SSHAuthType = sshclient.SSHAuthType_Certificate
client.SSHKeyLocation = payload.SSHFile
} else {
client.SSHAuthType = sshclient.SSHAuthType_Password
client.SSHUser = payload.SSHUser
client.SSHPassword = payload.SSHPass
}
theClient, err := client.Connect()
return client, theClient, err
}
func (s *ServerController) TestConnection(r *knot.WebContext) interface{} {
r.Config.OutputType = knot.OutputJson
payload := new(colonycore.Server)
err := r.GetPayload(&payload)
if err != nil {
return helper.CreateResult(false, nil, err.Error())
}
if payload.ServerType == "hadoop" {
hadeepes, err := hdfs.NewWebHdfs(hdfs.NewHdfsConfig(payload.Host, payload.SSHPass))
if err != nil {
return helper.CreateResult(false, nil, err.Error())
}
_, err = hadeepes.List("/")
if err != nil {
return helper.CreateResult(false, nil, err.Error())
}
return helper.CreateResult(true, payload, "")
}
err = colonycore.Get(payload, payload.ID)
if err != nil {
return helper.CreateResult(false, nil, err.Error())
}
a, b, err := s.SSHConnect(payload)
if err != nil {
return helper.CreateResult(false, nil, err.Error())
}
defer b.Close()
c, err := a.Connect()
if err != nil {
return helper.CreateResult(false, nil, err.Error())
}
defer c.Close()
return helper.CreateResult(true, payload, "")
}
func (s *ServerController) CheckPing(r *knot.WebContext) interface{} {
r.Config.OutputType = knot.OutputJson
payload := struct {
IP string `json:"ip"`
}{}
err := r.GetPayload(&payload)
if err != nil {
return helper.CreateResult(false, nil, err.Error())
}
p := new(live.Ping)
p.Type = live.PingType_Network
p.Host = payload.IP
if err := p.Check(); err != nil {
return helper.CreateResult(false, nil, err.Error())
}
return helper.CreateResult(true, p.LastStatus, "")
}
|
[
5
] |
package store
import (
"context"
"math/rand"
"sync"
"math"
"github.com/aybabtme/epher/merkle"
"github.com/aybabtme/epher/thash"
)
func GrowthLog2(i int) int {
// log2(n):
// 10 -> 3
// 100 -> 6
// 1k -> 9
// 10k -> 13
// 100k -> 16
// 1M -> 20
f := float64(i)
lg2 := math.Log2(f)
return int(math.Floor(lg2))
}
func GrowthLog2Square(i int) int {
// log2(n)^2:
// 0..16 -> 0..16
// 20 -> 18
// 40 -> 28
// 60 -> 34
// 80 -> 39
// 100 -> 44
// 1k -> 99
// 10k -> 176
// 100k -> 275
// 1M -> 397
f := float64(i)
lg2sq := math.Pow(math.Log2(f), 2)
return int(math.Floor(lg2sq))
}
// RaceRandomOf will select a random concurrents from the given
// list, with a minimum of `minCount`, growing with `growth` of the size
// of the list of concurrents.
func RaceRandomOf(r *rand.Rand, growth func(int) int, min int) func([]merkle.Store) []merkle.Store {
return func(in []merkle.Store) []merkle.Store {
n := len(in)
picks := growth(n)
if picks < min {
picks = min
}
if picks > n {
return in
}
selected := make([]merkle.Store, 0, picks)
for i := 0; i < picks; i++ {
selected = append(selected,
in[rand.Intn(len(in))],
)
}
return selected
}
}
// Race makes multiple stores race together. The first answer to any
// query is returned, while the other ones are cancelled.
func Race(
selection func([]merkle.Store) []merkle.Store,
concurrent Pool,
) merkle.Store {
return &raced{selection: selection, concurrent: concurrent}
}
type raced struct {
selection func([]merkle.Store) []merkle.Store
concurrent Pool
}
func (race *raced) PutNode(ctx context.Context, node merkle.Node) error {
_, _, err := race.first(ctx, func(ctx context.Context, store merkle.Store) (interface{}, bool, error) {
err := store.PutNode(ctx, node)
return nil, err == nil, err
})
return err
}
func (race *raced) GetNode(ctx context.Context, sum thash.Sum) (merkle.Node, bool, error) {
type res struct {
node merkle.Node
found bool
}
iface, success, err := race.first(ctx, func(ctx context.Context, store merkle.Store) (interface{}, bool, error) {
node, found, err := store.GetNode(ctx, sum)
return &res{node: node, found: found}, found, err
})
if success {
out := iface.(*res)
return out.node, out.found, err
}
return merkle.Node{}, false, err
}
func (race *raced) InfoBlob(ctx context.Context, sum thash.Sum) (merkle.BlobInfo, bool, error) {
type res struct {
info merkle.BlobInfo
found bool
}
iface, success, err := race.first(ctx, func(ctx context.Context, store merkle.Store) (interface{}, bool, error) {
info, found, err := store.InfoBlob(ctx, sum)
return &res{info: info, found: found}, found, err
})
if success {
out := iface.(*res)
return out.info, out.found, err
}
return merkle.BlobInfo{}, false, err
}
func (race *raced) PutBlob(ctx context.Context, sum thash.Sum, blob []byte) error {
_, _, err := race.first(ctx, func(ctx context.Context, store merkle.Store) (interface{}, bool, error) {
err := store.PutBlob(ctx, sum, blob)
return nil, err == nil, err
})
return err
}
func (race *raced) GetBlob(ctx context.Context, sum thash.Sum) ([]byte, bool, error) {
type res struct {
data []byte
found bool
}
iface, success, err := race.first(ctx, func(ctx context.Context, store merkle.Store) (interface{}, bool, error) {
data, found, err := store.GetBlob(ctx, sum)
return &res{data: data, found: found}, found, err
})
if success {
out := iface.(*res)
return out.data, out.found, err
}
return nil, false, err
}
// first calls all the backend stores concurrently and returns the first
// successful answer it received.
func (race *raced) first(
ctx context.Context,
fn func(context.Context, merkle.Store) (answer interface{}, success bool, err error),
) (interface{}, bool, error) {
// pick the backing stores that will be concurring
concurrent := race.concurrent()
if race.selection != nil {
concurrent = race.selection(concurrent)
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
first := make(chan interface{}, 1)
errc := make(chan error, len(concurrent))
var wg sync.WaitGroup
for _, cc := range concurrent {
wg.Add(1)
go func(cc merkle.Store) {
defer wg.Done()
out, success, err := fn(ctx, cc)
if err != nil {
select {
case errc <- err:
default:
}
} else if success {
select {
case first <- out:
default:
}
}
}(cc)
}
go func() {
wg.Wait()
close(errc)
close(first)
}()
for out := range first {
return out, true, nil
}
err := <-errc
return nil, false, err
}
|
[
1
] |
package goutils
import (
"bytes"
"math/rand"
"strings"
"unicode"
)
func AddSlashesDoubleQuote(str string) string {
var buf bytes.Buffer
for _, char := range str {
switch char {
case '"':
buf.WriteRune('\\')
}
buf.WriteRune(char)
}
return buf.String()
}
func RemoveAllSpace(str string) string {
return strings.Map(func(r rune) rune {
if unicode.IsSpace(r) {
// if the character is a space, drop it
return -1
}
// else keep it in the string
return r
}, str)
}
const letterBytes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
func RandString(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
return string(b)
}
|
[
7
] |
package main
import (
"fmt"
)
func main() {
var average, ost, n, sum, kolvo int
n = 1
for n != 0 {
fmt.Printf("Введите число (для окончания ввода ввидите 0) \n")
fmt.Scanln(&n)
ost = n % 10
if ost == 8 && n > 0 {
sum = sum + n
kolvo++
}
}
average = sum / kolvo
fmt.Println("Среднее арифмитическое введенных чисел = ", average)
}
|
[
0
] |
package main
import "fmt"
func helloWorld(num int) {
if (num%3 == 0) && (num%5 == 0) {
fmt.Println("Hello World")
} else if num%3 == 0 {
fmt.Println("Hello")
} else if num%5 == 0 {
fmt.Println("World")
}
}
func main() {
helloWorld(15)
helloWorld(10)
helloWorld(9)
}
|
[
5
] |
// add by stefan
package RedisConn
import (
"strings"
"github.com/gomodule/redigo/redis"
)
func updateScript() (us *redis.Script) {
us = redis.NewScript(2, `
local key1 = KEYS[1] -- hash val
local key2 = KEYS[2] -- key or hash field
local ag1 = ARGV[1] -- field's value
local ag2 = ARGV[2] -- value
local ag3 = ARGV[3] -- "ex" flag
local ag4 = ARGV[4] -- exist time
redis.call('HSET', key1, key2, ag1)
if ag3 == "ex" then
redis.call('SETEX', key2, ag4, ag2)
else
redis.call('SET', key2, ag2)
end
`)
return
}
/*
key is 21 length string
min key: "111111111111111111111" string to int32 val:1029
max key: "fffffffffffffffffffff" string to int32 val:2142
sub number : 1675
key transfer interge %1000 with 1-1000
*/
func RoleKey2Haskey(key string) (hashk int) {
for _, ki := range key {
hashk += int(ki)
}
hashk = hashk % ERedHasKeyTransferMultiNum
if hashk == 0 {
hashk = 1
}
return
}
func MakeRedisModel(Identify, MainModel, SubModel string) string {
return MainModel + "." + SubModel + "." + Identify
}
func ParseRedisKey(redkey string) (Identify, MainModel, SubModel string) {
rediskeys := strings.Split(redkey, ".")
MainModel = rediskeys[0]
SubModel = rediskeys[1]
Identify = rediskeys[2]
return
}
|
[
0,
2
] |
package days
import (
"fmt"
"regexp"
"strconv"
"github.com/fivegreenapples/AOC2015/utils"
)
func (r *Runner) Day7Part1(in string) string {
wires := utils.MultilineCsvToStrings(in, " -> ")
circuit := circuit{
rawWires: map[string]string{},
resolvedWires: map[string]uint16{},
}
for _, w := range wires {
circuit.rawWires[w[1]] = w[0]
}
valA := circuit.resolve("a")
return strconv.FormatUint(uint64(valA), 10)
}
func (r *Runner) Day7Part2(in string) string {
wires := utils.MultilineCsvToStrings(in, " -> ")
circuit := circuit{
rawWires: map[string]string{},
resolvedWires: map[string]uint16{},
}
for _, w := range wires {
circuit.rawWires[w[1]] = w[0]
}
circuit.rawWires["b"] = "46065"
valA := circuit.resolve("a")
return strconv.FormatUint(uint64(valA), 10)
}
type circuit struct {
rawWires map[string]string
resolvedWires map[string]uint16
reg *regexp.Regexp
}
func (c *circuit) resolve(wire string) uint16 {
if val, resolved := c.resolvedWires[wire]; resolved {
return val
}
// check if wire is a number
wireVal, ok := strconv.Atoi(wire)
if ok == nil {
c.resolvedWires[wire] = uint16(wireVal)
return uint16(wireVal)
}
details := c.rawWires[wire]
if c.reg == nil {
c.reg = regexp.MustCompile(`^(([0-9a-z]+)|(([0-9a-z]+) (AND|OR) ([0-9a-z]+))|(([0-9a-z]+) (LSHIFT|RSHIFT) ([0-9a-z]+))|(NOT ([0-9a-z]+)))$`)
}
matches := c.reg.FindStringSubmatch(details)
if len(matches) == 0 {
panic(fmt.Errorf("unexpected no regex match for %s", details))
}
var val uint16
if len(matches[2]) > 0 {
val = c.resolve(matches[2])
} else if matches[5] == "AND" {
val = c.resolve(matches[4]) & c.resolve(matches[6])
} else if matches[5] == "OR" {
val = c.resolve(matches[4]) | c.resolve(matches[6])
} else if matches[9] == "LSHIFT" {
val = c.resolve(matches[8]) << utils.MustAtoi(matches[10])
} else if matches[9] == "RSHIFT" {
val = c.resolve(matches[8]) >> utils.MustAtoi(matches[10])
} else if len(matches[12]) > 0 {
val = ^c.resolve(matches[12])
}
c.resolvedWires[wire] = val
return val
}
|
[
5
] |
package main
import (
"bufio"
"flag"
"fmt"
"io/ioutil"
"os"
"strconv"
"gopkg.in/yaml.v2"
"nning.io/go/vigenere_jorin"
)
// Mode represents a mode object in the configuration
type Mode struct {
Name string `yaml:"name"`
Alphabet string `yaml:"alphabet"`
KeyPositionReset bool `yaml:"keyPositionReset"`
}
// Conf represents the top level object in the configuration
type Conf struct {
DefaultMode string `yaml:"defaultMode"`
Modes []Mode `yaml:"modes"`
}
var mode = flag.String("m", "default", "Select mode defined in config.yml")
func printHelp(config *Conf) {
fmt.Fprintf(os.Stderr, `
%s [options] <operation> <key> <message> [rounds]
operation "encrypt" or "decrypt"
key Key for operation
message Text for operation or "-" for reading from stdin
rounds Times to repeat operation, default 1
options Optional flags
-m Mode (from config.yml)
Key and message will be transformed to only upper case letters and space.
`, os.Args[0])
if config != nil {
fmt.Fprintf(os.Stderr, "Available modes: %v\n\n", getModeNames(config))
}
os.Exit(1)
}
func getConfig() *Conf {
var c Conf
content, err := ioutil.ReadFile("config.yml")
if err != nil {
return nil
}
err = yaml.Unmarshal(content, &c)
if err != nil {
fmt.Printf("%v\n", err)
}
return &c
}
func getDefaultMode(config *Conf) string {
if config.DefaultMode != "" {
return config.DefaultMode
}
return "default"
}
func getMode(config *Conf, name string) *Mode {
i := 0
for ; i < len(config.Modes); i++ {
if config.Modes[i].Name == name {
break
}
}
if i < len(config.Modes) {
return &config.Modes[i]
}
return nil
}
func getModeNames(config *Conf) []string {
a := make([]string, len(config.Modes))
for i := 0; i < len(config.Modes); i++ {
a[i] = config.Modes[i].Name
}
return a
}
func main() {
args := os.Args
argsLen := len(args)
config := getConfig()
if argsLen < 4 || argsLen > 7 {
printHelp(config)
}
flag.Parse()
args = flag.Args()
argsLen = len(args)
if argsLen < 3 || argsLen > 4 {
printHelp(config)
}
if config != nil {
defaultMode := getDefaultMode(config)
mode = &defaultMode
cMode := getMode(config, *mode)
if mode != nil {
vigenere_jorin.SetParameters(cMode.Alphabet, cMode.KeyPositionReset)
} else {
fmt.Fprintf(os.Stderr, "Warning: Mode definition for \"%s\" not found\n", *mode)
}
}
key := vigenere_jorin.Sanitize(args[1])
m := args[2]
if m == "-" {
m = ""
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
m = m + scanner.Text()
if m[len(m)-1] != '\n' {
m = m + "\n"
}
}
}
msg := vigenere_jorin.Sanitize(m)
rounds := 1
if argsLen == 4 {
rounds, _ = strconv.Atoi(args[3])
}
out := make([]rune, len(msg))
copy(out, msg)
switch args[0][0] {
case 'e':
out = vigenere_jorin.Encrypt(key, out, rounds)
case 'd':
out = vigenere_jorin.Decrypt(key, out, rounds)
}
fmt.Println(string(out))
}
|
[
0
] |
package main
import (
"fmt"
"strconv"
"strings"
"github.com/icemanblues/advent-of-code/pkg/util"
)
func parseLine(line string) (string, string) {
leftRight := strings.Split(line, " = ")
if leftRight[0] == "mask" {
return leftRight[0], leftRight[1]
}
// must be a memory instruction
mapIndex := leftRight[0]
index := mapIndex[4 : len(mapIndex)-1]
return index, leftRight[1]
}
func memSum(mem map[int]int) int {
sum := 0
for _, v := range mem {
sum += v
}
return sum
}
func runMask(lines []string) int {
var mask string
mem := make(map[int]int)
for _, line := range lines {
cmd, arg := parseLine(line)
if cmd == "mask" {
mask = arg
continue
}
// apply the mask
addr, _ := strconv.Atoi(cmd)
value, _ := strconv.Atoi(arg)
number := 0
for i, r := range mask {
bitIndex := 35 - i
bit := 1 << bitIndex
switch r {
case '1': // force it to 1
number += bit
case '0': // force it to 0, skip
case 'X': // copy the bit from the number
number += value & bit
default:
panic("mask is messed up")
}
}
// update memory
mem[addr] = number
}
return memSum(mem)
}
func applyMaskAddr(mask string, addr int) (int, []int) {
var floating []int
memAddr := 0
for i, r := range mask {
bitIndex := 35 - i
bit := 1 << bitIndex
switch r {
case '1': // force it to 1
memAddr += bit
case '0': // take the value that is there
memAddr += addr & bit
case 'X': // floating
floating = append(floating, bitIndex)
default:
panic("mask is messed up")
}
}
return memAddr, floating
}
func runMemAddrDecoder(lines []string) int {
var mask string
mem := make(map[int]int)
for _, line := range lines {
cmd, arg := parseLine(line)
if cmd == "mask" {
mask = arg
continue
}
// must be a memory instruction
index, _ := strconv.Atoi(cmd)
value, _ := strconv.Atoi(arg)
// apply the mask to memory address
memAddr, floating := applyMaskAddr(mask, index)
// update memory, apply floating bits (power set)
limit := 1 << len(floating)
for i := 0; i < limit; i++ {
addr := memAddr
for j, floater := range floating {
bitIndex := 1 << j
valueZero := i&bitIndex == 0
membit := 1 << floater
memZero := addr&membit == 0
// both are zero, nothing to do
// we want to set 1, but its current1
// we want to set 1, but its current 0
if !valueZero && memZero {
addr = addr + membit
}
// we want to set 0, but its current 1
if valueZero && !memZero {
addr = addr - membit
}
}
mem[addr] = value
}
}
return memSum(mem)
}
func part1() {
lines, _ := util.ReadInput("input.txt")
fmt.Printf("Part 1: %v\n", runMask(lines))
}
func part2() {
lines, _ := util.ReadInput("input.txt")
fmt.Printf("Part 2: %v\n", runMemAddrDecoder(lines))
}
func main() {
fmt.Println("Day 14: Docking Data")
part1()
part2()
}
|
[
0
] |
package main
import (
"encoding/json"
"flag"
"github.com/google/gopacket"
"github.com/google/gopacket/pcap"
"fmt"
"github.com/client9/reopen"
"io/ioutil"
"log"
"log/syslog"
"os"
"os/signal"
"strconv"
"syscall"
)
// The option82 program reads DHCPv4 packets via libpcap (network or file input)
// and ouputs JSON strings to a log file or to Stdout containing fields that
// should aid network troubelshooting, incident handling, or forensics.
func main() {
srcFile := flag.String("f", "", "PCAP input file")
srcInt := flag.String("i", "", "Capture interface")
outFile := flag.String("o", "",
"Log file (messages go to stdout if absent)")
enableSyslog := flag.Bool("s", false,
"Output option 82 data to syslog instead of log file or stdout")
pidFile := flag.String("p", "", "PID file (optional)")
flag.Parse()
var handle *pcap.Handle = nil
var sysLog *syslog.Writer = nil
if *srcFile != "" && *srcInt != "" {
log.Fatal("Cannot input from file and network at the same time")
} else if *srcFile != "" {
var err error = nil
handle, err = pcap.OpenOffline(*srcFile)
if err != nil {
log.Fatalf("Problem opening pcap file: %s", err)
}
} else if *srcInt != "" {
var err error = nil
handle, err = pcap.OpenLive(*srcInt, 1600, true, pcap.BlockForever)
if err != nil {
log.Fatalf("Problem opening pcap interface: %s", err)
}
} else {
log.Fatal("Aborting: you must specify -i XOR -f")
}
if *outFile != "" {
f, err := reopen.NewFileWriter(*outFile)
if err != nil {
log.Fatalf("Unable to set output log: %s", err)
}
log.SetOutput(f)
sighup := make(chan os.Signal, 1)
signal.Notify(sighup, syscall.SIGHUP)
go func() {
for {
<-sighup
log.Println("Got a sighup, reopening log file.")
f.Reopen()
}
}()
} else {
// Output to Stdout seems more useful if not logging to file.
log.SetOutput(os.Stdout)
}
if *enableSyslog {
var err error = nil
sysLog, err = syslog.Dial("", "", syslog.LOG_LOCAL0, "option82")
if err != nil {
log.Fatalf("Unable to connect to syslog: %s", err)
}
}
if *pidFile != "" {
err := writePidFile(*pidFile)
if err != nil {
log.Fatalf("Problem writing pid file: %s", err)
}
}
// TODO: Should be possible to override BPF rule with a flag
if err := handle.SetBPFFilter("udp src and dst port 67"); err != nil {
log.Fatalf("Unable to set BPF: %s", err)
} else {
packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
for packet := range packetSource.Packets() {
result, hasOption82 := HandlePacket(packet)
if hasOption82 {
enc, err := json.Marshal(*result)
if err != nil {
log.Fatalf("Could not marshal JSON: %s", err)
}
if *enableSyslog {
sysLog.Info(string(enc))
} else {
log.Println(string(enc))
}
}
}
}
}
// Write a pid file, but first make sure it doesn't exist with a running pid.
// https://gist.github.com/davidnewhall/3627895a9fc8fa0affbd747183abca39
func writePidFile(pidFile string) error {
// Read in the pid file as a slice of bytes.
piddata, err := ioutil.ReadFile(pidFile)
if err == nil {
// Convert the file contents to an integer.
pid, err := strconv.Atoi(string(piddata))
if err == nil {
// Look for the pid in the process list.
process, err := os.FindProcess(pid)
if err == nil {
// Send the process a signal zero kill.
err := process.Signal(syscall.Signal(0))
if err == nil {
// We only get an error if the pid isn't running,
// or it's not ours.
return fmt.Errorf("pid already running: %d", pid)
}
}
}
}
// If we get here, then the pidfile didn't exist,
// or the pid in it doesn't belong to the user running this app.
return ioutil.WriteFile(pidFile,
[]byte(fmt.Sprintf("%d", os.Getpid())), 0664)
}
|
[
5
] |
package leecode
import (
"sort"
)
/*
q15
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
*/
func ThreeSum(nums []int) [][]int {
if len(nums) == 0 {
return nil
}
sort.Ints(nums)
var res [][]int
length := len(nums)
if nums[0] <= 0 && nums[length-1] >= 0 {
for k, v := range nums {
// in the case, [a,a,a...],
// if a <= 0, only take care of the first left a
// if a > 0, only take care of the last right a
if k >= 1 && nums[k] <= 0 && nums[k] == nums[k-1] {
continue
}
if k+1 < length && nums[k] > 0 && nums[k] == nums[k+1] {
continue
}
i := k + 1
j := length - 1
for {
if i >= j || v*nums[j] > 0 {
break
}
sum := v + nums[i] + nums[j]
if sum == 0 {
res = append(res, []int{v, nums[i], nums[j]})
i = i + 1
j = j - 1
for {
if i < j && nums[j] == nums[j+1] {
j = j - 1
} else {
break
}
}
for {
if i < j && nums[i] == nums[i-1] {
i = i + 1
} else {
break
}
}
} else if sum > 0 {
j = j - 1
for {
if i < j && nums[j] == nums[j+1] {
j = j - 1
} else {
break
}
}
} else {
i = i + 1
for {
if i < j && nums[i] == nums[i-1] {
i = i + 1
} else {
break
}
}
}
}
}
}
return res
}
|
[
0,
5
] |
package user
import "fmt"
// Users is the entity used for controlling
// interactions with many users in the database
type Users struct{}
// NewUsers returns an Users controller
func NewUsers() *Users {
return &Users{}
}
// All returns all the users registered in the database
func (us *Users) All() ([]*User, error) {
users, err := getUsersWhere("")
if err != nil {
return users, fmt.Errorf("unable to get users: %v", err)
}
return users, nil
}
// Get returns a single user according to its ID
func (us *Users) Get(id int64) (*User, error) {
exp := fmt.Sprintf("user_id=%v", id)
return getUserWhere(exp)
}
// Search returns a single user according to important unique attr
func (us *Users) Search(f string) (*User, error) {
exp := fmt.Sprintf("username='%v' OR email='%v'", f, f)
return getUserWhere(exp)
}
// Where return many users according to a map of attrs
func (us *Users) Where(exp string) ([]*User, error) {
users, err := getUsersWhere(exp)
if err != nil {
return nil, fmt.Errorf("unable to get users: %v", err)
}
return users, nil
}
// Delete deletes an user based on its ID
func (us *Users) Delete(ID int64) error {
if err := deleteUser(ID); err != nil {
return fmt.Errorf("unable to delete user: %v", err)
}
return nil
}
|
[
2
] |
package main
import "fmt"
// https://leetcode.com/problems/path-with-maximum-gold/
// In a gold mine grid of size m * n, each cell in this mine has an integer
// representing the amount of gold in that cell, 0 if it is empty.
// Return the maximum amount of gold you can collect under the conditions:
// Every time you are located in a cell you will collect all the gold in that cell.
// From your position you can walk one step to the left, right, up or down.
// You can't visit the same cell more than once.
// Never visit a cell with 0 gold.
// You can start and stop collecting gold from any position in the grid that has some gold.
// Example 1:
// Input: grid = [[0,6,0],[5,8,7],[0,9,0]]
// Output: 24
// Explanation:
// [[0,6,0],
// [5,8,7],
// [0,9,0]]
// Path to get the maximum gold, 9 -> 8 -> 7.
// Example 2:
// Input: grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]
// Output: 28
// Explanation:
// [[1,0,7],
// [2,0,6],
// [3,4,5],
// [0,3,0],
// [9,0,20]]
// Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7.
// Constraints:
// 1 <= grid.length, grid[i].length <= 15
// 0 <= grid[i][j] <= 100
// There are at most 25 cells containing gold.
func getMaximumGold(grid [][]int) int {
visited := make([][]bool, len(grid))
for i := range visited {
visited[i] = make([]bool, len(grid[0]))
}
max, cur := new(int), new(int)
for i := 0; i < len(grid); i++ {
for j := 0; j < len(grid[0]); j++ {
// only start from edge cell
if grid[i][j] > 0 {
visit(grid, visited, i, j, max, cur)
}
}
}
return *max
}
func visit(grid [][]int, visited [][]bool, i, j int, max, cur *int) {
visited[i][j] = true
*cur += grid[i][j]
if *cur > *max {
*max = *cur
}
for _, neighbor := range neighbors(grid, i, j) {
if !visited[neighbor[0]][neighbor[1]] {
visit(grid, visited, neighbor[0], neighbor[1], max, cur)
}
}
*cur -= grid[i][j]
visited[i][j] = false
}
func neighbors(grid [][]int, i, j int) [][2]int {
dir := [][2]int{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}
neighbor := make([][2]int, 0, 4)
for d := range dir {
ni, nj := i+dir[d][0], j+dir[d][1]
if ni >= 0 && nj >= 0 && ni < len(grid) && nj < len(grid[0]) && grid[ni][nj] > 0 {
neighbor = append(neighbor, [2]int{ni, nj})
}
}
return neighbor
}
func main() {
fmt.Println(getMaximumGold([][]int{
{0, 6, 0},
{5, 8, 7},
{0, 9, 0},
}))
fmt.Println(getMaximumGold([][]int{
{1, 0, 7},
{2, 0, 6},
{3, 4, 5},
{0, 3, 0},
{9, 0, 20},
}))
fmt.Println(getMaximumGold([][]int{
{23, 21, 38, 12, 18, 36, 0, 7, 30, 29, 20, 3, 28},
{23, 3, 19, 2, 1, 11, 4, 8, 9, 24, 6, 5, 35},
}))
}
|
[
1
] |
package main
// Basic radius testing of the golang radius library.
// https://github.com/tomarus/radius originally https://github.com/go-av/radius
// Sends an Accept-Request packet followed by an Accounting-Stop record.
// Tommy van Leeuwen <[email protected]>
import (
"flag"
"fmt"
"github.com/tomarus/radius"
"log"
"math/rand"
"net"
"os"
)
var host = flag.String("host", "localhost", "Hostname of radius server.")
var port = flag.Int("port", 1812, "Portnr of radius server.")
var secret = flag.String("secret", "testing123", "Radius secret.")
var user = flag.String("user", "", "Username to test.")
var pass = flag.String("pass", "", "Password to test.")
var ip = flag.String("ip", "10.0.0.1", "Client IP to use.")
func main() {
flag.Parse()
if *host == "" || *user == "" || *pass == "" || *secret == "" {
flag.Usage()
os.Exit(0)
}
auth := RadiusConnect(*port)
RadiusAuth(auth)
acct := RadiusConnect(*port + 1)
RadiusAcct(acct)
}
func RadiusConnect(port int) *net.UDPConn {
udpAddr, err := net.ResolveUDPAddr("udp4", fmt.Sprintf("%s:%d", *host, port))
if err != nil {
log.Fatal(err)
}
rc, err := net.DialUDP("udp", nil, udpAddr)
if err != nil {
log.Fatal(err)
}
return rc
}
func RadiusAuth(rc *net.UDPConn) {
p := new(radius.Packet)
p.Code = radius.AccessRequest
p.Id = byte(rand.Int() & 0xff)
p.Secret = *secret
p.Pairs = append(p.Pairs, radius.Pair{Type: radius.FramedIP, Str: *ip})
p.Pairs = append(p.Pairs, radius.Pair{Type: radius.UserName, Str: *user})
p.Pairs = append(p.Pairs, radius.Pair{Type: radius.UserPass, Str: *pass})
response, err := radius.SendPacket(rc, p)
if err != nil {
log.Fatal(err)
}
if response.Code == radius.AccessAccept {
log.Printf("Received Access-Accept")
for _, p := range response.Pairs {
if p.Type == 78 {
log.Printf("Received Access-Accept Configuration-Token %s", p.Bytes)
}
if p.Type == radius.ReplyMessage {
log.Printf("Received Access-Accept Reply-Message %s", p.Str)
}
}
} else if response.Code == radius.AccessReject {
log.Printf("Received Access-Reject")
} else {
log.Printf("Received unknown Access-Request packet %d", response.Code)
}
}
func RadiusAcct(rc *net.UDPConn) {
p := new(radius.Packet)
p.Code = radius.AcctRequest
p.Id = byte(rand.Int() & 0xff)
p.Secret = *secret
p.Pairs = append(p.Pairs, radius.Pair{Type: radius.FramedIP, Str: *ip})
p.Pairs = append(p.Pairs, radius.Pair{Type: radius.UserName, Str: *user})
p.Pairs = append(p.Pairs, radius.Pair{Type: radius.AcctStatusType, Uint32: radius.AcctStop})
p.Pairs = append(p.Pairs, radius.Pair{Type: radius.AcctSessionTime, Uint32: 30})
p.Pairs = append(p.Pairs, radius.Pair{Type: radius.AcctInputOctets, Uint32: 1234567})
p.Pairs = append(p.Pairs, radius.Pair{Type: radius.AcctInputGigawords, Uint32: 2})
p.Pairs = append(p.Pairs, radius.Pair{Type: radius.AcctInputPackets, Uint32: 12345})
p.Pairs = append(p.Pairs, radius.Pair{Type: radius.AcctOutputOctets, Uint32: 7654321})
p.Pairs = append(p.Pairs, radius.Pair{Type: radius.AcctOutputGigawords, Uint32: 1})
p.Pairs = append(p.Pairs, radius.Pair{Type: radius.AcctOutputPackets, Uint32: 54321})
response, err := radius.SendPacket(rc, p)
if err != nil {
log.Fatal(err)
}
if response.Code == radius.AcctResponse {
log.Printf("Received Acct-Response")
} else {
log.Printf("Received unknown Acct-Response packet %d", response.Code)
}
}
|
[
5
] |
package util
import (
"crypto/md5"
"math/rand"
"time"
)
func Md5(str string) string {
h := md5.New()
h.Write([]byte(str))
return string(h.Sum(nil))
}
func RandString(len int) string {
bytes := make([]byte, len)
r := rand.New(rand.NewSource(time.Now().Unix()))
for i := 0; i < len; i++ {
b := r.Intn(26) + 65
bytes[i] = byte(b)
}
return string(bytes)
}
|
[
1
] |
package handler
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"tes-project/driver"
models "tes-project/models"
repository "tes-project/repository"
loan "tes-project/repository/loan"
)
// NewLoanHandler ...
func NewLoanHandler(db *driver.DB) *Loan {
return &Loan{
repo: loan.NewSQLLoanRepo(db.SQL),
}
}
// Loan ...
type Loan struct {
repo repository.LoanRepo
}
// Create a new installment
func (p *Loan) Create(w http.ResponseWriter, r *http.Request) {
post := models.Loan{}
json.NewDecoder(r.Body).Decode(&post)
// Loan DATA
Amount := post.Amount
Tenor := post.Tenor
RequestDate, _ := time.Parse("2006-01-02", post.Date)
// GET Interest
TempInterest, _ := p.repo.GetInterest(r.Context(), Tenor)
Interest := TempInterest[0].Interest
TempAmountInstallment := Amount / Tenor
TempAmountInterest := float64(Amount) * Interest / 100
totalInstallment := float64(TempAmountInstallment) + TempAmountInterest
// Loan CODE
DateTimeNow := time.Now()
TempDate := DateTimeNow.Format("01-02-2006")
TempTime := DateTimeNow.Format("15:04:05")
LoanCode := "LOAN" + strings.Replace(string(TempDate), "-", "", -1) + strings.Replace(string(TempTime), ":", "", -1)
for i := 1; i <= Tenor; i++ {
// fmt.Println("============================================================")
// fmt.Println("== Temp Amount Installment : ", TempAmountInstallment)
// fmt.Println("== Temp Amount Interest : ", TempAmountInterest)
// fmt.Println("== Total Installment : ", totalInstallment)
// fmt.Println("== Request Date : ", RequestDate.AddDate(0, i, 0).Format("2006-01-02"))
// fmt.Println("============================================================")
newID, err := p.repo.InsertInstallment(r.Context(), LoanCode, float64(TempAmountInstallment), TempAmountInterest, totalInstallment, i, RequestDate.AddDate(0, i, 0).Format("2006-01-02"))
if err != nil {
respondWithErrorLoan(w, http.StatusInternalServerError, "Server Error")
}
fmt.Println("Success insert installment : ID => ", newID)
}
payload, _ := p.repo.GetInstallmentByLoanCode(r.Context(), LoanCode)
respondwithJSONLoan(w, http.StatusCreated, payload)
}
// TrackLoan to Track average of loan application
func (p *Loan) TrackLoan(w http.ResponseWriter, r *http.Request) {
loan := models.LoanTrack{}
json.NewDecoder(r.Body).Decode(&loan)
RequestDate, _ := time.Parse("2006-01-02", loan.Date)
payload, _ := p.repo.GetLoanTrack(r.Context(), RequestDate.AddDate(0, 0, -7).Format("2006-01-02"), RequestDate.Format("2006-01-02"))
var totalLoan float64
for index := 0; index < len(payload); index++ {
totalLoan = totalLoan + payload[0].JumlahPinjaman
}
average := totalLoan / 7
countLoan := len(payload)
respondwithJSONLoan(w, http.StatusCreated, map[string]string{"Count": strconv.Itoa(countLoan), "Summary": fmt.Sprintf("%.0f", totalLoan), "7-day avg": fmt.Sprintf("%.0f", average)})
}
// respondwithJSON write json response format
func respondwithJSONLoan(w http.ResponseWriter, code int, payload interface{}) {
response, _ := json.Marshal(payload)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(response)
}
// respondwithError return error message
func respondWithErrorLoan(w http.ResponseWriter, code int, msg string) {
respondwithJSONLoan(w, code, map[string]string{"message": msg})
}
|
[
0
] |
package main
import "sort"
// minNum 给定一个自然数n和自然数数组nums(每个元素取值[0,9]),求由nums中元素组成的、小于n的最大数。
// 示例:n=23121,nums={2,4,9},返回=22999
func minNum(nums []int, n int) int {
if n <= 0 || len(nums) == 0 {
return -1
}
sort.Slice(nums, func(i, j int) bool {
return nums[i] < nums[j]
})
// parts 从小到大
var parts []int
for v := n; v > 0; v = v / 10 {
d := v % 10
parts = append(parts, d)
}
if len(parts) == 1 && parts[0] <= nums[0] {
return -1
}
var result []int
var flag bool
// 寻找替换的 idx 和值
for idx := len(parts) - 1; idx >= 0; idx-- {
if flag {
// 这里替换为 minMax,后续都用 max(nums) 填充即刻
result = append(result, nums[len(nums)-1])
continue
}
v := parts[idx]
minMax := -1
for _, a := range nums {
if a > v {
break
}
minMax = a
}
result = append(result, minMax)
flag = minMax < v && minMax != -1
}
if !flag {
// 3456 [7,8,9] --> 999
// 123 [1,2,3] --> 33
// 321 [1,2,3] --> 313
// 一直都用的当前值,需要退位
var done bool
for idx := len(result) - 1; idx >= 0; idx-- {
v := result[idx]
minMax := -1
for _, a := range nums {
// 寻找下一个更小的值
if a >= v {
break
}
minMax = a
}
if minMax == -1 {
continue
}
// 找到了,将这位替换,然后其他都替换为最大值
result[idx] = minMax
for j := len(result) - 1; j > idx; j-- {
result[j] = nums[len(nums)-1]
}
done = true
break
}
if !done {
// 减少一位,其他都用最大值
result = result[1:]
for i := range result {
result[i] = nums[len(nums)-1]
}
}
}
var res int
for _, v := range result {
if v == -1 {
v = nums[len(nums)-1]
}
res = res*10 + v
}
return res
}
|
[
0
] |
package structRepo
type Car struct {
Gas_pedal int
Brake_pedal int
Steering_well int
}
func CallStruct() (Car_a Car) {
Car_a = Car{}
return
}
|
[
2
] |
/*
* Copyright (c) 2020 Baidu, 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 brn
import (
"errors"
"fmt"
"regexp"
"strings"
"github.com/baidu/easyfaas/pkg/api"
)
var (
RegAlias = regexp.MustCompile("^[a-zA-Z0-9-_]+$")
regBrn = regexp.MustCompile(`^(brn:(cloud[a-zA-Z-]*):faas:)([a-z]{2,5}[0-9]*:)([0-9a-z]{32}:)(function:)([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?$`)
regPartialBrn = regexp.MustCompile(`^([0-9a-z]{32}:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?$`)
RegNotMatchErr = errors.New(`member must satisfy regular expression pattern: (brn:(cloud[a-zA-Z-]*)?:faas:)?([a-z]{2,5}[0-9]*:)?([0-9a-z]{32}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?`)
)
type FunctionBRN struct {
BRN
FunctionName string
Version string
Alias string
}
var invalidFunctionBrnError = errors.New("invalid function brn")
func GenerateFunctionBRN(region, uid, functionName, qualifier string) FunctionBRN {
var resource string
var alias string
var version string
if len(qualifier) > 0 {
resource = fmt.Sprintf("function:%s:%s", functionName, qualifier)
version, alias = GetVersionAndAlias(qualifier)
} else {
resource = fmt.Sprintf("function:%s", functionName)
}
b := FunctionBRN{
BRN: BRN{
Partition: "cloud",
Service: "faas",
Region: region,
AccountID: Md5BceUid(uid),
Resource: resource,
},
FunctionName: functionName,
Version: version,
Alias: alias,
}
return b
}
func ParseFunction(brn string) (FunctionBRN, error) {
commonBrn, err := Parse(brn)
if err != nil {
return FunctionBRN{}, err
}
parts := strings.SplitN(commonBrn.Resource, ":", 3)
if len(parts) < 2 {
return FunctionBRN{}, invalidFunctionBrnError
}
if parts[0] != "function" {
return FunctionBRN{}, invalidFunctionBrnError
}
functionName := parts[1]
var qualifier string
var alias string
var version string
if len(parts) == 3 {
qualifier = parts[2]
version, alias = GetVersionAndAlias(qualifier)
}
b := FunctionBRN{
BRN: commonBrn,
FunctionName: functionName,
Version: version,
Alias: alias,
}
return b, nil
}
// fName = ThumbnailName/Uid-ThumbnailName/FuncBrn
func DealFName(accountID, fName string) (thumbnailName, version, alias string, err error) {
t, err := JudgeUnderlyingBrn(fName)
if err != nil {
return
}
switch t {
case "FunctionBRN":
brn, errp := ParseFunction(fName)
if errp != nil {
err = errp
return
}
thumbnailName = brn.FunctionName
version = brn.Version
alias = brn.Alias
return
case "PartialBRN":
splitArr := strings.Split(fName, ":")
lenSplitArr := len(splitArr)
switch lenSplitArr {
case 1:
// function-name
thumbnailName = splitArr[0]
case 2:
// account-id:function or function:version
if accountID != "" && strings.HasPrefix(fName, accountID) {
thumbnailName = splitArr[1]
} else {
thumbnailName = splitArr[0]
version, alias = GetVersionAndAlias(splitArr[1])
}
case 3:
// account-id:function:version
if accountID != "" && accountID != splitArr[0] {
err = RegNotMatchErr
} else {
accountID = splitArr[0]
thumbnailName = splitArr[1]
version, alias = GetVersionAndAlias(splitArr[2])
}
default:
err = RegNotMatchErr
}
return
}
err = RegNotMatchErr
return
}
func JudgeUnderlyingBrn(underlyingBrn string) (string, error) {
if regBrn.MatchString(underlyingBrn) {
return "FunctionBRN", nil
} else if regPartialBrn.MatchString(underlyingBrn) {
return "PartialBRN", nil
} else {
return "", RegNotMatchErr
}
}
func JudgeQualifier(qualifier string) (string, error) {
if api.RegVersion.MatchString(qualifier) {
return "version", nil
} else if RegAlias.MatchString(qualifier) {
return "alias", nil
} else {
return "", errors.New("Qualifier not match Regexp")
}
}
func GetVersionAndAlias(qualifier string) (version, alias string) {
qtype, err := JudgeQualifier(qualifier)
if err != nil {
return
} else if qtype == "version" {
version = qualifier
return
} else if qtype == "alias" {
alias = qualifier
return
}
return
}
func GenerateFuncBrnString(region, uid, functionName, qualifier string) string {
return GenerateFunctionBRN(region, uid, functionName, qualifier).String()
}
|
[
5
] |
package main
import (
"bufio"
"fmt"
"log"
"os"
"strings"
"text/scanner"
)
const (
LBRACK = "["
RBRACK = "]"
COMMENT1 = ";"
COMMENT2 = "#"
ASSIGN = "="
EOL = "\n"
)
type Ini map[string]KeyVals
type KeyVals map[string]string
func readSection(s *scanner.Scanner) string {
tok := s.Scan()
var val string
for tok != scanner.EOF {
c := s.TokenText()
if c == RBRACK {
return val
} else {
val = val + c
}
tok = s.Scan()
}
fmt.Println("Error near: [", val)
os.Exit(1)
return ""
}
func readValue(s *scanner.Scanner) string {
tok := s.Scan()
c := s.TokenText()
var v string
if c != ASSIGN {
os.Exit(1)
}
tok = s.Scan()
for tok != scanner.EOF {
c := s.TokenText()
switch c {
case COMMENT1, COMMENT2:
tok = scanner.EOF
default:
v = v + c
tok = s.Scan()
}
}
return v
}
func parse(file *os.File) {
var s scanner.Scanner
var c string
ini := Ini{}
var section string
linesScanner := bufio.NewScanner(file)
for linesScanner.Scan() {
line := linesScanner.Text()
s.Init(strings.NewReader(line))
s.Scan()
c = s.TokenText()
switch c {
case LBRACK:
section = readSection(&s)
ini[section] = KeyVals{}
case COMMENT1, COMMENT2:
default:
k := c
v := readValue(&s)
ini[section][k] = v
}
}
fmt.Println(ini)
}
func main() {
file, err := os.Open("lol.ini") // For read access.
if err != nil {
log.Fatal(err)
}
parse(file)
}
|
[
0
] |
// Copyright 2018 The go-daq Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ipbus
import (
"fmt"
)
func newmask(name string, value uint32) msk {
shift := uint(0)
for i := uint(0); i < 32; i++ {
test := uint32(1) << i
if test&value > 0 {
shift = i
break
}
}
return msk{name, value, shift}
}
type msk struct {
name string
value uint32
shift uint
}
type Register struct {
Name string
Addr uint32 // Global IPbus address
Masks []string // List of names bitmasks
noninc bool
size int
msks map[string]msk
}
func (r Register) String() string {
s := fmt.Sprintf("%s at 0x%x", r.Name, r.Addr)
if r.noninc {
s += " (non-inc)"
}
if len(r.Masks) > 0 {
s += " ["
}
i := 0
for n, m := range r.msks {
if i > 0 {
s += ", "
}
s += fmt.Sprintf("%s:0x%x", n, m.value)
i += 1
}
if i > 0 {
s += "]"
}
return s
}
// Read the value of masked part of register
func (r Register) ReadMask(mask string, val uint32) (uint32, error) {
m, ok := r.msks[mask]
if !ok {
err := fmt.Errorf("Register %s has no mask %s.", r.Name, mask)
return uint32(0), err
}
maskedval := val & m.value
maskedval = maskedval >> m.shift
return maskedval, nil
}
func (r Register) WriteMask(mask string, val uint32) (uint32, uint32, error) {
m, ok := r.msks[mask]
if !ok {
err := fmt.Errorf("Register %s has no mask %s.", r.Name, mask)
return uint32(0), uint32(0), err
}
andterm := uint32(0xffffffff) &^ m.value
orterm := (val << m.shift) & m.value
return andterm, orterm, nil
}
|
[
0
] |
/*
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 controllers
import (
"context"
"fmt"
"github.com/go-logr/logr"
"github.com/pkg/errors"
"github.com/riita10069/rolling-update-status/controllers/pkg"
appsv1 "k8s.io/api/apps/v1"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)
// DeploymentReconciler reconciles a Deployment object
type DeploymentReconciler struct {
client.Client
Log logr.Logger
Scheme *runtime.Scheme
StoreRepo pkg.StoreRepository
}
// +kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=apps,resources=deployments/status,verbs=get;update;patch
func (r *DeploymentReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {
ctx := context.Background()
// _ = r.Log.WithValues("deployment", req.NamespacedName)
var dply appsv1.Deployment
err := r.Get(ctx, req.NamespacedName, &dply)
if err != nil {
return ctrl.Result{}, errors.WithStack(err)
}
r.StoreRepo = pkg.NewStore(dply)
if ok, err := pkg.ValidateNewReplicaSet(dply, r.Client); err != nil {
if err == pkg.NewReplicaSetNotFound {
return ctrl.Result{Requeue: true}, nil
} else {
if !ok {
return ctrl.Result{}, nil
}
}
}
stmt, status, err := pkg.RolloutStatus(dply)
fmt.Println("rollout status", stmt, status)
if stmt == pkg.RevisionNotFound {
return ctrl.Result{Requeue: true}, nil
}
if err != nil {
return reconcile.Result{}, err
}
if stmt == pkg.TimedOutReason {
if err := r.StoreRepo.Create("ok", "error: timed out waiting for any update progress to be made"); err != nil {
return ctrl.Result{}, err
}
return reconcile.Result{}, nil
}
if !status {
return ctrl.Result{}, nil
} else {
if err = r.StoreRepo.Create("success", "the cluster ok the Rolling Update."); err != nil {
return reconcile.Result{}, err
}
return reconcile.Result{}, nil
}
}
func (r *DeploymentReconciler) SetupWithManager(mgr ctrl.Manager) error {
pred := predicate.Funcs{
CreateFunc: func(event.CreateEvent) bool { return false },
DeleteFunc: func(event.DeleteEvent) bool { return false },
UpdateFunc: func(event.UpdateEvent) bool { return true },
GenericFunc: func(event.GenericEvent) bool { return false },
}
return ctrl.NewControllerManagedBy(mgr).
For(&appsv1.Deployment{}).
WithEventFilter(pred).
Complete(r)
}
|
[
4
] |
package sequence
// CharacterType ...
type CharacterType byte
const (
// Numeric ...
Numeric = CharacterType(0)
// ASCIIAlpha ...
ASCIIAlpha = CharacterType('@')
// ASCIINumeric ...
ASCIINumeric = CharacterType('#')
// ASCIIAlphanumeric ...
ASCIIAlphanumeric = CharacterType('!')
)
// Bytes implements the iterator interface.
type Bytes struct {
overflowed bool
dims int
start Start
current Current
end End
format Format
incOrder IncrementOrder
skip SkipFnc
}
// Start ...
type Start Field
// Current ...
type Current Field
// End ...
type End Field
// Exceptions ...
type Exceptions map[byte]struct{}
// Format ...
type Format []CharFmt
// NewFormat ...
func NewFormat(cfs ...CharFmt) Format {
f := make(Format, 0, len(cfs))
for _, cf := range cfs {
f = append(f, cf)
}
return f
}
// CharFmt ...
type CharFmt struct {
charType CharacterType
min, max byte
}
// NewCharFmt ...
func NewCharFmt(min, max byte, incOrder int) CharFmt {
if max < min {
panic("invalid range")
}
cf := CharFmt{
min: min,
max: max,
}
switch {
case 0 <= min && min <= max && max <= 9:
cf.charType = Numeric
case '0' <= min && min <= max && max <= '9':
cf.charType = ASCIINumeric
case 'A' <= min && min <= max && max <= 'Z':
cf.charType = ASCIIAlpha
case '0' <= min && min <= '9' && 'A' <= max && max <= 'Z':
cf.charType = ASCIIAlphanumeric
default:
panic("invalid character type detected")
}
return cf
}
// IncrementOrder ... The ith value is the next index to increment.
type IncrementOrder []int
// MaxChars ...
type MaxChars Field
// MinChars ...
type MinChars Field
// SkipFnc ...
type SkipFnc func(c Current) bool
// NewBytes ...
func NewBytes(opts ...interface{}) Bytes {
bts := Bytes{
skip: func(c Current) bool { return false },
}
for _, opt := range opts {
switch t := opt.(type) {
case Start:
bts.start = t.Copy()
case Current:
bts.current = t.Copy()
case End:
bts.end = t.Copy()
case Format:
bts.dims = len(t)
bts.format = t.Copy()
case IncrementOrder:
bts.incOrder = t.Copy()
case SkipFnc:
bts.skip = t
default:
panic("invalid option type")
}
}
if bts.format == nil {
panic("format is required")
}
if bts.start == nil {
bts.start = bts.format.Start()
// TODO: Increment for any exception characters
}
if bts.current == nil {
bts.current = Current(bts.start.Copy())
}
// TODO: compare start to current to end
if bts.end == nil {
bts.end = bts.format.End()
// TODO: Decrement for any exception characters
}
bts.validate()
return bts
}
func incChar(char byte, cf CharFmt) (byte, byte) {
switch char {
case cf.max:
return cf.min, 1
default:
switch cf.charType {
case ASCIIAlphanumeric:
if char == '9' {
return 'A', 0
}
return char + 1, 0
default:
return char + 1, 0
}
}
}
func (bts *Bytes) increment() {
var carry byte
for _, index := range bts.incOrder {
var (
cf = bts.format[index]
)
bts.current[index], carry = incChar(bts.current[index], cf)
if carry != 0 {
}
}
}
// TODO
func (bts *Bytes) validate() {}
// Compare ...
func (bts Bytes) Compare(b Bytes) int {
if bts.dims != b.dims {
panic("invalid dimension")
}
for _, index := range bts.incOrder {
if bts.format[index].charType != b.format[index].charType {
panic("invalid character format")
}
x, y := bts.current[index], b.current[index]
switch {
case x < y:
return -1
case y < x:
return 1
}
}
return 0
}
// Copy ...
func (s Start) Copy() Start {
cpy := make(Start, len(s), cap(s))
copy(cpy, s)
return cpy
}
// Copy ...
func (c Current) Copy() Current {
cpy := make(Current, len(c), cap(c))
copy(cpy, c)
return cpy
}
// Copy ...
func (e End) Copy() End {
cpy := make(End, len(e), cap(e))
copy(cpy, e)
return cpy
}
// Copy ...
func (e Exceptions) Copy() Exceptions {
cpy := make(Exceptions)
for k, v := range e {
cpy[k] = v
}
return cpy
}
// Copy ...
func (f Format) Copy() Format {
cpy := make(Format, 0, cap(f))
for _, cf := range f {
cpy = append(cpy, cf.Copy())
}
return cpy
}
// End ...
func (f Format) End() End {
e := make(End, 0, len(f))
for _, cf := range f {
e = append(e, cf.max)
}
return e
}
// Start ...
func (f Format) Start() Start {
s := make(Start, 0, len(f))
for _, cf := range f {
s = append(s, cf.min)
}
return s
}
// Copy ...
func (io IncrementOrder) Copy() IncrementOrder {
cpy := make(IncrementOrder, len(io), cap(io))
copy(cpy, io)
return cpy
}
// Copy ...
func (mc MaxChars) Copy() MaxChars {
cpy := make(MaxChars, len(mc), cap(mc))
copy(cpy, mc)
return cpy
}
// Copy ...
func (mc MinChars) Copy() MinChars {
cpy := make(MinChars, len(mc), cap(mc))
copy(cpy, mc)
return cpy
}
// Copy ...
func (cf CharFmt) Copy() CharFmt {
return CharFmt{
charType: cf.charType,
min: cf.min,
max: cf.max,
}
}
|
[
1
] |
package leetcode
func isPerfectSquareLoop(num int) bool {
for i := 0; ; i++ {
squaredValue := i * i
if squaredValue == num {
return true
} else if squaredValue > num {
break
}
}
return false
}
func isPerfectSquareBinarySearch(num int) bool {
start, end := 0, num
for start <= end {
guess := (start + end) / 2
squaredValue := guess * guess
if squaredValue == num {
return true
} else if squaredValue > num {
end = guess - 1
} else if squaredValue < num {
start = guess + 1
}
}
return false
}
func isPerfectSquare(num int) bool {
return isPerfectSquareBinarySearch(num)
}
|
[
5
] |
package tokens
import (
"math/rand"
"strconv"
"sync"
"time"
)
var (
rnd *rand.Rand
validKeys []string
// We use mutex to prevent race conditions, as this will be accessed from
// multiple goroutines.
mut sync.Mutex
)
func init() {
rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
}
// randIntRange generate a random number within a given range.
func randIntRange(min, max int) int {
return rnd.Intn(max-min) + min
}
// GenerateInviteKey generates a new invite key.
func GenerateInviteKey() (code string) {
mut.Lock()
defer mut.Unlock()
code = strconv.Itoa(randIntRange(1000, 9999))
validKeys = append(validKeys, code)
return code
}
// CheckAndConsumeKey checks a given key whether it is valid or not, and
// consumes it if valid. Returns whether the key given was valid.
func CheckAndConsumeKey(key string) bool {
mut.Lock()
defer mut.Unlock()
for i, k := range validKeys {
if k == key {
validKeys = append(validKeys[:i], validKeys[i+1:]...)
return true
}
}
return false
}
|
[
1
] |
package iterator_test
import (
"log"
"testing"
"github.com/kvanticoss/goutils/v2/internal/iterator"
"github.com/stretchr/testify/assert"
)
type SortableStruct struct {
Val int
}
// Less answers if "other" is Less (should be sorted before) this struct
func (s *SortableStruct) Less(other interface{}) bool {
otherss, ok := other.(*SortableStruct)
if !ok {
log.Printf("Type assertion failed in SortableStruct; got other of type %#v", other)
return true
}
res := s.Val < otherss.Val
return res
}
func getRecordIterator(multiplier, max int) iterator.RecordIterator {
i := 0
return func() (interface{}, error) {
i = i + 1
if i <= max {
return &SortableStruct{
Val: i * multiplier,
}, nil
}
return nil, iterator.ErrIteratorStop
}
}
func TestSortedRecordIterators(t *testing.T) {
e, err := iterator.SortedRecordIterators([]iterator.RecordIterator{
getRecordIterator(1, 3),
getRecordIterator(2, 12),
getRecordIterator(4, 7),
getRecordIterator(1, 10),
})
if err != nil {
assert.NoError(t, err)
return
}
count := 0
lastVal := 0
var r interface{}
for r, err = e(); err == nil; r, err = e() {
record, ok := r.(*SortableStruct)
if !ok {
t.Error("Failure in type assertion to SortableStruct")
}
if record.Val < lastVal {
t.Errorf("Expected each record value to be higher than the last; got %v", record.Val)
}
count++
lastVal = record.Val
}
if err != iterator.ErrIteratorStop {
t.Errorf("Expected only error to be IteratorStop; Got %v", err)
}
expectedCount := (3 + 12 + 7 + 10)
if count != expectedCount {
t.Errorf("Sorted Iterator skipped some records; all should be processed. Only processed %d / %d records", count, expectedCount)
}
if lastVal == 0 {
t.Error("Record emitter didn't yield any records")
}
}
func BenchmarkSortedRecordIterators(b *testing.B) {
b.Run("1000 rows x 2 streams", func(b *testing.B) {
amount := 1000
for n := 0; n < b.N; n++ {
for n := 0; n < b.N; n++ {
b.StopTimer()
e, err := iterator.SortedRecordIterators([]iterator.RecordIterator{
getRecordIterator(1, amount),
getRecordIterator(2, amount)})
if err != nil {
b.Fatal(err)
return
}
b.StartTimer()
for _, err := e(); err == nil; _, err = e() {
}
}
}
})
b.Run("10000 rows x 2 streams", func(b *testing.B) {
amount := 10000
for n := 0; n < b.N; n++ {
b.StopTimer()
e, err := iterator.SortedRecordIterators([]iterator.RecordIterator{
getRecordIterator(1, amount),
getRecordIterator(2, amount)})
if err != nil {
b.Fatal(err)
return
}
b.StartTimer()
for _, err := e(); err == nil; _, err = e() {
}
}
})
b.Run("10000 rows x 10 streams", func(b *testing.B) {
amount := 10000
for n := 0; n < b.N; n++ {
b.StopTimer()
e, err := iterator.SortedRecordIterators([]iterator.RecordIterator{
getRecordIterator(1, amount),
getRecordIterator(2, amount),
getRecordIterator(2, amount),
getRecordIterator(1, amount),
getRecordIterator(2, amount),
getRecordIterator(2, amount),
getRecordIterator(1, amount),
getRecordIterator(2, amount),
getRecordIterator(10, amount),
getRecordIterator(6, amount)})
if err != nil {
b.Fatal(err)
return
}
b.StartTimer()
for _, err := e(); err == nil; _, err = e() {
}
}
})
b.Run("1M rows x 2 streams", func(b *testing.B) {
amount := 1000000
for n := 0; n < b.N; n++ {
for n := 0; n < b.N; n++ {
b.StopTimer()
e, err := iterator.SortedRecordIterators([]iterator.RecordIterator{
getRecordIterator(1, amount),
getRecordIterator(2, amount)})
if err != nil {
b.Fatal(err)
return
}
b.StartTimer()
for _, err := e(); err == nil; _, err = e() {
}
}
}
})
b.Run("1M rows x 10 streams", func(b *testing.B) {
amount := 1000000
for n := 0; n < b.N; n++ {
b.StopTimer()
e, err := iterator.SortedRecordIterators([]iterator.RecordIterator{
getRecordIterator(1, amount),
getRecordIterator(2, amount),
getRecordIterator(2, amount),
getRecordIterator(1, amount),
getRecordIterator(2, amount),
getRecordIterator(2, amount),
getRecordIterator(1, amount),
getRecordIterator(2, amount),
getRecordIterator(10, amount),
getRecordIterator(6, amount)})
if err != nil {
b.Fatal(err)
return
}
b.StartTimer()
for _, err := e(); err == nil; _, err = e() {
}
}
})
}
func BenchmarkLargeBench(b *testing.B) {
amount := 1000000
for n := 0; n < b.N; n++ {
b.StopTimer()
e, err := iterator.SortedRecordIterators([]iterator.RecordIterator{
getRecordIterator(1, amount),
getRecordIterator(2, amount),
getRecordIterator(2, amount),
getRecordIterator(2, amount),
getRecordIterator(3, amount),
getRecordIterator(5, amount),
getRecordIterator(2, amount),
getRecordIterator(7, amount),
getRecordIterator(2, amount),
getRecordIterator(10, amount)})
if err != nil {
b.Fatal(err)
return
}
b.StartTimer()
for _, err := e(); err == nil; _, err = e() {
}
}
}
|
[
0,
1
] |
package main
import (
"fmt"
"strings"
"github.com/golang/glog"
"github.com/piex/gowechat"
)
func main() {
tuling := Tuling{
URL: "http://openapi.tuling123.com/openapi/api/v2",
Keys: map[string]Rebot{
"Mervyn": Rebot{
Name: "asmr",
Key: "dc54d5efed42466f9f0f57def6e7dead",
},
},
}
wx := gowechat.Start()
for msg := range wx.MsgChan {
for _, m := range msg.AddMsgList {
m.Content = strings.Replace(m.Content, "<", "<", -1)
m.Content = strings.Replace(m.Content, ">", ">", -1)
switch m.MsgType {
case 1:
if m.FromUserName[:2] == "@@" { // 群消息
content := strings.Split(m.Content, ":<br/>")[1]
fmt.Println(content)
if (wx.User.NickName != "" && strings.Contains(content, "@"+wx.User.NickName)) || (wx.User.RemarkName != "" && strings.Contains(content, "@"+wx.User.RemarkName)) {
content = strings.Replace(content, "@"+wx.User.NickName, "", -1)
content = strings.Replace(content, "@"+wx.User.RemarkName, "", -1)
fmt.Printf("[群消息] %s", content)
reply, _ := tuling.getReply(content, m.FromUserName)
wx.SendMessage(reply, m.FromUserName)
}
} else {
// 普通消息
fmt.Printf("[好友消息] %s", m.Content)
reply, _ := tuling.getReply(m.Content, m.FromUserName)
wx.SendMessage(reply, m.FromUserName)
}
}
}
glog.Flush()
}
}
|
[
7
] |
package main
import "fmt"
func main() {
a, b, c := 1, 0, 0
var s string
fmt.Scanln(&s)
for _, ch := range s {
if ch == 'A' {
a, b = b, a
} else if ch == 'B' {
b, c = c, b
} else {
a, c = c, a
}
}
if a != 0 {
fmt.Println(1)
} else if b != 0 {
fmt.Println(2)
} else {
fmt.Println(3)
}
}
|
[
5
] |
package question_861_870
// 862. 和至少为 K 的最短子数组
// https://leetcode-cn.com/problems/shortest-subarray-with-sum-at-least-k
// Topics: 队列 二分查找
func shortestSubarray(A []int, K int) int {
return 0
}
|
[
2
] |
package Bubble_Sort
func BubbleSort(items []int) {
var (
n = len(items)
sorted = false
)
for !sorted {
swapped := false
for i := 0; i < n-1; i++ {
if items[i] > items[i+1] {
items[i+1], items[i] = items[i], items[i+1]
swapped = true
}
}
if !swapped {
sorted = true
}
n = n - 1
}
}
func bubbleSort(arr[]int){
for i:=0;i<len(arr)-1;i++{
for j:=0;j<len(arr)-i-1;j++{
if arr[j] > arr[j+1]{
arr[j], arr[j+1]= arr[j+1],arr[j]
}
}
}
}
|
[
0
] |
package main
import "fmt"
type node struct {
value int
left *node
right *node
count int
}
type binarySearchTree struct {
root *node
}
type queue []node
func (q *queue) enqueue(n node) {
*q = append(*q, n)
}
func (q *queue) dequeue() (node, error) {
if len(*q) == 0 {
return node{}, fmt.Errorf("empty queue")
}
a, b := (*q)[1:], (*q)[0]
*q = a
return b, nil
}
func (b *binarySearchTree) insert(v int) {
newNode := &node{value: v}
if b.root == nil {
b.root = newNode
return
}
currentNode := b.root
for {
if v == currentNode.value {
currentNode.count++
return
} else if v < currentNode.value {
if currentNode.left == nil {
currentNode.left = newNode
newNode.count++
return
}
currentNode = currentNode.left
} else {
if currentNode.right == nil {
currentNode.right = newNode
newNode.count++
return
}
currentNode = currentNode.right
}
}
}
func (b *binarySearchTree) contains(v int) bool {
if b.root == nil {
return false
}
currentNode := b.root
for currentNode != nil {
if v == currentNode.value {
return true
} else if v < currentNode.value {
currentNode = currentNode.left
} else {
currentNode = currentNode.right
}
}
return false
}
func (b *binarySearchTree) bfs() error {
var q, visited queue
var output []int
q = make([]node, 0)
visited = make([]node, 0)
if b.root == nil {
return fmt.Errorf("empty tree")
}
q = append(q, *b.root)
for len(q) != 0 {
v, err := q.dequeue()
if err != nil {
return err
}
visited = append(visited, v)
if v.left != nil {
q.enqueue(*v.left)
}
if v.right != nil {
q.enqueue(*v.right)
}
}
for _, v := range visited {
output = append(output, v.value)
}
fmt.Println(output)
return nil
}
func traverse(visited *queue, n *node, s string) {
if s == "preorder" {
visited.enqueue(*n)
}
if n.left != nil {
traverse(visited, n.left, s)
}
if s == "inorder" {
visited.enqueue(*n)
}
if n.right != nil {
traverse(visited, n.right, s)
}
if s == "postorder" {
visited.enqueue(*n)
}
}
func (b *binarySearchTree) dfs(s string) error {
var q, visited queue
var output []int
if b.root == nil {
return fmt.Errorf("empty tree")
}
q = append(q, *b.root)
v, err := q.dequeue()
if err != nil {
return err
}
traverse(&visited, &v, s)
for _, v := range visited {
output = append(output, v.value)
}
fmt.Println(output)
return nil
}
func main() {
var b binarySearchTree
b.insert(10)
b.insert(6)
b.insert(15)
b.insert(3)
b.insert(8)
b.insert(20)
fmt.Println(b)
fmt.Println(b.contains(1))
fmt.Println(b.contains(5))
fmt.Println(b.contains(11))
fmt.Println(b.contains(18))
b.bfs()
b.dfs("preorder")
b.dfs("postorder")
b.dfs("inorder")
}
|
[
5
] |
package gubrak
import (
"math"
"reflect"
"time"
)
func typeIs(data interface{}, types ...reflect.Kind) bool {
valueOfData := reflect.ValueOf(data)
for _, tipe := range types {
if tipe == valueOfData.Kind() {
return true
}
}
return false
}
// IsSlice is alias of IsSlice()
func IsSlice(data interface{}) bool {
return typeIs(data, reflect.Slice)
}
// IsArray is alias of IsArray()
func IsArray(data interface{}) bool {
return typeIs(data, reflect.Array)
}
// IsSliceOrArray will return true when type of the data is array/slice
func IsSliceOrArray(data interface{}) bool {
return IsSlice(data) || IsArray(data)
}
var IsArrayOrSlice = IsSliceOrArray
// IsBool will return true when type of the data is boolean
func IsBool(data interface{}) bool {
return typeIs(data,
reflect.Bool,
)
}
// IsChannel will return true when type of the data is channel
func IsChannel(data interface{}) bool {
return typeIs(data, reflect.Chan)
}
// IsDate will return true when type of the data is time.Time
func IsDate(data interface{}) bool {
if _, ok := data.(time.Time); ok {
return true
}
return false
}
// IsString will return true when type of the data is string
func IsString(data interface{}) bool {
return typeIs(data, reflect.String)
}
// IsEmptyString will return true when type of the data is string and it's empty
func IsEmptyString(data interface{}) bool {
if data == nil {
return true
}
if value, ok := data.(string); ok {
return value == ""
}
return false
}
// IsFloat will return true when type of the data is floating number
func IsFloat(data interface{}) bool {
return typeIs(data,
reflect.Float32,
reflect.Float64,
)
}
// IsFunction will return true when type of the data is closure/function
func IsFunction(data interface{}) bool {
return typeIs(data, reflect.Func)
}
// IsInt will return true when type of the data is numeric integer
func IsInt(data interface{}) bool {
return typeIs(data,
reflect.Int,
reflect.Int8,
reflect.Int16,
reflect.Int32,
reflect.Int64,
)
}
// IsMap will return true when type of the data is hash map
func IsMap(data interface{}) bool {
return typeIs(data, reflect.Map)
}
// IsNil will return true when type of the data is nil
func IsNil(data interface{}) bool {
if data == nil {
return true
}
valueOfData := reflect.ValueOf(data)
switch valueOfData.Kind() {
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer, reflect.Struct:
if valueOfData.IsNil() {
return true
}
}
return false
}
// IsNumeric will return true when type of the data is numeric (float, uint, int)
func IsNumeric(data interface{}) bool {
return typeIs(data,
reflect.Int,
reflect.Int8,
reflect.Int16,
reflect.Int32,
reflect.Int64,
reflect.Float32,
reflect.Float64,
reflect.Uint,
reflect.Uint8,
reflect.Uint16,
reflect.Uint32,
reflect.Uint64,
reflect.Uintptr,
)
}
// IsPointer will return true when type of the data is pointer
func IsPointer(data interface{}) bool {
return typeIs(data, reflect.Ptr)
}
// IsStructObject will return true when type of the data is object from struct
func IsStructObject(data interface{}) bool {
return typeIs(data, reflect.Struct)
}
// IsTrue will return true when type of the data is bool, and the value is true
func IsTrue(data interface{}) bool {
if data == nil {
return false
}
if value, ok := data.(bool); ok {
return value == true
}
return false
}
// IsUint will return true when type of the data is uint
func IsUint(data interface{}) bool {
return typeIs(data,
reflect.Uint,
reflect.Uint8,
reflect.Uint16,
reflect.Uint32,
reflect.Uint64,
reflect.Uintptr,
)
}
// IsZeroNumber will return true when type of the data is numeric and it's has 0 value
func IsZeroNumber(data interface{}) bool {
if data == nil {
return true
}
if value, ok := data.(float32); ok {
return value == 0
}
if value, ok := data.(float64); ok {
return value == 0
}
if value, ok := data.(int); ok {
return value == 0
}
if value, ok := data.(int8); ok {
return value == 0
}
if value, ok := data.(int16); ok {
return value == 0
}
if value, ok := data.(int32); ok {
return value == 0
}
if value, ok := data.(int64); ok {
return value == 0
}
if value, ok := data.(uint); ok {
return value == 0
}
if value, ok := data.(uint8); ok {
return value == 0
}
if value, ok := data.(uint16); ok {
return value == 0
}
if value, ok := data.(uint32); ok {
return value == 0
}
if value, ok := data.(uint64); ok {
return value == 0
}
if value, ok := data.(uintptr); ok {
return value == 0
}
if value, ok := data.(complex64); ok {
value128 := complex128(value)
return math.Float64bits(real(value128)) == 0 && math.Float64bits(imag(value128)) == 0
}
if value, ok := data.(complex128); ok {
return math.Float64bits(real(value)) == 0 && math.Float64bits(imag(value)) == 0
}
return false
}
// IsZeroValue reports whether value is the zero value for its type.
func IsZeroValue(data interface{}) bool {
if data == nil {
return true
} else if value, ok := data.(string); ok {
return value == ""
} else if value, ok := data.(bool); ok {
return value == false
} else if value, ok := data.(float32); ok {
return value == 0
} else if value, ok := data.(float64); ok {
return value == 0
} else if value, ok := data.(int); ok {
return value == 0
} else if value, ok := data.(int8); ok {
return value == 0
} else if value, ok := data.(int16); ok {
return value == 0
} else if value, ok := data.(int32); ok {
return value == 0
} else if value, ok := data.(int64); ok {
return value == 0
} else if value, ok := data.(uint); ok {
return value == 0
} else if value, ok := data.(uint8); ok {
return value == 0
} else if value, ok := data.(uint16); ok {
return value == 0
} else if value, ok := data.(uint32); ok {
return value == 0
} else if value, ok := data.(uint64); ok {
return value == 0
} else if value, ok := data.(uintptr); ok {
return value == 0
} else if value, ok := data.(complex64); ok {
value128 := complex128(value)
return math.Float64bits(real(value128)) == 0 && math.Float64bits(imag(value128)) == 0
} else if value, ok := data.(complex128); ok {
return math.Float64bits(real(value)) == 0 && math.Float64bits(imag(value)) == 0
} else {
if IsStructObject(data) {
if IsNil(data) {
return true
}
valueOfData := reflect.ValueOf(data)
for i := 0; i < valueOfData.NumField(); i++ {
if !IsZeroValue(valueOfData.Field(i).Interface()) {
return false
}
}
} else {
if IsNil(data) {
return true
}
}
}
return true
}
var IsEmpty = IsZeroValue
|
[
4
] |
// 动态子树和查询
// n,q=2e5
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
// https://judge.yosupo.jp/problem/dynamic_tree_vertex_add_subtree_sum
// 0 u v w x 删除 u-v 边, 添加 w-x 边
// 1 p x 将 p 节点的值加上 x
// 2 u p 对于边(u,p) 查询结点v的子树的和,p为u的父节点
in := bufio.NewReader(os.Stdin)
out := bufio.NewWriter(os.Stdout)
defer out.Flush()
var n, q int
fmt.Fscan(in, &n, &q)
nums := make([]int, n)
for i := 0; i < n; i++ {
fmt.Fscan(in, &nums[i])
}
lct := NewLinkCutTreeSubTree(true)
vs := lct.Build(nums)
for i := 0; i < n-1; i++ { // 连接树边
var v1, v2 int
fmt.Fscan(in, &v1, &v2)
lct.LinkEdge(vs[v1], vs[v2])
}
for i := 0; i < q; i++ {
var op int
fmt.Fscan(in, &op)
if op == 0 {
var u, v, w, x int
fmt.Fscan(in, &u, &v, &w, &x)
lct.CutEdge(vs[u], vs[v])
lct.LinkEdge(vs[w], vs[x])
} else if op == 1 {
var root, delta int
fmt.Fscan(in, &root, &delta)
lct.Set(vs[root], lct.Get(vs[root])+delta)
} else {
var root, parent int
fmt.Fscan(in, &root, &parent)
lct.Evert(vs[parent]) // !注意查询子树前要先把父节点旋转到根节点
fmt.Fprintln(out, lct.QuerySubTree(vs[root]))
}
}
}
type E = int // 子树和
func (*TreeNode) e() E { return 0 }
func (*TreeNode) op(this, other E) E { return this + other }
func (*TreeNode) inv(this, other E) E { return this - other }
type LinkCutTreeSubTree struct {
nodeId int
edges map[struct{ u, v int }]struct{}
check bool
}
// check: AddEdge/RemoveEdge で辺の存在チェックを行うかどうか.
func NewLinkCutTreeSubTree(check bool) *LinkCutTreeSubTree {
return &LinkCutTreeSubTree{edges: make(map[struct{ u, v int }]struct{}), check: check}
}
// 各要素の値を vs[i] としたノードを生成し, その配列を返す.
func (lct *LinkCutTreeSubTree) Build(vs []E) []*TreeNode {
nodes := make([]*TreeNode, len(vs))
for i, v := range vs {
nodes[i] = lct.Alloc(v)
}
return nodes
}
// 要素の値を v としたノードを生成する.
func (lct *LinkCutTreeSubTree) Alloc(key E) *TreeNode {
res := newTreeNode(key, lct.nodeId)
lct.nodeId++
lct.update(res)
return res
}
// t を根に変更する.
func (lct *LinkCutTreeSubTree) Evert(t *TreeNode) {
lct.expose(t)
lct.toggle(t)
lct.push(t)
}
func (lct *LinkCutTreeSubTree) LinkEdge(child, parent *TreeNode) (ok bool) {
if lct.check {
if lct.IsConnected(child, parent) {
return
}
id1, id2 := child.id, parent.id
if id1 > id2 {
id1, id2 = id2, id1
}
tuple := struct{ u, v int }{id1, id2}
lct.edges[tuple] = struct{}{}
}
lct.Evert(child)
lct.expose(parent)
child.p = parent
parent.r = child
lct.update(parent)
return true
}
func (lct *LinkCutTreeSubTree) CutEdge(u, v *TreeNode) (ok bool) {
if lct.check {
id1, id2 := u.id, v.id
if id1 > id2 {
id1, id2 = id2, id1
}
tuple := struct{ u, v int }{id1, id2}
if _, has := lct.edges[tuple]; !has {
return
}
delete(lct.edges, tuple)
}
lct.Evert(u)
lct.expose(v)
parent := v.l
v.l = nil
lct.update(v)
parent.p = nil
return true
}
// u と v の lca を返す.
// u と v が異なる連結成分なら nullptr を返す.
// !上記の操作は根を勝手に変えるため, 事前に Evert する必要があるかも.
func (lct *LinkCutTreeSubTree) QueryLCA(u, v *TreeNode) *TreeNode {
if !lct.IsConnected(u, v) {
return nil
}
lct.expose(u)
return lct.expose(v)
}
func (lct *LinkCutTreeSubTree) QueryKthAncestor(x *TreeNode, k int) *TreeNode {
lct.expose(x)
for x != nil {
lct.push(x)
if x.r != nil && x.r.cnt > k {
x = x.r
} else {
if x.r != nil {
k -= x.r.cnt
}
if k == 0 {
return x
}
k--
x = x.l
}
}
return nil
}
// t を根とする部分木の要素の値の和を返す.
// !Evert を忘れない!
func (lct *LinkCutTreeSubTree) QuerySubTree(t *TreeNode) E {
lct.expose(t)
return t.op(t.key, t.sub)
}
// t の値を v に変更する.
func (lct *LinkCutTreeSubTree) Set(t *TreeNode, key E) *TreeNode {
lct.expose(t)
t.key = key
lct.update(t)
return t
}
// t の値を返す.
func (lct *LinkCutTreeSubTree) Get(t *TreeNode) E {
return t.key
}
// u と v が同じ連結成分に属する場合は true, そうでなければ false を返す.
func (lct *LinkCutTreeSubTree) IsConnected(u, v *TreeNode) bool {
return u == v || lct.GetRoot(u) == lct.GetRoot(v)
}
func (lct *LinkCutTreeSubTree) expose(t *TreeNode) *TreeNode {
rp := (*TreeNode)(nil)
for cur := t; cur != nil; cur = cur.p {
lct.splay(cur)
if cur.r != nil {
cur.Add(cur.r)
}
cur.r = rp
if cur.r != nil {
cur.Erase(cur.r)
}
lct.update(cur)
rp = cur
}
lct.splay(t)
return rp
}
func (lct *LinkCutTreeSubTree) update(t *TreeNode) {
t.cnt = 1
if t.l != nil {
t.cnt += t.l.cnt
}
if t.r != nil {
t.cnt += t.r.cnt
}
t.Merge(t.l, t.r)
}
func (lct *LinkCutTreeSubTree) rotr(t *TreeNode) {
x := t.p
y := x.p
x.l = t.r
if t.r != nil {
t.r.p = x
}
t.r = x
x.p = t
lct.update(x)
lct.update(t)
t.p = y
if y != nil {
if y.l == x {
y.l = t
}
if y.r == x {
y.r = t
}
lct.update(y)
}
}
func (lct *LinkCutTreeSubTree) rotl(t *TreeNode) {
x := t.p
y := x.p
x.r = t.l
if t.l != nil {
t.l.p = x
}
t.l = x
x.p = t
lct.update(x)
lct.update(t)
t.p = y
if y != nil {
if y.l == x {
y.l = t
}
if y.r == x {
y.r = t
}
lct.update(y)
}
}
func (lct *LinkCutTreeSubTree) toggle(t *TreeNode) {
t.l, t.r = t.r, t.l
t.rev = !t.rev
}
func (lct *LinkCutTreeSubTree) push(t *TreeNode) {
if t.rev {
if t.l != nil {
lct.toggle(t.l)
}
if t.r != nil {
lct.toggle(t.r)
}
t.rev = false
}
}
func (lct *LinkCutTreeSubTree) splay(t *TreeNode) {
lct.push(t)
for !t.IsRoot() {
q := t.p
if q.IsRoot() {
lct.push(q)
lct.push(t)
if q.l == t {
lct.rotr(t)
} else {
lct.rotl(t)
}
} else {
r := q.p
lct.push(r)
lct.push(q)
lct.push(t)
if r.l == q {
if q.l == t {
lct.rotr(q)
lct.rotr(t)
} else {
lct.rotl(t)
lct.rotr(t)
}
} else {
if q.r == t {
lct.rotl(q)
lct.rotl(t)
} else {
lct.rotr(t)
lct.rotl(t)
}
}
}
}
}
func (lct *LinkCutTreeSubTree) GetRoot(t *TreeNode) *TreeNode {
lct.expose(t)
for t.l != nil {
lct.push(t)
t = t.l
}
return t
}
type TreeNode struct {
key, sum, sub E
rev bool
cnt int
id int
l, r, p *TreeNode
}
func newTreeNode(key E, id int) *TreeNode {
res := &TreeNode{key: key, sum: key, cnt: 1, id: id}
res.sub = res.e()
return res
}
func (n *TreeNode) IsRoot() bool {
return n.p == nil || (n.p.l != n && n.p.r != n)
}
func (n *TreeNode) Add(other *TreeNode) { n.sub = n.op(n.sub, other.sum) }
func (n *TreeNode) Erase(other *TreeNode) { n.sub = n.inv(n.sub, other.sum) }
func (n *TreeNode) Merge(n1, n2 *TreeNode) {
var tmp1, tmp2 E
if n1 != nil {
tmp1 = n1.sum
} else {
tmp1 = n.e()
}
if n2 != nil {
tmp2 = n2.sum
} else {
tmp2 = n.e()
}
n.sum = n.op(n.op(tmp1, n.key), n.op(n.sub, tmp2))
}
|
[
5
] |
package algotest
func BubbleSort(data []int) {
for i := 0; i < len(data); i++ {
for j := 1; j < len(data)-i; j++ {
if data[j] < data[j-1] {
data[j], data[j-1] = data[j-1], data[j]
}
}
}
}
func SelectionSort(data []int) {
length := len(data)
for i := 0; i < length; i++ {
maxIndex := 0
for j := 1; j < length-i; j++ {
if data[j] > data[maxIndex] {
maxIndex = j
}
}
data[length-i-1], data[maxIndex] = data[maxIndex], data[length-i-1]
}
}
func HeapSort(data []int) []int {
heapify(data)
for i := len(data) - 1; i > 0; i-- {
data[0], data[i] = data[i], data[0]
siftDown(data, 0, i)
}
return data
}
func heapify(data []int) {
for i := (len(data) - 1) / 2; i >= 0; i-- {
siftDown(data, i, len(data))
}
}
func siftDown(heap []int, lo, hi int) {
root := lo
for {
child := root*2 + 1
if child >= hi {
break
}
if child+1 < hi && heap[child] < heap[child+1] {
child++
}
if heap[root] < heap[child] {
heap[root], heap[child] = heap[child], heap[root]
root = child
} else {
break
}
}
}
func InsertionSort(data []int) {
for i := 1; i < len(data); i++ {
if data[i] < data[i-1] {
j := i - 1
temp := data[i]
for j >= 0 && data[j] > temp {
data[j+1] = data[j]
j--
}
data[j+1] = temp
}
}
}
func ShellSort(data []int) {
n := len(data)
h := 1
for h < n/3 {
h = 3*h + 1
}
for h >= 1 {
for i := h; i < n; i++ {
for j := i; j >= h && data[j] < data[j-h]; j -= h {
data[j], data[j-h] = data[j-h], data[j]
}
}
h /= 3
}
}
func MergeSort(data []int) []int {
if len(data) <= 1 {
return data
}
middle := len(data) / 2
left := MergeSort(data[:middle])
right := MergeSort(data[middle:])
return merge(left, right)
}
func merge(left, right []int) []int {
result := make([]int, len(left)+len(right))
for i := 0; len(left) > 0 || len(right) > 0; i++ {
if len(left) > 0 && len(right) > 0 {
if left[0] < right[0] {
result[i] = left[0]
left = left[1:]
} else {
result[i] = right[0]
right = right[1:]
}
} else if len(left) > 0 {
result[i] = left[0]
left = left[1:]
} else if len(right) > 0 {
result[i] = right[0]
right = right[1:]
}
}
return result
}
|
[
5
] |
package p38
import "unicode/utf8"
func convertString2Numbers(s string) (numbers []int) {
bs := []byte(s)
for _, v := range bs {
if isNumberByte(v) {
n := convertByteNumber2Integer(v)
if n != NotNum {
numbers = append(numbers, n)
}
}
}
return numbers
}
func filterEvenNumbers(oriNumbers []int) (EvenNumbers []int) {
for _, v := range oriNumbers {
if v%2 == 0 {
EvenNumbers = append(EvenNumbers, v)
}
}
return
}
func convertByteNumber2Integer(b byte) int {
if !isNumberByte(b) {
return NotNum
}
return int(b - '0')
}
func isNumberByte(b byte) bool {
if b >= '0' && b <= '9' {
return true
}
return false
}
func isAEvenNumberByte(b byte) bool {
evenList := getEvenNumByteList()
for _, v := range evenList {
if v == b {
return true
}
}
return false
}
func getNumByteList() []byte {
return []byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
}
func getEvenNumByteList() []byte {
return []byte{'0', '2', '4', '6', '8'}
}
func trimLastChar(s string) string {
r, size := utf8.DecodeLastRuneInString(s)
if r == utf8.RuneError && (size == 0 || size == 1) {
size = 0
}
return s[:len(s)-size]
}
|
[
2
] |
package g53
import (
"errors"
"github.com/mistletoeChao/g53/util"
)
type SPF struct {
Data []string
}
func (spf *SPF) Rend(r *MsgRender) {
rendField(RDF_C_TXT, spf.Data, r)
}
func (spf *SPF) ToWire(buffer *util.OutputBuffer) {
fieldToWire(RDF_C_TXT, spf.Data, buffer)
}
func (spf *SPF) String() string {
return fieldToStr(RDF_D_TXT, spf.Data)
}
func SPFFromWire(buffer *util.InputBuffer, ll uint16) (*SPF, error) {
f, ll, err := fieldFromWire(RDF_C_TXT, buffer, ll)
if err != nil {
return nil, err
} else if ll != 0 {
return nil, errors.New("extra data in rdata part when parse spf")
} else {
data, _ := f.([]string)
return &SPF{data}, nil
}
}
func SPFFromString(s string) (*SPF, error) {
f, err := fieldFromStr(RDF_D_TXT, s)
if err != nil {
return nil, err
} else {
return &SPF{f.([]string)}, nil
}
}
|
[
5
] |
package payanother
import (
"github.com/pkg/errors"
"net/http"
"fmt"
)
type SendParam struct {
MertNo string
EncryptKey string
ConfValue string // 通道的其他配置,必须用json格式
OrderNo string
Amount int
BankCode string
BusType int // 0:对私;1:对公
AccountName string
CardNo string
Attach string
NotifyURL string
}
type SendResp struct {
ThirdOrderNo string
PayAmount int
Status int // 1:成功;2:失败;3:处理中
Msg string
}
func Send(name string, param *SendParam) (*SendResp, error) {
fmt.Println(param)
if v, ok := GetBankMap(name)[param.BankCode]; ok {
param.BankCode = v
}
switch name {
case PayAnother_huitao:
return new(HuiTaoPay).Pay(param)
}
return nil, errors.New("代付通道不存在")
}
func Notice(name string, w http.ResponseWriter, r *http.Request, getMd5Key func(args ... string) string, busCallback func(args ... string) bool) error {
switch name {
case PayAnother_huitao:
return new(HuiTaoPay).Notice(w, r, getMd5Key, busCallback)
}
return errors.New("Channel not found")
}
type QueryBalanceParam struct {
MertNo string
EncryptKey string
ConfValue string // 通道的其他配置,必须用json格式
}
func QueryBalance(name string, param *QueryBalanceParam) (int, error) {
switch name {
case PayAnother_huitao:
return new(HuiTaoPay).QueryBalance(param)
}
return 0, errors.New("该通道不支持余额查询")
}
|
[
7
] |
package cron
import (
"bytes"
"fmt"
"reflect"
"strconv"
"strings"
"testing"
)
// Supported values and formats
func TestParseList(t *testing.T) {
// Supported
t.Run("anyValue set first bit", th(parseListReq("*", frame{}), 1<<0, false))
t.Run("list set first bit", th(parseListReq("0", frame{0, 1}), 1<<0, false))
t.Run("list set multiple bits", th(parseListReq("0,1", frame{0, 1}), 1<<0|1<<1, false))
t.Run("range set multiple bits", th(parseListReq("1-2", frame{1, 2}), 1<<1|1<<2, false))
t.Run("anyValue with step", th(parseListReq("*/2", frame{0, 3}), 1<<0|1<<2, false))
t.Run("range with step", th(parseListReq("0-5/2", frame{0, 9}), 1<<0|1<<2|1<<4, false))
t.Run("range with step and offset", th(parseListReq("1-5/2", frame{0, 9}), 1<<1|1<<3|1<<5, false))
t.Run("range with step > frame.max", th(parseListReq("1-5/20", frame{0, 9}), 1<<1, false))
t.Run("list, range, list", th(parseListReq("4,3-5,2", frame{2, 5}), 1<<4|1<<3|1<<5|1<<2, false))
t.Run("zero step", th(parseListReq("*/0", frame{0, 3}), 0, false))
t.Run("reversed range", th(parseListReq("3-1", frame{0, 3}), 1<<0|1<<1|1<<3, false))
t.Run("reversed range with step", th(parseListReq("3-1/2", frame{0, 3}), 1<<0|1<<3, false))
// Not supported
t.Run("empty value", th(parseListReq("", frame{0, 3}), 0, true))
t.Run("invalid character", th(parseListReq("i", frame{0, 3}), 0, true))
t.Run("list values out of frame", th(parseListReq("1,2", frame{}), 0, true))
t.Run("range values out of frame", th(parseListReq("1-2", frame{}), 0, true))
t.Run("invalid range format", th(parseListReq("1-2-3", frame{0, 3}), 0, true))
t.Run("incomplete range format", th(parseListReq("-1", frame{0, 3}), 0, true))
t.Run("invalid chars in before step", th(parseListReq("p/1", frame{0, 3}), 0, true))
t.Run("invalid chars in step", th(parseListReq("1/p", frame{0, 3}), 0, true))
t.Run("invalid chars in range from", th(parseListReq("p-1", frame{0, 3}), 0, true))
t.Run("invalid chars in range to", th(parseListReq("1-p", frame{0, 3}), 0, true))
t.Run("invalid chars in range with step", th(parseListReq("1-p/4", frame{0, 3}), 0, true))
t.Run("invalid chars in step with range", th(parseListReq("1-2/p", frame{0, 3}), 0, true))
}
func TestAround(t *testing.T) {
// 5-2 -> 5 6 7 0 1 2
t.Run("non-standard step format", th(parseListReq("5-2", frame{0, 7}), 1<<0|1<<1|1<<2|1<<5|1<<6|1<<7, false))
t.Run("non-standard step format", th(parseListReq("5-2", frame{0, 3}), 0, true))
}
func TestNonStandard(t *testing.T) {
// 0 1 2 3
// 1
t.Run("non-standard step format", th(parseListReq("1/3", frame{0, 3}), 1<<1, false))
// 0 1 2 3
// 1 1 1
t.Run("non-standard step with list", th(parseListReq("1,2,3/8", frame{0, 3}), 1<<1|1<<2|1<<3, false))
}
func TestFieldsFrame(t *testing.T) {
// 0-59
t.Run("Minute", func(t *testing.T) {
fr := frames["minute"]
t.Run("input in frame", th(parseListReq("0-59", fr), (1<<(fr.max+1)-1), false))
t.Run("input out of frame", th(parseListReq("60", fr), 0, true))
})
// 0-23
t.Run("Hour", func(t *testing.T) {
fr := frames["hour"]
t.Run("input in frame", th(parseListReq("0-23", fr), (1<<(fr.max+1)-1), false))
t.Run("input out of frame", th(parseListReq("0-24", fr), 0, true))
t.Run("input 0", th(parseListReq("0", fr), 1, false))
})
// 1-31
t.Run("DayOfMonth", func(t *testing.T) {
fr := frames["dayOfMonth"]
t.Run("input in frame", th(parseListReq("1-31", fr), (1<<(fr.max)-1)<<1, false))
t.Run("input out of frame", th(parseListReq("0,1,2", fr), 0, true))
})
// 1-12
t.Run("Month", func(t *testing.T) {
fr := frames["month"]
t.Run("input in frame", th(parseListReq("1,2,11-12", fr), 1<<1|1<<2|1<<11|1<<12, false))
t.Run("input out of frame", th(parseListReq("1,2,12-13", fr), 0, true))
})
// 0-7
t.Run("DayOfWeek", func(t *testing.T) {
fr := frames["dayOfWeek"]
t.Run("input in frame", th(parseListReq("4,3-5,2", fr), 1<<4|1<<3|1<<5|1<<2, false))
t.Run("input out of frame", th(parseListReq("6,7,8,5", fr), 0, true))
})
}
func TestParse(t *testing.T) {
t.Run("Valid input", func(t *testing.T) {
inp := "*/15 0 1,15 * 1-5"
exp := &Schedule{
Minutes: 1<<0 | 1<<15 | 1<<30 | 1<<45,
Hours: 1 << 0,
DaysOfMonth: 1<<1 | 1<<15,
Months: (1<<(12) - 1) << 1,
DaysOfWeek: 1<<1 | 1<<2 | 1<<3 | 1<<4 | 1<<5,
}
got, err := Parse(inp)
if err != nil {
t.Errorf("exp no err got %v", err)
}
if !reflect.DeepEqual(exp, got) {
t.Errorf("\nexp %v\ngot %v", exp, got)
}
})
t.Run("Missing/invalid input, exp err", func(t *testing.T) {
tt := []string{
"a * * * *",
"* */3 1,-2 * *",
"* */3 1-2 9- *",
"* */3 1-2 9 8",
"",
"* * * *",
}
for _, tc := range tt {
t.Run(tc, func(t *testing.T) {
got, err := Parse(tc)
if got != nil {
t.Errorf("%v exp nil schedule", tc)
}
if err == nil {
t.Errorf("%v exp err got nil", tc)
}
})
}
})
}
func rangeToString(min, max uint8) string {
arr := make([]string, max-min+1)
for i := range arr {
arr[i] = strconv.Itoa(int(min) + i)
}
return strings.Join(arr, " ")
}
func TestPrintMethodsAndTable(t *testing.T) {
schedule := &Schedule{
Minutes: 0xFFFFFFFFFFFFFFF,
Hours: 0xFFFFFF,
DaysOfMonth: 0xFFFFFFFF,
Months: 0xFFFF,
DaysOfWeek: 0xFF,
}
tt := []struct {
exp string
inp func() string
fr frame
}{
{"minute", schedule.PrintMinutes, frames["minute"]},
{"hour", schedule.PrintHours, frames["hour"]},
{"day of month", schedule.PrintDaysOfMonth, frames["dayOfMonth"]},
{"month", schedule.PrintMonths, frames["month"]},
{"day of week", schedule.PrintDaysOfWeek, frames["dayOfWeek"]},
}
var expBuf bytes.Buffer
for _, tc := range tt {
t.Run(tc.exp, func(t *testing.T) {
got := tc.inp()
exp := fmt.Sprintf("%-14s %s", tc.exp, rangeToString(tc.fr.min, tc.fr.max))
if !strings.HasPrefix(got, exp) {
t.Errorf("\nexp %v\ngot %v", exp, got)
}
expBuf.WriteString(exp)
expBuf.WriteString("\n")
})
}
var gotBuf bytes.Buffer
schedule.PrintTable(&gotBuf)
if gotBuf.String() != expBuf.String() {
t.Errorf("\ngot\n%v\nexp\n%v", expBuf.String(), gotBuf.String())
}
}
type parseListResp func() (uint64, error)
func parseListReq(s string, fr frame) parseListResp {
return func() (uint64, error) {
return parseList(s, fr)
}
}
func th(fn parseListResp, exp uint64, expErr bool) func(*testing.T) {
return func(t *testing.T) {
got, err := fn()
if expErr && err == nil {
t.Errorf("expected err, got nil")
}
if got != exp {
t.Errorf("\nexp %040b\ngot %040b", exp, got)
}
}
}
func TestExtractField(t *testing.T) {
tt := []struct {
inp, exp string
}{
{" */ ", "*/"},
{"\t*/\t", "*/"},
{"\t\t 1\t ", "1"},
}
for _, tc := range tt {
t.Run(tc.inp, func(t *testing.T) {
_, got := extractField(tc.inp)
if got != tc.exp {
t.Errorf("got %v exp %v", tc.exp, got)
}
})
}
}
|
[
1
] |
package ABC_problemC_gray
import (
"sort"
"strings"
"testing"
)
type Words []string
func (ws Words) Len() int {
return len(ws)
}
func (ws Words) Less(i, j int) bool {
if ws[i] < ws[j] {
return true
}
return false
}
func (ws Words) Swap(i, j int) {
ws[i], ws[j] = ws[j], ws[i]
}
// strings.Join のまま
func (ws Words) Join(sep string) string {
switch len(ws) {
case 0:
return ""
case 1:
return ws[0]
}
n := len(sep) * (len(ws) - 1)
for i := 0; i < len(ws); i++ {
n += len(ws[i])
}
var builder strings.Builder
builder.Grow(n)
builder.WriteString(ws[0])
for _, w := range ws[1:] {
builder.WriteString(sep)
builder.WriteString(w)
}
return builder.String()
}
type WordMap map[string]int
func (wm WordMap) MaxFreq() int {
var maxFreq int
for _, freq := range wm {
if maxFreq < freq {
maxFreq = freq
}
}
return maxFreq
}
// [ABC155C - Poll](https://atcoder.jp/contests/abc155/tasks/abc155_c)
func AnswerABC155Cその1(N int, S []string) string {
wordMap := make(WordMap)
for _, s := range S {
wordMap[s]++
}
var maxFreq = wordMap.MaxFreq()
var modeWords = make(Words, 0, len(wordMap))
for word, freq := range wordMap {
if freq == maxFreq {
modeWords = append(modeWords, word)
}
}
// keysをソートして昇順にしてもいい(というか、そのほうがスッキリ)
sort.Stable(modeWords)
return modeWords.Join("\n")
}
func TestAnswerABC155Cその1(t *testing.T) {
tests := []struct {
name string
N int
S []string
want string
}{
{
"入力例1",
7,
[]string{"beat", "vet", "beet", "bed", "vet", "bet", "beet"},
"beet\nvet",
},
{
"入力例2",
8,
[]string{"buffalo", "buffalo", "buffalo", "buffalo", "buffalo", "buffalo", "buffalo", "buffalo"},
"buffalo",
},
{
"入力例3",
7,
[]string{"bass", "bass", "kick", "kick", "bass", "kick", "kick"},
"kick",
},
{
"入力例4",
4,
[]string{"ushi", "tapu", "nichia", "kun"},
"kun\nnichia\ntapu\nushi",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := AnswerABC155Cその1(tt.N, tt.S)
if got != tt.want {
t.Errorf("got %v want %v", got, tt.want)
}
})
}
}
|
[
2
] |
package problems
import (
"io/ioutil"
"strings"
"strconv"
"math"
)
func LIA() {
dat, err := ioutil.ReadFile("inputs/lia.in")
check(err)
result := SolutionLIA(string(dat))
err = ioutil.WriteFile("inputs/lia.out", []byte(result), 0644)
check(err)
}
func SolutionLIA(s string) string{
inputs := strings.Split(s, " ")
n0, err := strconv.ParseFloat(inputs[0], 64)
check(err)
n1, err := strconv.ParseFloat(inputs[1], 64)
check(err)
return strconv.FormatFloat(calcIndependentAlleles(n0, n1), 'f', -1, 64)
}
func calcIndependentAlleles(k, n float64) float64{
sum := 0.0
for i := 0.0; i < n; i++{
sum = sum + binomial(math.Pow(2.0,k), i) * math.Pow(0.25,i) * math.Pow(0.75,(math.Pow(2.0,k) - i))
}
return 1.0 - sum
}
// return binomial(2**k, n) * 0.25**n * 0.75**(2**k - n)
// return 1 - sum([P(n, k) for n in range(N)])
|
[
0
] |
package main
import (
"bufio"
"fmt"
"log"
"os"
"sort"
"strings"
"time"
)
// Log hello
type Log struct {
id int
timestamp time.Time
activity int
}
func main() {
src, err := os.Open("./input.txt")
if err != nil {
log.Fatalf("Failed to open file: %v\n", err)
}
defer src.Close()
logs := []Log{}
scanner := bufio.NewScanner(src)
for scanner.Scan() {
line := scanner.Text()
var y, m, d, h, min int
var desc string
var l Log
if !strings.Contains(line, "#") {
_, err := fmt.Sscanf(line, "[%d-%d-%d %d:%d] %s",
&y, &m, &d, &h, &min,
&desc)
l.id = -1
checkError(err)
} else {
_, err := fmt.Sscanf(line, "[%d-%d-%d %d:%d] %s #%d",
&y, &m, &d, &h, &min,
&desc, &l.id)
checkError(err)
}
l.timestamp = time.Date(y, time.Month(m), d, h, min, 0, 0, time.UTC)
if desc == "Guard" {
l.activity = 0
} else if desc == "wakes" {
l.activity = 2
} else {
l.activity = 1
}
logs = append(logs, l)
}
sort.Slice(logs, func(i, j int) bool { return logs[i].timestamp.Before(logs[j].timestamp) })
for i := 1; i < len(logs); i++ {
if logs[i].id == -1 {
logs[i].id = logs[i-1].id
}
}
fmt.Printf("Most asleep guard with min multiplied: %d\n", part1(logs))
fmt.Printf("Most frequent guard with min multiplied: %d\n", part2(logs))
}
func part1(logs []Log) int {
// Calcluate the numer of minutes slept for each guard
noOfMinutesSlept := make(map[int]int)
for i := 0; i < len(logs); i++ {
if _, ok := noOfMinutesSlept[logs[i].id]; ok {
if logs[i].activity == 2 {
// time awake - time asleep
noOfMinutesSlept[logs[i].id] += int(logs[i].timestamp.Sub(logs[i-1].timestamp).Minutes())
}
} else {
noOfMinutesSlept[logs[i].id] = 0
}
}
// Find the guard Id with the most minuites slept
var hSleepDuration, hDurationGuardID int
for currentID, currentMinutesSlept := range noOfMinutesSlept {
if currentMinutesSlept > hSleepDuration {
hDurationGuardID = currentID
hSleepDuration = currentMinutesSlept
}
}
// Fill out sleepSchedule with the frequency that
// that minute the guard is asleep in
var sleepSchedule [59]int
var lastAsleep int
for i := 0; i < len(logs); i++ {
// Filter for corrrect guard
if logs[i].id == hDurationGuardID {
// Check if activity is wake up or fell asleep
if logs[i].activity == 1 {
lastAsleep = logs[i].timestamp.Minute()
} else if logs[i].activity == 2 {
for j := lastAsleep; j < logs[i].timestamp.Minute(); j++ {
sleepSchedule[j]++
}
}
}
}
// Find most frequent minute
var mostFrequentMin, hFrequency int
for i := 0; i < len(sleepSchedule); i++ {
if sleepSchedule[i] > hFrequency {
hFrequency = sleepSchedule[i]
mostFrequentMin = i
}
}
return hDurationGuardID * mostFrequentMin
}
// part2 calculates the most common minute asleep * guard ID
func part2(logs []Log) int {
// Init noOfMinutesSlept with keys as guard ids and empty sleep schedules
noOfMinutesSlept := make(map[int][]int)
for i := 0; i < len(logs); i++ {
if _, ok := noOfMinutesSlept[logs[i].id]; !ok {
noOfMinutesSlept[logs[i].id] = make([]int, 59)
}
}
// Fill in all guards sleeping schedule
for currentGuardID, currentSleepSchedule := range noOfMinutesSlept {
var lastAsleep int
for i := 0; i < len(logs); i++ {
// Filter for correct guard
if logs[i].id == currentGuardID {
// Check if activity is wake up or fell asleep
if logs[i].activity == 1 {
lastAsleep = logs[i].timestamp.Minute()
} else if logs[i].activity == 2 {
for j := lastAsleep; j < logs[i].timestamp.Minute(); j++ {
currentSleepSchedule[j]++
}
}
}
}
}
// Find most frequent minute for any guard
var mostFrequentMin, hFrequency, hGuardID int
for currentGuardID, currentSleepSchedule := range noOfMinutesSlept {
for i := 0; i < len(currentSleepSchedule); i++ {
if currentSleepSchedule[i] > hFrequency {
hFrequency = currentSleepSchedule[i]
mostFrequentMin = i
hGuardID = currentGuardID
}
}
}
return hGuardID * mostFrequentMin
}
func checkError(err error) {
if err != nil {
log.Fatal(err)
}
}
|
[
1,
5
] |
package main
type MsgPrefix string
const (
MSGPREFIX_JOINED MsgPrefix = "001"
MSGPREFIX_REMOVED MsgPrefix = "002"
MSGPREFIX_MESSAGE MsgPrefix = "003"
MSGPREFIX_ERROR MsgPrefix = "999"
)
type ErrorCode int
const (
ERRORCODE_JOINED ErrorCode = 1
)
func getErrorCodeMessage(errorCode ErrorCode) string {
message := "Error"
switch errorCode {
case ERRORCODE_JOINED:
message = "接続できませんでした。"
}
return message
}
|
[
7
] |
package bench_test
import (
"testing"
"github.com/bsm/nanoid"
"github.com/chilts/sid"
"github.com/fogfish/guid/v2"
"github.com/google/uuid"
"github.com/itrabbit/rid"
"github.com/kjk/betterguid"
"github.com/lithammer/shortuuid/v3"
gonanoid "github.com/matoous/go-nanoid"
"github.com/rs/xid"
"github.com/segmentio/ksuid"
"github.com/wmentor/uniq"
)
func uuidNew() string { return uuid.New().String() }
func gonanoidNew() string { s, _ := gonanoid.Nanoid(); return s }
func guidNew() string { return guid.G(guid.Clock).String() }
func ridNew() string { return rid.New().String() }
func xidNew() string { return xid.New().String() }
func ksuidNew() string { return ksuid.New().String() }
func bench(b *testing.B, fn func() string, min, max int) {
for i := 0; i < b.N; i++ {
if s := fn(); len(s) < min || len(s) > max {
b.Fatalf("expected %d-%d chars, but got %d (%s)", min, max, len(s), s)
}
}
}
func pbench(b *testing.B, fn func() string, min, max int) {
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
if s := fn(); len(s) < min || len(s) > max {
b.Fatalf("expected %d-%d chars, but got %d (%s)", min, max, len(s), s)
}
}
})
}
func Benchmark_random(b *testing.B) {
b.Run("bsm/nanoid", func(b *testing.B) { // "Q2mAgYI9yIgSPd9ENknGM"
bench(b, nanoid.New, 21, 21)
})
b.Run("google/uuid", func(b *testing.B) { // "6887c36e-85ba-4d64-80fe-0e14ee38e2a2"
bench(b, uuidNew, 36, 36)
})
b.Run("lithammer/shortuuid", func(b *testing.B) { // "DSNxRpoZZPa6Eb9GkMD"
bench(b, shortuuid.New, 18, 22)
})
b.Run("matoous/go-nanoid", func(b *testing.B) { // "rhANQ2U-QMnfNVvDnZaSs"
bench(b, gonanoidNew, 21, 21)
})
}
func Benchmark_random_parallel(b *testing.B) {
b.Run("bsm/nanoid", func(b *testing.B) { // "Q2mAgYI9yIgSPd9ENknGM"
pbench(b, nanoid.New, 21, 21)
})
b.Run("google/uuid", func(b *testing.B) { // "6887c36e-85ba-4d64-80fe-0e14ee38e2a2"
pbench(b, uuidNew, 36, 36)
})
b.Run("lithammer/shortuuid", func(b *testing.B) { // "DSNxRpoZZPa6Eb9GkMD"
pbench(b, shortuuid.New, 18, 22)
})
b.Run("matoous/go-nanoid", func(b *testing.B) { // "rhANQ2U-QMnfNVvDnZaSs"
pbench(b, gonanoidNew, 21, 21)
})
}
func Benchmark_sorted(b *testing.B) {
b.Run("chilts/sid", func(b *testing.B) { // "1599734701420031946-7468365110993091186"
bench(b, sid.Id, 39, 39)
})
b.Run("fogfish/guid", func(b *testing.B) { // "NgOglOfNRUy5c7.0"
bench(b, guidNew, 16, 16)
})
b.Run("itrabbit/rid", func(b *testing.B) { // "8n2q609dtz97m42o67e0"
bench(b, ridNew, 20, 20)
})
b.Run("kjk/betterguid", func(b *testing.B) { // "-MGrcC-au8zVbV_nR7mH"
bench(b, betterguid.New, 20, 20)
})
b.Run("rs/xid", func(b *testing.B) { // "btd08je7gngoc3t23on0"
bench(b, xidNew, 20, 20)
})
b.Run("segmentio/ksuid", func(b *testing.B) { // "1hJgyJ1FomiECVaJTV1kWmbzoQE"
bench(b, ksuidNew, 27, 27)
})
b.Run("wmentor/uniq", func(b *testing.B) { // "a7b1d7c7d1458316336661f00320551368"
bench(b, uniq.New, 32, 34)
})
}
func Benchmark_sorted_parallel(b *testing.B) {
b.Run("chilts/sid", func(b *testing.B) { // "1599734701420031946-7468365110993091186"
pbench(b, sid.Id, 39, 39)
})
b.Run("fogfish/guid", func(b *testing.B) { // "NgOglOfNRUy5c7.0"
pbench(b, guidNew, 16, 16)
})
b.Run("itrabbit/rid", func(b *testing.B) { // "8n2q609dtz97m42o67e0"
pbench(b, ridNew, 20, 20)
})
b.Run("kjk/betterguid", func(b *testing.B) { // "-MGrcC-au8zVbV_nR7mH"
pbench(b, betterguid.New, 20, 20)
})
b.Run("rs/xid", func(b *testing.B) { // "btd08je7gngoc3t23on0"
pbench(b, xidNew, 20, 20)
})
b.Run("segmentio/ksuid", func(b *testing.B) { // "1hJgyJ1FomiECVaJTV1kWmbzoQE"
pbench(b, ksuidNew, 27, 27)
})
b.Run("wmentor/uniq", func(b *testing.B) { // "a7b1d7c7d1458316336661f00320551368"
pbench(b, uniq.New, 32, 34)
})
}
|
[
1
] |
package engine
import (
"math"
)
type Piece struct {
White bool
Square bool
x int
y int
}
type direction int
const (
up direction = iota
down
left
right
)
func NewWhiteSquarePiece() *Piece {
return &Piece{White: true, Square: true}
}
func NewWhiteRoundPiece() *Piece {
return &Piece{White: true, Square: false}
}
func NewBlackSquarePiece() *Piece {
return &Piece{White: false, Square: true}
}
func NewBlackRoundPiece() *Piece {
return &Piece{White: false, Square: false}
}
func (p *Piece) PlacePiece(x, y int) {
p.x = x
p.y = y
}
func (p Piece) CanPush(g *Game, x, y int) bool {
if !p.Square || g.Board[y][x].Piece == nil {
return false
}
if p.x == x && p.y == y {
return false
}
dX := float64(x - p.x)
dXSq := math.Pow(dX, 2)
dY := float64(y - p.y)
dYSq := math.Pow(dY, 2)
D := math.Sqrt(dXSq + dYSq)
if D == 0 || D > 1 {
return false
}
if dX < 0 {
return checkDir(g, left, p.x, p.y)
} else if dX > 0 {
return checkDir(g, right, p.x, p.y)
} else if dY < 0 {
return checkDir(g, up, p.x, p.y)
} else if dY > 0 {
return checkDir(g, down, p.x, p.y)
}
return false
}
func checkDir(g *Game, dir direction, x, y int) bool {
switch dir {
case down:
if y+1 > len(g.Board)-1 {
return false
}
if g.Board[y+1][x].Tile == WallTile || (y+1 == g.AnchorY && x == g.AnchorX) {
return false
}
if g.Board[y+1][x].Piece != nil {
if checkDir(g, down, x, y+1) {
g.Board[y+1][x].Piece = g.Board[y][x].Piece
g.Board[y+1][x].Piece.PlacePiece(x, y+1)
g.Board[y][x].Piece = nil
return true
}
} else if g.Board[y+1][x].Tile == EmptyTile || g.Board[y+1][x].Tile == DeadlyTile {
if g.Board[y+1][x].Tile == DeadlyTile {
g.DeadPiece = g.Board[y][x].Piece
}
g.Board[y+1][x].Piece = g.Board[y][x].Piece
g.Board[y+1][x].Piece.PlacePiece(x, y+1)
g.Board[y][x].Piece = nil
return true
}
case up:
if y-1 < 0 {
return false
}
if g.Board[y-1][x].Tile == WallTile || (y-1 == g.AnchorY && x == g.AnchorX) {
return false
}
if g.Board[y-1][x].Piece != nil {
if checkDir(g, up, x, y-1) {
g.Board[y-1][x].Piece = g.Board[y][x].Piece
g.Board[y-1][x].Piece.PlacePiece(x, y-1)
g.Board[y][x].Piece = nil
return true
}
} else if g.Board[y-1][x].Tile == EmptyTile || g.Board[y-1][x].Tile == DeadlyTile {
if g.Board[y-1][x].Tile == DeadlyTile {
g.DeadPiece = g.Board[y][x].Piece
}
g.Board[y-1][x].Piece = g.Board[y][x].Piece
g.Board[y-1][x].Piece.PlacePiece(x, y-1)
g.Board[y][x].Piece = nil
return true
}
case left:
if x-1 < 1 {
return false
}
if g.Board[y][x-1].Tile == WallTile || (y == g.AnchorY && x-1 == g.AnchorX) {
return false
}
if g.Board[y][x-1].Piece != nil {
if checkDir(g, left, x-1, y) {
g.Board[y][x-1].Piece = g.Board[y][x].Piece
g.Board[y][x-1].Piece.PlacePiece(x-1, y)
g.Board[y][x].Piece = nil
return true
}
} else if g.Board[y][x-1].Tile == EmptyTile || g.Board[y][x-1].Tile == DeadlyTile {
if g.Board[y][x-1].Tile == DeadlyTile {
g.DeadPiece = g.Board[y][x].Piece
}
g.Board[y][x-1].Piece = g.Board[y][x].Piece
g.Board[y][x-1].Piece.PlacePiece(x-1, y)
g.Board[y][x].Piece = nil
return true
}
case right:
if x+1 > len(g.Board)-2 {
return false
}
if g.Board[y][x+1].Tile == WallTile || (y == g.AnchorY && x+1 == g.AnchorX) {
return false
}
if g.Board[y][x+1].Piece != nil {
if checkDir(g, right, x+1, y) {
g.Board[y][x+1].Piece = g.Board[y][x].Piece
g.Board[y][x+1].Piece.PlacePiece(x+1, y)
g.Board[y][x].Piece = nil
return true
}
} else if g.Board[y][x+1].Tile == EmptyTile || g.Board[y][x+1].Tile == DeadlyTile {
if g.Board[y][x+1].Tile == DeadlyTile {
g.DeadPiece = g.Board[y][x].Piece
}
g.Board[y][x+1].Piece = g.Board[y][x].Piece
g.Board[y][x+1].Piece.PlacePiece(x+1, y)
g.Board[y][x].Piece = nil
return true
}
}
return false
}
func (p Piece) CanMove(g *Game, x, y int) bool {
start := g.Board[p.y][p.x]
dest := g.Board[y][x]
if dest.Piece != nil {
return false
}
if dest.Tile != EmptyTile {
return false
}
stX := p.x
stY := p.y
cl := CheckList{}
return checkSquare(g, &p, &start, &cl, stX, stY, x, y)
}
type position struct {
X, Y int
}
type CheckList struct {
Positions []position
}
func (cl *CheckList) add(x, y int) {
cl.Positions = append(cl.Positions, position{x, y})
}
func (cl CheckList) HasBeenChecked(x, y int) bool {
for i := range cl.Positions {
if cl.Positions[i].X == x && cl.Positions[i].Y == y {
return true
}
}
return false
}
func checkSquare(g *Game, p *Piece, sq *Square, cl *CheckList, cX, cY, dX, dY int) bool {
if cl.HasBeenChecked(cX, cY) {
return false
}
cl.add(cX, cY)
if (cX == dX) && cY == dY {
return true
}
if sq.Piece != nil && len(cl.Positions) > 1 {
return false
}
if sq.Tile != EmptyTile {
return false
}
var newX int
var newY int
newY = cY - 1
if newY >= 0 {
if checkSquare(g, p, &g.Board[newY][cX], cl, cX, newY, dX, dY) {
return true
}
}
newY = cY + 1
if newY < len(g.Board) {
if checkSquare(g, p, &g.Board[newY][cX], cl, cX, newY, dX, dY) {
return true
}
}
newX = cX + 1
if newX < len(g.Board[cY]) {
if checkSquare(g, p, &g.Board[cY][newX], cl, newX, cY, dX, dY) {
return true
}
}
newX = cX - 1
if newX > 0 {
if checkSquare(g, p, &g.Board[cY][newX], cl, newX, cY, dX, dY) {
return true
}
}
return false
}
|
[
5
] |
package logic
import "strconv"
const (
// Frog1 1
Frog1 int = 1
// Frog2 2
Frog2 int = 2
// Frog3 3
Frog3 int = 3
// Frog4 4
Frog4 int = 4
// Frog5 5
Frog5 int = 5
// Frog6 6
Frog6 int = 6
)
// Game1006 游戏
type Game1006 struct {
frog []int // 青蛙
name map[string]int // 名称
image string // 图片
}
// GetID 获取编号
func (g *Game1006) GetID() int {
return 1006
}
// IsSucceed 是否成功
func (g *Game1006) IsSucceed() bool {
if g.frog[0] == 4 && g.frog[1] == 5 && g.frog[2] == 6 &&
g.frog[4] == 1 && g.frog[5] == 2 && g.frog[6] == 3 {
return true
}
return false
}
// Background 背景
func (g *Game1006) Background() string {
return `两队青蛙狭路相逢,(1.2.3)向右移动,(4.5.6)向左移动,移动的规则就是跳棋游戏的规则,你能指挥它们顺利跳过吗?`
}
// Description 描述
func (g *Game1006) Description() string {
return `青蛙:一(1)、二(2)、三(3)、四(4)、五(5)、六(6)
无需输入 跳 操作
跳一号青蛙请输入:一 或 1
支持语音识别,请说普通话
跳一号青蛙请发送语音:一`
}
// OnGameEvent 游戏事件
func (g *Game1006) OnGameEvent(event string) string {
which, ok := g.name[event]
if !ok {
return "非法青蛙"
}
pos := Index(g.frog, which)
if pos == -1 {
return "出现严重问题"
}
if which <= Frog3 {
if pos+1 < len(g.frog) && g.frog[pos+1] == 0 {
g.frog[pos], g.frog[pos+1] = g.frog[pos+1], g.frog[pos]
} else if pos+2 < len(g.frog) && g.frog[pos+2] == 0 {
g.frog[pos], g.frog[pos+2] = g.frog[pos+2], g.frog[pos]
} else {
return "无法向右跳动青蛙"
}
} else if which >= Frog4 {
if pos-1 >= 0 && g.frog[pos-1] == 0 {
g.frog[pos], g.frog[pos-1] = g.frog[pos-1], g.frog[pos]
} else if pos-2 >= 0 && g.frog[pos-2] == 0 {
g.frog[pos], g.frog[pos-2] = g.frog[pos-2], g.frog[pos]
} else {
return "无法向左跳动青蛙"
}
}
if g.frog[0] == 4 && g.frog[1] == 5 && g.frog[2] == 6 &&
g.frog[4] == 1 && g.frog[5] == 2 && g.frog[6] == 3 {
return g.GameScene() + "\n\n恭喜过关"
}
return g.GameScene()
}
// OnGameStart 游戏开始
func (g *Game1006) OnGameStart() string {
g.frog = []int{1, 2, 3, 0, 4, 5, 6}
g.name = map[string]int{"yi": 1, "er": 2, "san": 3, "si": 4, "wu": 5, "liu": 6, "一": Frog1, "二": Frog2,
"三": Frog3, "四": Frog4, "五": Frog5, "六": Frog6, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6}
g.image = "pEnTAPWdIFaIB0fVJT1nvxQDDKYATgNCzGUYo6OwbYg"
return g.GameScene()
}
// GameImage 游戏图片
func (g *Game1006) GameImage() string {
var image string
if g.image != "" {
image = g.image
g.image = ""
}
return image
}
// GameScene 游戏场景
func (g *Game1006) GameScene() string {
scene := "青蛙信息:"
for k, v := range g.frog {
if v != 0 {
scene += strconv.Itoa(v)
} else {
scene += "_"
}
if k+1 != len(g.frog) {
scene += " "
}
}
return scene
}
// GameTips 提示
func (g *Game1006) GameTips() string {
return "跳之前先把对面的青蛙跳到自己面前"
}
// Strategy 攻略
func (g *Game1006) Strategy() string {
return "pEnTAPWdIFaIB0fVJT1nv30aGZLKjR5pp2KEonUk_Ck"
}
// Remind 提醒
func (g *Game1006) Remind() string {
if g.frog[0] == 4 && g.frog[1] == 5 && g.frog[2] == 6 &&
g.frog[4] == 1 && g.frog[5] == 2 && g.frog[6] == 3 {
return "您已通关青蛙直线跳棋,请通过点击菜单或发送指令选择其它游戏继续挑战"
}
return "还未通关青蛙直线跳棋,开动脑筋继续挑战吧,当然您也可以通过点击菜单或发送指令获取提示和攻略\n\n" + g.GameScene()
}
|
[
5
] |
package main
import (
"database/sql"
"log"
"net/http"
"net/url"
"time"
"os"
"path/filepath"
"github.com/BurntSushi/toml"
"gopkg.in/telegram-bot-api.v4"
_ "github.com/mattn/go-sqlite3"
"github.com/doylecnn/NSFCbot/command"
)
func main() {
var err error
exefile, err := os.Executable()
if err != nil {
panic(err)
}
exePath := filepath.Dir(exefile)
var config tomlConfig
if _, err = toml.DecodeFile(filepath.Join(exePath, "config.toml"), &config); err != nil {
log.Fatalln(err)
return
}
db, err := sql.Open("sqlite3", filepath.Join(exePath, config.Database.DBName))
if err != nil {
log.Fatalln(err)
}
defer db.Close()
initDB(db)
var (
addFC = AddFC{db:db}
myFC = MyFC{db:db}
fc = FC{db:db}
sfc = SFC{db:db}
fclist = FCList{db:db}
router = command.NewRouter()
)
router.HandleFunc("addfc", addFC.Do)
router.HandleFunc("myfc", myFC.Do)
router.HandleFunc("fc", fc.Do)
router.HandleFunc("sfc", sfc.Do)
router.HandleFunc("fclist", fclist.Do)
bot := initBotAPI(config.Telegram.Token, config.Misc.Proxy)
bot.Debug = config.Telegram.Debug
log.Printf("Authorized on account: %s", bot.Self.UserName)
log.Printf("dbname: %s", config.Database.DBName)
u := tgbotapi.NewUpdate(0)
u.Timeout = config.Telegram.UpdateTimeout
updates, err := bot.GetUpdatesChan(u)
time.Sleep(time.Millisecond * 500)
updates.Clear()
for update := range updates {
if update.InlineQuery != nil {
if update.InlineQuery.Query == "myFC"{
text, err := inlineQueryAnswer(db, update.InlineQuery)
if err != nil{
log.Println(err)
continue
}
article := tgbotapi.NewInlineQueryResultArticleMarkdown(update.InlineQuery.ID, "MyFC", text)
article.Description = update.InlineQuery.Query
btns := tgbotapi.NewInlineKeyboardMarkup(tgbotapi.NewInlineKeyboardRow(tgbotapi.NewInlineKeyboardButtonData("赞","赞的event_id")))
article.ReplyMarkup = &btns
inlineConf := tgbotapi.InlineConfig{
InlineQueryID: update.InlineQuery.ID,
IsPersonal: true,
CacheTime: 0,
Results: []interface{}{article},
}
if _, err := bot.AnswerInlineQuery(inlineConf); err != nil {
log.Println(err)
}
}
}else if update.CallbackQuery != nil{
callback := update.CallbackQuery
log.Println(callback.Data)
bot.AnswerCallbackQuery(tgbotapi.NewCallback(callback.ID,"测试成功"))
}else if update.Message != nil{
go func(message *tgbotapi.Message){
if (message.Chat.IsGroup() || message.Chat.IsSuperGroup()) && message.IsCommand() {
messageSendTime := time.Unix(int64(message.Date), 0)
if time.Since(messageSendTime).Seconds() > 30 {
return
}
replyMessage, err := router.Run(message)
if err != nil {
log.Printf("%s", err.InnerError)
if len(err.ReplyText) > 0 {
replyMessage = &tgbotapi.MessageConfig{
BaseChat: tgbotapi.BaseChat{
ChatID: message.Chat.ID,
ReplyToMessageID: message.MessageID},
Text: err.ReplyText}
}
}
if replyMessage != nil {
bot.Send(*replyMessage)
}
}
}(update.Message)
}
}
}
func initDB(db *sql.DB) {
_, err := db.Exec(`CREATE TABLE IF NOT EXISTS user_NSFC(userID int64 not null unique, fc int64 not null, username text not null);
CREATE UNIQUE INDEX IF NOT EXISTS nsfc_idx_1 ON user_NSFC (userID, fc);
CREATE TABLE IF NOT EXISTS group_user(groupID not null, userID int64 not null);
CREATE UNIQUE INDEX IF NOT EXISTS group_idx_1 ON group_user (groupID, userid);`)
if err != nil {
log.Fatalln(err)
}
}
func initBotAPI(token, proxy string) (bot *tgbotapi.BotAPI) {
var err error
if len(proxy) > 0 {
client, err := createProxyClient(proxy)
if err != nil {
log.Fatalln(err)
}
bot, err = tgbotapi.NewBotAPIWithClient(token, client)
if err != nil {
log.Fatalf("Some error occur: %s.\n", err)
}
}else{
bot, err = tgbotapi.NewBotAPI(token)
if err != nil {
log.Fatalln(err)
}
}
return
}
func createProxyClient(proxy string) (client *http.Client, err error) {
log.Println("verify proxy:", proxy)
var proxyURL *url.URL
proxyURL, err = url.Parse(proxy)
if err == nil {
client = &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)}}
var r *http.Response
r, err = client.Get("https://www.google.com")
if err != nil || r.StatusCode != 200 {
return
}
}
return
}
|
[
5
] |
package pretty
import (
"fmt"
"sort"
"strings"
"github.com/fatih/color"
"github.com/google/uuid"
"github.com/pachyderm/pachyderm/v2/src/pps"
)
type renderConfig struct {
boxWidth int
edgeHeight int
}
type RenderOption func(*renderConfig)
func BoxWidthOption(boxWidth int) RenderOption {
return func(ro *renderConfig) {
ro.boxWidth = boxWidth
}
}
func EdgeHeightOption(verticalSpace int) RenderOption {
return func(ro *renderConfig) {
ro.edgeHeight = verticalSpace
}
}
type vertex struct {
id string
label string
edges map[string]*vertex
layer int
rowOffset int
red bool
}
func newVertex(label string) *vertex {
return &vertex{id: uuid.New().String(), label: label, edges: make(map[string]*vertex)}
}
func dummyVertex() *vertex {
return &vertex{id: uuid.New().String(), label: "*", edges: make(map[string]*vertex)}
}
func (v *vertex) addEdge(u *vertex) {
v.edges[u.id] = u
}
func (v *vertex) removeEdge(u *vertex) {
delete(v.edges, u.id)
}
type layerer func([]*vertex) [][]*vertex
type orderer func([][]*vertex)
func Draw(pis []*pps.PipelineInfo, opts ...RenderOption) (string, error) {
ro := &renderConfig{
boxWidth: 11,
edgeHeight: 5,
}
for _, o := range opts {
o(ro)
}
g, err := makeGraph(pis)
if err != nil {
return "", err
}
return draw(g, layerLongestPath, orderGreedy, ro), nil
}
func makeGraph(pis []*pps.PipelineInfo) ([]*vertex, error) {
vMap := make(map[string]*vertex)
vs := make([]*vertex, 0)
upsertVertex := func(name string, lastState pps.JobState) *vertex {
v := newVertex(name)
if _, ok := vMap[name]; !ok {
vMap[name] = v
vs = append(vs, v)
}
if lastState == pps.JobState_JOB_FAILURE || lastState == pps.JobState_JOB_KILLED {
vMap[name].red = true
}
return vMap[name]
}
for _, pi := range pis {
pv := upsertVertex(pi.Pipeline.Name, pi.LastJobState)
if err := pps.VisitInput(pi.Details.Input, func(input *pps.Input) error {
var name string
if input.Pfs != nil {
name = input.Pfs.Name
} else if input.Cron != nil {
name = input.Cron.Name
} else {
return nil
}
iv := upsertVertex(name, pps.JobState_JOB_STATE_UNKNOWN)
iv.addEdge(pv)
return nil
}); err != nil {
return nil, err
}
}
return vs, nil
}
func draw(vertices []*vertex, lf layerer, of orderer, ro *renderConfig) string {
// Assign Layers
layers := lf(vertices)
of(layers)
assignCoordinates(layers, ro)
picture := renderPicture(layers, ro)
return picture
}
// precompute the box coordinates so that during rendering the edges can be filled between layers
func assignCoordinates(layers [][]*vertex, ro *renderConfig) {
maxWidth := rowWidth(layers, ro)
for _, l := range layers {
boxCenterOffset := maxWidth / (len(l) + 1)
for j := 0; j < len(l); j++ {
l[j].rowOffset = (j + 1) * boxCenterOffset
}
}
}
// ==================================================
// Layering Algorithms
func layerLongestPath(vs []*vertex) [][]*vertex {
assigned := make(map[string]*vertex, 0)
var layers [][]*vertex
addToLayer := func(v *vertex, l int) {
if l >= len(layers) {
layers = append(layers, make([]*vertex, 0))
}
layers[l] = append(layers[l], v)
}
fillDummies := func(v *vertex) {
// we gather list of callbacks so that we don't mutate v.edges as we are iterating over it
cbs := make([]func(), 0)
for _, e := range v.edges {
diff := v.layer - e.layer
if diff > 1 {
u := e // necessary to copy the basic vertex fields
cbs = append(cbs, func() {
latest := v
for i := 0; i < diff-1; i++ {
d := dummyVertex()
d.addEdge(u)
addToLayer(d, v.layer-i-1)
latest.removeEdge(u)
latest.addEdge(d)
latest = d
}
})
}
}
for _, cb := range cbs {
cb()
}
}
// build the layers up from the bottom of the DAG
for _, v := range leaves(vs) {
assigned[v.id] = v
addToLayer(v, 0)
}
for len(vs) != len(assigned) {
for _, v := range vs {
func() {
if _, ok := assigned[v.id]; !ok {
var maxLevel int
// check this node is assignable
for _, e := range v.edges {
u, eDone := assigned[e.id]
if !eDone {
return
}
maxLevel = max(u.layer, maxLevel)
}
v.layer = maxLevel + 1
addToLayer(v, v.layer)
assigned[v.id] = v
fillDummies(v)
}
}()
}
}
return layers
}
// ==================================================
// Ordering Algorithms
func orderGreedy(layers [][]*vertex) {
var prev map[string]int
for i, l := range layers {
if i > 0 {
sort.Slice(l, func(i, j int) bool {
iScore, jScore := 0, 0
for u := range l[i].edges {
iScore += prev[u] - i
}
for u := range l[j].edges {
jScore += prev[u] - j
}
return iScore < jScore
})
}
prev = make(map[string]int)
for j, v := range l {
prev[v.id] = j
}
}
}
// ==================================================
// Rendering algorithm
func renderPicture(layers [][]*vertex, ro *renderConfig) string {
picture := ""
maxRowWidth := rowWidth(layers, ro)
// traverse the layers starting with source repos
for i := len(layers) - 1; i >= 0; i-- {
l := layers[i]
written := 0
row, border := "", ""
renderEdges := make([]renderEdge, 0)
// print the row of boxed vertices
for j := 0; j < len(l); j++ {
v := l[j]
colorSprint := color.New(color.FgHiGreen).SprintFunc()
if v.red {
colorSprint = color.New(color.FgHiRed).SprintFunc()
}
spacing := v.rowOffset - (ro.boxWidth+2)/2 - written
label := v.label
if len(label) > ro.boxWidth {
label = label[:ro.boxWidth-2] + ".."
}
boxPadLeft := strings.Repeat(" ", (ro.boxWidth-len(label))/2)
boxPadRight := strings.Repeat(" ", ro.boxWidth-len(label)-len(boxPadLeft))
if v.label == "*" {
hiddenRow := fmt.Sprintf("%s %s%s%s ", strings.Repeat(" ", spacing), boxPadLeft, "|", boxPadRight)
border += hiddenRow
row += hiddenRow
} else {
border += colorSprint(fmt.Sprintf("%s+%s+", strings.Repeat(" ", spacing), strings.Repeat("-", ro.boxWidth)))
row += colorSprint(fmt.Sprintf("%s|%s%s%s|", strings.Repeat(" ", spacing), boxPadLeft, label, boxPadRight))
}
written += spacing + len(boxPadLeft) + len(label) + len(boxPadRight) + 2
for _, u := range v.edges {
renderEdges = append(renderEdges, renderEdge{src: v.rowOffset, dest: u.rowOffset})
}
}
picture += fmt.Sprintf("%s\n%s\n%s\n", border, row, border)
// print up to `layerVerticalSpace` rows that will contain edge drawings
for j := 0; j < ro.edgeHeight; j++ {
row := strings.Repeat(" ", maxRowWidth)
for _, re := range renderEdges {
row = re.render(row, j, ro.edgeHeight)
}
picture += fmt.Sprint(row)
picture += "\n"
}
}
return picture
}
// renderEdge is used to describe the source and destination of an edge in terms of the x-axis.
// The number of vertical lines spanned is calculated at each layer
type renderEdge struct {
src int
dest int
}
func (re renderEdge) distance() int {
return abs(re.src - re.dest)
}
// render sets an edge character in the 'row' string, calculated using the re.src & re.dest (the edge's range along the x-axis),
// and 'vertDist' (the height of the edge) and 'vertIdx' (how many lines down 'vertDist' we are)
func (re renderEdge) render(row string, vertIdx, vertDist int) string {
setEdgeChar := func(s string, i int, r rune) string {
if s[i] == byte(r) {
return s
} else if s[i] == ' ' {
return s[:i] + string(r) + s[i+1:]
}
return s[:i] + "+" + s[i+1:] // set the coordinate to "+" if there's an edge crossing
}
if re.src == re.dest {
return setEdgeChar(row, re.src, '|')
}
const srcEdgeCenterOffset = 1 // start drawing a diagonal edge one space away from the center of a node
adjustedXDist := re.distance() - srcEdgeCenterOffset // number of horizontal spaces we must fill with edges
// vertical line
if vertDist > adjustedXDist && vertIdx >= adjustedXDist/2 && vertIdx < vertDist-adjustedXDist/2 {
return setEdgeChar(row, (re.src+re.dest)/2, '|')
}
// horizontal line
if vertDist < adjustedXDist && vertIdx == vertDist/2 {
step := 1
if re.src > re.dest {
step = -1
}
diagCoverage := (vertDist / 2) * step
tmp := re.src + diagCoverage
for tmp != re.dest-diagCoverage-(step*vertDist%2) {
tmp += step
row = setEdgeChar(row, tmp, '-')
}
return row
}
// diagonal line
offset := vertIdx + srcEdgeCenterOffset
// calculate offset based on distance from the end in case we're on the bottom half of the edge
if vertIdx > vertDist/2 {
offset = adjustedXDist - (vertDist - offset)
}
if re.src > re.dest {
return setEdgeChar(row, re.src-offset, '/')
} else {
return setEdgeChar(row, re.src+offset, '\\')
}
}
// ==================================================
func leaves(vs []*vertex) []*vertex {
ls := make([]*vertex, 0)
for _, v := range vs {
if len(v.edges) == 0 {
ls = append(ls, v)
}
}
return ls
}
func rowWidth(layers [][]*vertex, ro *renderConfig) int {
mlw := maxLayerWidth(layers)
return mlw * (ro.boxWidth + 2) * 2
}
func maxLayerWidth(layers [][]*vertex) int {
m := 0
for _, l := range layers {
m = max(m, len(l))
}
return m
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func abs(x int) int {
if x < 0 {
return x * -1
}
return x
}
|
[
5
] |
// https://leetcode.com/problems/search-insert-position/
package main
import (
"fmt"
"sort"
)
func searchInsert(nums []int, target int) int {
left, right, mid := 0, len(nums)-1, 0
for left <= right {
mid = (left + right) / 2
if nums[mid] < target {
left = mid + 1
} else if nums[mid] > target {
right = mid - 1
} else {
return mid
}
}
return right + 1
}
func main() {
a := []int{1, 2, 3, 1, 2, 3, 5}
sort.Ints(a)
fmt.Println(a)
fmt.Println(searchInsert(a, 3))
}
|
[
5
] |
package main
import (
"flag"
"github.com/bufsnake/SwitchProxy/config"
"github.com/bufsnake/SwitchProxy/internal"
"io/ioutil"
"log"
"strings"
)
func main() {
terminal := config.Terminal{}
flag.StringVar(&terminal.Listen, "listen", "127.0.0.1:8081", "listen port")
flag.StringVar(&terminal.Proxy, "proxy", "http://127.0.0.1:8080", "proxy address,support http/socks4/socks5 protocol")
flag.StringVar(&terminal.ProxyList, "proxy-list", "", "proxy address list,support http/socks4/socks5 protocol")
flag.Parse()
if terminal.Listen == "" {
flag.Usage()
return
}
proxys := make(map[string]interface{})
if terminal.ProxyList != "" {
file, err := ioutil.ReadFile(terminal.ProxyList)
if err != nil {
log.Fatal(err)
}
split := strings.Split(string(file), "\n")
for i := 0; i < len(split); i++ {
split[i] = strings.Trim(split[i], "\r")
if len(split[i]) != 0 {
proxys[split[i]] = nil
}
}
} else if terminal.Proxy != "" {
proxys[terminal.Proxy] = nil
} else {
flag.Usage()
return
}
err := internal.RunSwitchProxy(proxys, terminal)
if err != nil {
log.Fatal(err)
}
}
|
[
5
] |
// Package release implements versioning.
package release
import (
"errors"
"fmt"
"strconv"
"strings"
"time"
)
// New returns a release for the current year and month with a zero
// iteration counter.
func New() Release {
now := time.Now()
return Release{
Year: now.Year(),
Month: int(now.Month()),
}
}
// Release represents a release tag. They use a YYYY-MM-IT form, where
// IT is the current iteration of the package this month. Extra allows
// for additional information (such as "-dirty") in the release.
type Release struct {
Year int
Month int
Iteration int
Extra string
}
// String satisfies the Stringer interface.
func (r Release) String() string {
s := fmt.Sprintf("%04d.%d.%d", r.Year, r.Month, r.Iteration)
if r.Extra != "" {
s += "-" + r.Extra
}
return s
}
// Cmp compares two releases. It returns -1 if r is an older release
// than o, 0 if they are the same release, and 1 if r is a later
// release. If the releases are the same except for extra (which is
// typically a git hash and some other tag), there isn't a way to
// determine which release comes first, so the return value will be
// -1.
func (r Release) Cmp(o Release) int {
if r.Year < o.Year {
return -1
} else if r.Year > o.Year {
return 1
}
if r.Month < o.Month {
return -1
} else if r.Month > o.Month {
return 1
}
if r.Iteration < o.Iteration {
return -1
} else if r.Iteration > o.Iteration {
return 1
}
if r.Extra == "" {
if o.Extra != "" {
return -1
}
}
if o.Extra == "" {
if r.Extra != "" {
return 1
}
}
if r.Extra != "" && o.Extra != "" {
if r.Extra != o.Extra {
return -1
}
}
return 0
}
// Inc increments the release. If the year or month has changed,
// the iteration counter is reset. No extra tags are assigned.
func (r Release) Inc() (Release, error) {
return r.IncAt(time.Now())
}
// IncAt increments the release assuming the given timestamp. This is
// useful for verifying increments.
func (r Release) IncAt(now time.Time) (Release, error) {
year := now.Year()
month := int(now.Month())
rel := Release{
Year: r.Year,
Month: r.Month,
Iteration: r.Iteration,
Extra: r.Extra,
}
if r.Year > year {
return rel, errors.New("release: incremented release caused a regression (year)")
}
if r.Year == year && r.Month > month {
return rel, errors.New("release: incremented release caused a regression (month)")
}
if year != rel.Year {
rel.Year = year
rel.Month = month
rel.Iteration = 0
} else if month != rel.Month {
rel.Month = month
rel.Iteration = 0
} else {
rel.Iteration++
}
return rel, nil
}
// Parse takes a version string and returns a release structure.
func Parse(in string) (Release, error) {
var rel Release
parts := strings.Split(in, ".")
if len(parts) != 3 {
return rel, errors.New("release: invalid release " + in)
}
var err error
rel.Year, err = strconv.Atoi(parts[0])
if err != nil {
return rel, err
} else if rel.Year > 2038 || rel.Year < 2000 {
return rel, errors.New("release: " + parts[0] + " is an invalid year (2000 >= year <= 2038)")
}
rel.Month, err = strconv.Atoi(parts[1])
if err != nil {
return rel, err
} else if rel.Month < 1 || rel.Month > 12 {
return rel, errors.New("release: " + parts[1] + " is an invalid month (1 >= month <= 12)")
}
parts = strings.SplitN(parts[2], "-", 2)
rel.Iteration, err = strconv.Atoi(parts[0])
if err != nil {
return rel, err
}
if len(parts) == 2 {
rel.Extra = parts[1]
}
return rel, nil
}
|
[
5
] |
/***** BEGIN LICENSE BLOCK *****
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# The Initial Developer of the Original Code is the Mozilla Foundation.
# Portions created by the Initial Developer are Copyright (C) 2014-2015
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Liu Ming ([email protected])
#
# ***** END LICENSE BLOCK *****/
package heka_ftp_polling_input
import (
"archive/tar"
"compress/gzip"
"fmt"
"github.com/jlaffaye/ftp"
"github.com/mozilla-services/heka/message"
"github.com/mozilla-services/heka/pipeline"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"time"
)
type FtpPollingInput struct {
*FtpPollingInputConfig
stop chan bool
runner pipeline.InputRunner
hostname string
client *ftp.ServerConn
}
type FtpPollingInputConfig struct {
TickerInterval uint `toml:"ticker_interval"`
Repeat bool `toml:"repeat"`
RepeatMarkDir string `toml:"repeat_mark_dir"`
Suffix string `toml:"suffix"`
MaxPacket int `toml:"max_packet"`
Host string `toml:"host"`
Port int `toml:"port"`
User string `toml:"user"`
Pass string `toml:"password"`
Compress bool `toml:"compress"`
Dir string `toml:"dir"`
}
func (input *FtpPollingInput) ConfigStruct() interface{} {
return &FtpPollingInputConfig{
TickerInterval: uint(5),
Repeat: false,
MaxPacket: 1 << 15,
Port: 22,
User: "anonymous",
Pass: "anonymous",
RepeatMarkDir: "dir_polling_input_repeat_mark",
}
}
func (input *FtpPollingInput) Init(config interface{}) (err error) {
conf := config.(*FtpPollingInputConfig)
input.FtpPollingInputConfig = conf
input.stop = make(chan bool)
addr := fmt.Sprintf("%s:%d", conf.Host, conf.Port)
if input.client, err = ftp.Dial(addr); err == nil {
if err = input.client.Login(conf.User, conf.Pass); err != nil {
log.Fatalf("unable to start ftp subsytem: %v", err)
if err = input.client.ChangeDir(conf.Dir); err != nil {
log.Fatalf("unable to change ftp dir: %v", err)
}
}
} else {
log.Fatalf("unable to connect to [%s]: %v", addr, err)
}
return
}
func (input *FtpPollingInput) Stop() {
input.client.Logout()
close(input.stop)
}
func (input *FtpPollingInput) packDecorator(pack *pipeline.PipelinePack) {
pack.Message.SetType("heka.ftp.polling")
}
func (input *FtpPollingInput) Run(runner pipeline.InputRunner,
helper pipeline.PluginHelper) error {
input.runner = runner
input.hostname = helper.PipelineConfig().Hostname()
tickChan := runner.Ticker()
sRunner := runner.NewSplitterRunner("")
if !sRunner.UseMsgBytes() {
sRunner.SetPackDecorator(input.packDecorator)
}
for {
select {
case <-input.stop:
return nil
case <-tickChan:
}
runner.LogMessage("start polling from sftp")
if err := input.polling(func(f io.ReadCloser, name string) error {
return input.read(f, name, runner)
}); err != nil {
runner.LogError(err)
return nil
}
}
}
func (input *FtpPollingInput) polling(fn func(io.ReadCloser, string) error) error {
if entries, err := input.client.List("."); err == nil {
for _, entry := range entries {
if entry.Type != ftp.EntryTypeFolder && (input.FtpPollingInputConfig.Suffix == "" || strings.HasSuffix(entry.Name, input.FtpPollingInputConfig.Suffix)) {
mark := filepath.Join(input.FtpPollingInputConfig.RepeatMarkDir, input.FtpPollingInputConfig.Dir, entry.Name+".ok")
if !input.FtpPollingInputConfig.Repeat {
if _, err := os.Stat(mark); !os.IsNotExist(err) {
return fmt.Errorf("repeat file %s", entry.Name)
}
}
dir := filepath.Dir(mark)
if err = os.MkdirAll(dir, 0774); err != nil {
return fmt.Errorf("Error opening file: %s", err.Error())
} else {
if err := ioutil.WriteFile(mark, []byte(time.Now().String()), 0664); err != nil {
return err
}
}
f, err := input.client.Retr(entry.Name)
if err != nil {
return fmt.Errorf("Error opening remote file: %s", err.Error())
}
defer f.Close()
err = fn(f, entry.Name)
}
}
}
return nil
}
func (input *FtpPollingInput) read(file io.ReadCloser, name string, runner pipeline.InputRunner) (err error) {
sRunner := runner.NewSplitterRunner(name)
if !sRunner.UseMsgBytes() {
sRunner.SetPackDecorator(func(pack *pipeline.PipelinePack) {
pack.Message.SetType("heka.sftp.polling")
pack.Message.SetHostname(input.hostname)
if field, err := message.NewField("file_name", name, ""); err == nil {
pack.Message.AddField(field)
}
return
})
}
if input.FtpPollingInputConfig.Compress && input.FtpPollingInputConfig.Suffix == ".gz" {
var fileReader *gzip.Reader
if fileReader, err = gzip.NewReader(file); err == nil {
defer fileReader.Close()
tarBallReader := tar.NewReader(fileReader)
for {
if header, err := tarBallReader.Next(); err == nil {
// get the individual filename and extract to the current directory
switch header.Typeflag {
case tar.TypeReg:
split(runner, sRunner, tarBallReader)
}
} else {
break
}
}
}
} else {
split(runner, sRunner, file)
}
return
}
func split(runner pipeline.InputRunner, sRunner pipeline.SplitterRunner, reader io.Reader) {
var err error
for err == nil {
err = sRunner.SplitStream(reader, nil)
if err != io.EOF && err != nil {
runner.LogError(fmt.Errorf("Error reading file: %s", err.Error()))
}
}
}
func init() {
pipeline.RegisterPlugin("FtpPollingInput", func() interface{} {
return new(FtpPollingInput)
})
}
|
[
7
] |
package arrays
import (
"encoding/json"
"strconv"
)
// FloatArray alias type for []float64
type FloatArray []float64
// Delete deletes float element from array of floats
func (arr *FloatArray) Delete(elem float64) {
// original version got form https://yourbasic.org/golang/delete-element-slice/
var elemIndex *int
for i, e := range *arr {
if e == elem {
elemIndex = &i
break
}
}
if elemIndex != nil {
// Remove the element at index i from a.
copy((*arr)[*elemIndex:], (*arr)[*elemIndex+1:]) // Shift a[i+1:] left one index.
*arr = (*arr)[:len(*arr)-1] // Truncate slice.
}
}
// Contains checks if array of floats contains provided float
func (arr *FloatArray) Contains(elem float64) bool {
if len(*arr) == 0 {
return false
}
for _, e := range *arr {
if e == elem {
return true
}
}
return false
}
// Clear remove all elements from array of floats
func (arr *FloatArray) Clear() {
newArr := *arr
*arr = newArr[:0]
}
// Collect return new array contained values returned by the provided function
func (arr *FloatArray) Collect(exec func(el float64) float64) []float64 {
newArr := make([]float64, 0, 0)
for _, e := range *arr {
newArr = append(newArr, exec(e))
}
return newArr
}
// Concat append elements of other arrays to self
func (arr *FloatArray) Concat(arrays ...[]float64) {
if len(arrays) == 0 {
return
}
for _, a := range arrays {
*arr = append(*arr, a...)
}
}
// Index return index of first matched float in array if not found return nil
func (arr *FloatArray) Index(elem float64) *int {
if len(*arr) == 0 {
return nil
}
for i, el := range *arr {
if el == elem {
return &i
}
}
return nil
}
// Map return new array contained values returned by the provided function
func (arr *FloatArray) Map(exec func(el float64) float64) []float64 {
return arr.Collect(exec)
}
// Min return min float64
func (arr *FloatArray) Min() *float64 {
if len(*arr) == 0 {
return nil
}
newArr := []float64(*arr)
var min = newArr[0]
for _, el := range newArr {
if el < min {
min = el
}
}
return &min
}
// Max return max int
func (arr *FloatArray) Max() *float64 {
if len(*arr) == 0 {
return nil
}
newArr := []float64(*arr)
var max = newArr[0]
for _, el := range newArr {
if el > max {
max = el
}
}
return &max
}
// Pop removes last element from array and returns it
func (arr *FloatArray) Pop(args ...int) *float64 {
if len(*arr) == 0 {
return nil
}
n := 1
var last float64
var newArr []float64
if len(args) > 0 {
n = args[0]
if len(*arr) < n {
return nil
}
}
for i := 0; i < n; i++ {
newArr = []float64(*arr)
last = newArr[len(newArr)-1]
arr.Delete(last)
}
return &last
}
// Push append element to array
func (arr *FloatArray) Push(elem float64) {
*arr = append(*arr, elem)
}
// Select returns a new array containing all elements of array for which the given block returns true
func (arr *FloatArray) Select(exec func(str float64) bool) []float64 {
if len(*arr) == 0 {
return []float64{}
}
resArr := make([]float64, 0, 0)
for _, el := range *arr {
if exec(el) {
resArr = append(resArr, el)
}
}
return resArr
}
// Uniq removes duplicated elements form given array
func (arr *FloatArray) Uniq() {
if len(*arr) == 0 {
return
}
strMap := make(map[float64]int)
for _, el := range *arr {
// value doesn't matter here cause we collect just keys
strMap[el] = 1
}
resArr := make([]float64, 0, 0)
for k := range strMap {
resArr = append(resArr, k)
}
*arr = resArr
}
// ToStringArray implements Convertible for converting to string array
func (arr *FloatArray) ToStringArray() (*[]string, error) {
newArr := make([]string, 0, 0)
for _, el := range *arr {
newArr = append(newArr, strconv.FormatFloat(el, 'f', -1, 64))
}
return &newArr, nil
}
// ToFloat64Array implements Convertible for converting to float32 array
func (arr *FloatArray) ToFloat64Array() (*[]float64, error) {
newArr := []float64(*arr)
return &newArr, nil
}
// ToFloat32Array implements Convertible for converting to float32 array
func (arr *FloatArray) ToFloat32Array() (*[]float32, error) {
newArr := make([]float32, 0, 0)
for _, el := range *arr {
newArr = append(newArr, float32(el))
}
return &newArr, nil
}
// ToInt64Array implements Convertible for converting to int64 array
func (arr *FloatArray) ToInt64Array() (*[]int64, error) {
newArr := make([]int64, 0, 0)
for _, el := range *arr {
newArr = append(newArr, int64(el))
}
return &newArr, nil
}
// ToInt32Array implements Convertible for converting to int32 array
func (arr *FloatArray) ToInt32Array() (*[]int32, error) {
newArr := make([]int32, 0, 0)
for _, el := range *arr {
newArr = append(newArr, int32(el))
}
return &newArr, nil
}
// ToUintArray implements Convertible for converting to uint array
func (arr *FloatArray) ToUintArray() (*[]uint, error) {
newArr := make([]uint, 0, 0)
for _, el := range *arr {
newArr = append(newArr, uint(el))
}
return &newArr, nil
}
// ToUint32Array implements Convertible for converting to uint32 array
func (arr *FloatArray) ToUint32Array() (*[]uint32, error) {
newArr := make([]uint32, 0, 0)
for _, el := range *arr {
newArr = append(newArr, uint32(el))
}
return &newArr, nil
}
// ToUint64Array implements Convertible for converting to uint64 array
func (arr *FloatArray) ToUint64Array() (*[]uint64, error) {
newArr := make([]uint64, 0, 0)
for _, el := range *arr {
newArr = append(newArr, uint64(el))
}
return &newArr, nil
}
// ToJSON implements Convertible for converting to json string
func (arr *FloatArray) ToJSON() (string, error) {
data, err := json.Marshal(*arr)
if err != nil {
return "", err
}
return string(data), nil
}
|
[
1
] |
package match
type Matches []Match
func (s Matches)Len() int {
return len(s)
}
func (s Matches)Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s Matches) Less(i, j int) bool {
if s[i].I < s[j].I {
return true
} else if s[i].I == s[j].I {
return s[i].J < s[j].J
} else {
return false
}
}
type Match struct {
Pattern string
I, J int
Token string
MatchedWord string
Rank float64
DictionaryName string
DictionaryLength int
Ascending bool
Turns int
ShiftedCount int
Entropy float64
RepeatedChar string
}
type DateMatch struct {
Pattern string
I, J int
Token string
Separator string
Day, Month, Year int64
}
|
[
5
] |
package main
import (
"bufio"
debug "log"
"io"
"fmt"
"os"
"./night"
"sort"
)
func check(err error) {
if err != nil {
panic(err)
}
}
func main() {
debug.SetFlags(0)
debug.SetPrefix("debug: ")
answer, err := solve(newValReader(os.Stdin))
if err != nil {
panic(err)
}
fmt.Println(answer)
}
func solve(reader valReader) (answer int, outErr error) {
lines := make([]string, 0)
for v := range reader.Vals() {
lines = append(lines, v)
// debug.Println(v)
}
sort.Strings(lines)
// sleepPatterns[guard_id][min] is the number of times
// that guard was asleep at that minute
sleepPatterns := make(map[int][]int)
for state := range night.StateGenerator(lines) {
// debug.Printf("%#v\n", state)
if state.Asleep {
if sleepPatterns[state.Guard] == nil {
sleepPatterns[state.Guard] = make([]int, 60)
}
sleepPatterns[state.Guard][state.Time] += 1
}
}
debugPatterns(sleepPatterns)
guard, max := argmaxPatterns(
func(pat []int) int {
_, numTimes := argmaxInt(pat)
return numTimes
},
sleepPatterns,
)
minute, _ := argmaxInt(sleepPatterns[guard])
debug.Printf("Guard #%d was asleep %d times during minute %d\n", guard, max, minute)
answer = guard*minute
return
}
func sum(a []int) int {
res := 0
for _, e := range a {
res += e
}
return res
}
func debugPatterns(pats map[int][]int) {
fmt.Println(" ID | Minute")
fmt.Println(" | 000000000011111111112222222222333333333344444444445555555555")
fmt.Println(" | 012345678901234567890123456789012345678901234567890123456789")
fmt.Println("-----------------------------------------------------------------------")
for id, arr := range pats {
fmt.Printf(" #%6d | ", id)
for _, sleepCount := range arr {
if sleepCount >= 20 {
fmt.Printf("x")
} else if sleepCount >= 10 {
fmt.Printf("%d", sleepCount-10)
} else {
fmt.Printf("-")
}
}
fmt.Printf("\n")
}
fmt.Println()
}
func argmaxPatterns(proj func([]int) int, m map[int][]int) (arg, max int) {
if len(m) == 0 {
panic("empty array")
}
arg = 0
max = 0 // hacky; not mathematically correct
for k, v := range m {
p := proj(v)
if proj(v) > max {
arg = k
max = p
}
}
if arg == 0 {
panic("probably need to rewrite argmax to play nice")
}
return
}
func argmaxInt(arr []int) (arg, max int) {
if len(arr) == 0 {
panic("empty array")
}
arg = 0
max = 0 // hacky; not mathematically correct
for k, v := range arr {
if v > max {
arg = k
max = v
}
}
if arg == 0 {
panic("probably need to rewrite argmaxInt to play nice")
}
return
}
func maxInt(a []int) (max int) {
if len(a) == 0 {
panic("empty array")
}
max = 0 // hacky; not mathematically correct
for _, e := range a {
if e > max {
max = e
}
}
if max == 0 {
panic("probably need to rewrite argmax to play nice")
}
return
}
// valReader converts an `io.Reader` to a `chan string`
// usage:
// reader := newValReader(os.Stdin)
// for val := reader.Vals() {
// _ = val
// }
// if reader.Err() != nil {
// panic(err)
// }
type valReader struct {
in io.Reader
out chan string
err error
}
func newValReader(in io.Reader) valReader {
out := make(chan string)
return valReader{
in: in,
out: out,
}
}
func (r *valReader) Vals() chan string {
go func() {
scanner := bufio.NewScanner(r.in)
for scanner.Scan() {
r.out <- scanner.Text()
}
if r.check(scanner.Err()) {
return
}
close(r.out)
}()
return r.out
}
func (r *valReader) Err() error {
return r.err
}
func (r *valReader) check(err error) bool {
if err != nil {
r.err = err
close(r.out)
return true
}
return false
}
|
[
1,
5
] |
package main
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param base double浮点型
* @param exponent int整型
* @return double浮点型
*/
// https://www.nowcoder.com/practice/1a834e5e3e1a4b7ba251417554e07c00?tpId=13&tqId=11165&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking
func Power(base float64, exponent int) float64 {
result := float64(1)
div := exponent < 0
if exponent < 0 {
exponent = -exponent
}
for i := 0; i < exponent; i++ {
result = result * base
}
if div {
result = 1 / result
}
return result
}
|
[
0
] |
package json2neo
import (
"fmt"
"github.com/johnnadratowski/golang-neo4j-bolt-driver"
"strings"
)
//TODO:: bejaye inhame param ye struct begiram
/*
DeleteBulkNodes deletes J2N generated node-tree(s) using stub and root information
*/
func DeleteBulkNodes(neoConn golangNeo4jBoltDriver.Conn, stubNodeID int64, rootNodeLabel, rootNodeName string, exceptNodeID int64) (golangNeo4jBoltDriver.Result, error) {
var cypher = `MATCH %s(root%s) WHERE %s AND %v AND %s
OPTIONAL MATCH (root)-[*..]->(leaf)
DETACH DELETE root,leaf`
var label, name, id, preID, except string
if rootNodeLabel != "" {
label = ":" + strings.ToUpper(rootNodeLabel)
}
if stubNodeID != -1 {
preID = fmt.Sprintf("(stub)-[rel%s]->", label)
id = fmt.Sprintf("ID(stub) = %d", stubNodeID)
} else {
id = ValueTrue
}
if rootNodeName != "" {
name = fmt.Sprintf("root.%s =~ '(?i)%s'", RootNameKey, rootNodeName)
} else {
name = ValueTrue
}
if exceptNodeID != -1 {
except = fmt.Sprintf("ID(root) <> %v", exceptNodeID)
}
cypher = fmt.Sprintf(cypher,
preID,
label,
id,
name,
except,
)
return neoConn.ExecNeo(cypher, map[string]interface{}{})
}
/*
FindRootIDByFields finds root nodeID using root node information
*/
func FindRootIDByFields(neoConn golangNeo4jBoltDriver.Conn, rootNodeLabel, rootNodeName string, conditions map[string]interface{}) (int64, error) {
var cypher = `MATCH (root%s)-[*..]->(leaf)
WHERE %s AND
%s
RETURN DISTINCT ID(root)`
var conditionsCypherStub = "(root.%s =~ '%v' or leaf.%s =~ '%v') AND "
var label, name, conditionsCypher string
if rootNodeLabel != "" {
label = ":" + strings.ToUpper(rootNodeLabel)
}
if rootNodeName != "" {
name = fmt.Sprintf("root.%s =~ '(?i)%s'", RootNameKey, rootNodeName)
} else {
name = ValueTrue
}
for key, value := range conditions {
switch value.(type) {
case string:
value = "(?i)" + value.(string)
}
conditionsCypher += fmt.Sprintf(conditionsCypherStub, key, value, key, value)
}
conditionsCypher += ValueTrue
cypher = fmt.Sprintf(cypher,
label,
name,
conditionsCypher,
)
res, _, _, err := neoConn.QueryNeoAll(cypher, conditions)
if err != nil {
panic(err)
}
if len(res) == 0 {
panic("node_not_found")
} else if len(res) > 1 {
panic("multiple_root_nodes_found")
} else {
return res[0][0].(int64), err
}
}
func firstPlace(s []interface{}, i interface{}) int {
for index, value := range s {
if value == i {
return index
}
}
return -1
}
|
[
5,
7
] |
// Package ultrapool implements a blazing fast worker pool with adaptive
// spawning of new workers and cleanup of idle workers
// It was modeled after valyala/fasthttp's worker pool which is one of the
// best worker pools I've seen in the Go world.
// Copyright 2019-2023 Moritz Fain
// Moritz Fain <[email protected]>
//
// Source available at github.com/maurice2k/ultrapool,
// licensed under the MIT license (see LICENSE file).
package ultrapool
import (
"errors"
"runtime"
"sync"
"sync/atomic"
"time"
"unsafe"
)
type TaskHandlerFunc[T any] func(task T)
type WorkerPool[T any] struct {
handlerFunc TaskHandlerFunc[T]
idleWorkerLifetime time.Duration
numShards int
shards []*poolShard[T]
mutex spinLocker
started bool
stopped bool
_ [56]byte
spawnedWorkers uint64
}
type workerInstance[T any] struct {
taskChan chan T
shard *poolShard[T]
lastUsed time.Time
isDeleted bool
_ [16]byte
}
type poolShard[T any] struct {
wp *WorkerPool[T]
workerCache sync.Pool
idleWorkerList []*workerInstance[T]
idleWorker1 *workerInstance[T]
idleWorker2 *workerInstance[T]
mutex spinLocker
stopped bool
}
const defaultIdleWorkerLifetime = time.Second
const maxShards = 128
// Creates a new workerInstance pool with the given task handling function
func NewWorkerPool[T any](handlerFunc TaskHandlerFunc[T]) *WorkerPool[T] {
wp := &WorkerPool[T]{
handlerFunc: handlerFunc,
idleWorkerLifetime: defaultIdleWorkerLifetime,
numShards: 1,
}
wp.SetNumShards(runtime.GOMAXPROCS(0))
return wp
}
// Sets number of shards (default is GOMAXPROCS shards)
func (wp *WorkerPool[T]) SetNumShards(numShards int) {
if numShards <= 1 {
numShards = 1
}
if numShards > maxShards {
numShards = maxShards
}
wp.numShards = numShards
}
// Sets the time after which idling workers are shut down (default is 15 seconds)
func (wp *WorkerPool[T]) SetIdleWorkerLifetime(d time.Duration) {
wp.idleWorkerLifetime = d
}
// Returns the number of currently spawned workers
func (wp *WorkerPool[T]) GetSpawnedWorkers() int {
return int(atomic.LoadUint64(&wp.spawnedWorkers))
}
// Starts the worker pool
func (wp *WorkerPool[T]) Start() {
wp.mutex.Lock()
if !wp.started {
for i := 0; i < wp.numShards; i++ {
shard := &poolShard[T]{
wp: wp,
workerCache: sync.Pool{
New: func() interface{} {
return &workerInstance[T]{
taskChan: make(chan T),
}
},
},
idleWorkerList: make([]*workerInstance[T], 0, 2048),
}
wp.shards = append(wp.shards, shard)
}
wp.started = true
}
wp.mutex.Unlock()
go wp.cleanup()
}
// Stops the worker pool.
// All tasks that have been added will be processed before shutdown.
func (wp *WorkerPool[T]) Stop() {
wp.mutex.Lock()
if !wp.started {
wp.mutex.Unlock()
return
}
if !wp.stopped {
for i := 0; i < wp.numShards; i++ {
shard := wp.shards[i]
shard.mutex.Lock()
shard.stopped = true
for j := 0; j < len(shard.idleWorkerList); j++ {
if !shard.idleWorkerList[j].isDeleted {
shard.idleWorkerList[j].isDeleted = true
close(shard.idleWorkerList[j].taskChan)
}
}
shard.mutex.Unlock()
}
}
wp.stopped = true
wp.mutex.Unlock()
}
// Adds a new task
func (wp *WorkerPool[T]) AddTask(task T) error {
if !wp.started {
return errors.New("worker pool must be started first")
}
shard := wp.shards[randInt()%wp.numShards]
shard.getWorker(task)
return nil
}
// Adds a new task
func (wp *WorkerPool[T]) AddTaskForShard(task T, shardIdx int) error {
if !wp.started {
return errors.New("worker pool must be started first")
}
shard := wp.shards[shardIdx%wp.numShards]
shard.getWorker(task)
return nil
}
// Returns next free worker or spawns a new worker
func (shard *poolShard[T]) getWorker(task T) (worker *workerInstance[T]) {
worker = shard.idleWorker1
if worker != nil && atomic.CompareAndSwapPointer((*unsafe.Pointer)(unsafe.Pointer(&shard.idleWorker1)), unsafe.Pointer(worker), nil) {
worker.taskChan <- task
return worker
}
worker = shard.idleWorker2
if worker != nil && atomic.CompareAndSwapPointer((*unsafe.Pointer)(unsafe.Pointer(&shard.idleWorker2)), unsafe.Pointer(worker), nil) {
worker.taskChan <- task
return worker
}
shard.mutex.Lock()
iws := len(shard.idleWorkerList)
if iws > 0 {
worker = shard.idleWorkerList[iws-1]
shard.idleWorkerList[iws-1] = nil
shard.idleWorkerList = shard.idleWorkerList[0 : iws-1]
shard.mutex.Unlock()
worker.taskChan <- task
return worker
}
shard.mutex.Unlock()
worker = shard.workerCache.Get().(*workerInstance[T])
worker.shard = shard
go worker.run()
worker.taskChan <- task
return worker
}
// Main worker runner
func (worker *workerInstance[T]) run() {
shard := worker.shard
wp := shard.wp
atomic.AddUint64(&wp.spawnedWorkers, +1)
for task := range worker.taskChan {
wp.handlerFunc(task)
if !shard.setWorkerIdle(worker) {
break
}
}
atomic.AddUint64(&wp.spawnedWorkers, ^uint64(0))
shard.workerCache.Put(worker)
}
// Mark worker as idle
func (shard *poolShard[T]) setWorkerIdle(worker *workerInstance[T]) bool {
worker.lastUsed = time.Now()
if shard.idleWorker2 == nil && atomic.CompareAndSwapPointer((*unsafe.Pointer)(unsafe.Pointer(&shard.idleWorker2)), nil, unsafe.Pointer(worker)) {
return true
}
if shard.idleWorker1 == nil && atomic.CompareAndSwapPointer((*unsafe.Pointer)(unsafe.Pointer(&shard.idleWorker1)), nil, unsafe.Pointer(worker)) {
return true
}
worker.shard.mutex.Lock()
if !worker.shard.stopped {
worker.shard.idleWorkerList = append(worker.shard.idleWorkerList, worker)
}
worker.shard.mutex.Unlock()
return !worker.shard.stopped
}
// Worker cleanup
func (wp *WorkerPool[T]) cleanup() {
var toBeCleaned []*workerInstance[T]
for {
time.Sleep(wp.idleWorkerLifetime)
if wp.stopped {
return
}
now := time.Now()
for i := 0; i < wp.numShards; i++ {
shard := wp.shards[i]
shard.mutex.Lock()
idleWorkerList := shard.idleWorkerList
iws := len(idleWorkerList)
j := 0
s := 0
if iws > 400 {
s = (iws - 1) / 2
for s > 0 && now.Sub(idleWorkerList[s].lastUsed) < wp.idleWorkerLifetime {
s = s / 2
}
if s == 0 {
shard.mutex.Unlock()
continue
}
}
for j = s; j < iws; j++ {
if now.Sub(idleWorkerList[s].lastUsed) < wp.idleWorkerLifetime {
break
}
}
if j == 0 {
shard.mutex.Unlock()
continue
}
toBeCleaned = append(toBeCleaned[:0], idleWorkerList[0:j]...)
numMoved := copy(idleWorkerList, idleWorkerList[j:])
for j = numMoved; j < iws; j++ {
idleWorkerList[j] = nil
}
shard.idleWorkerList = idleWorkerList[:numMoved]
shard.mutex.Unlock()
for j = 0; j < len(toBeCleaned); j++ {
if !toBeCleaned[j].shard.stopped {
close(toBeCleaned[j].taskChan)
}
toBeCleaned[j] = nil
}
}
}
}
// Spin locker
type spinLocker struct {
lock uint64
}
func (s *spinLocker) Lock() {
schedulerRuns := 1
for !atomic.CompareAndSwapUint64(&s.lock, 0, 1) {
for i := 0; i < schedulerRuns; i++ {
runtime.Gosched()
}
if schedulerRuns < 32 {
schedulerRuns <<= 1
}
}
}
func (s *spinLocker) Unlock() {
atomic.StoreUint64(&s.lock, 0)
}
// SplitMix64 style random pseudo number generator
type splitMix64 struct {
state uint64
}
// Initialize SplitMix64
func (sm64 *splitMix64) Init(seed int64) {
sm64.state = uint64(seed)
}
// Uint64 returns the next SplitMix64 pseudo-random number as a uint64
func (sm64 *splitMix64) Uint64() uint64 {
sm64.state = sm64.state + uint64(0x9E3779B97F4A7C15)
z := sm64.state
z = (z ^ (z >> 30)) * uint64(0xBF58476D1CE4E5B9)
z = (z ^ (z >> 27)) * uint64(0x94D049BB133111EB)
return z ^ (z >> 31)
}
// Int63 returns a non-negative pseudo-random 63-bit integer as an int64
func (sm64 *splitMix64) Int63() int64 {
return int64(sm64.Uint64() & (1<<63 - 1))
}
var splitMix64Pool sync.Pool = sync.Pool{
New: func() interface{} {
sm64 := &splitMix64{}
sm64.Init(time.Now().UnixNano())
return sm64
},
}
func randInt() (r int) {
sm64 := splitMix64Pool.Get().(*splitMix64)
r = int(sm64.Int63())
splitMix64Pool.Put(sm64)
return
}
|
[
0
] |
package dfsandbfs
/*
Company: Two Sigma(18), Pocket Gems(13), Twitter(7), Amazon(6), Google(2)
There are N students in a class. Some of them are friends, while some are not.
Their friendship is transitive in nature. For example, if A is a direct friend
of B, and B is a direct friend of C, then A is an indirect friend of C.
We defined a friend circle is a group of students who are direct or indirect friends.
Given a N*N matrix M representing the friend relationship between students in the class.
If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not.
And you have to output the total number of friend circles among all the students.
Example 1:
Input:
[[1,1,0],
[1,1,0],
[0,0,1]]
Output: 2
Explanation:The 0th and 1st students are direct friends, so they are in a friend circle.
The 2nd student himself is in a friend circle. So return 2.
Example 2:
Input:
[[1,1,0],
[1,1,1],
[0,1,1]]
Output: 1
Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends,
so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1.
Note:
N is in range [1,200].
M[i][i] = 1 for all students.
If M[i][j] = 1, then M[j][i] = 1.
*/
func findCircleNum547(M [][]int) int {
// the total number of students is the length of M
// we create a slice to store person have been visited
visitedPerson := make([]int, len(M))
res := 0
// we find all the direct and indirect friends of person i that has NOT been visited
for i := range M {
if visitedPerson[i] == 0 {
helper547(i, visitedPerson, M)
res++
}
}
return res
}
// DFS
func helper547(i int, visited []int, M [][]int) {
for j := range M {
if M[i][j] == 1 && visited[j] == 0 {
visited[j] = 1
helper547(j, visited, M)
}
}
}
|
[
2
] |
// Copyright 2020 The Dot Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"math"
"math/rand"
)
const Stride = 1024 * 1024
func getVector32() []float32 {
vector := make([]float32, 1024*1024*256)
for i := range vector {
vector[i] = rand.Float32()
}
return vector
}
func getVector16() []uint16 {
vector := make([]uint16, 1024*1024*256)
for i := range vector {
bits := math.Float32bits(rand.Float32())
vector[i] = uint16(bits >> 16)
}
return vector
}
func convert(aa []float32, a []uint16) {
for j, value := range a {
aa[j] = math.Float32frombits(uint32(value) << 16)
}
}
func vmdot16(a, b []uint16) float32 {
var sum float32
done := make(chan float32, 16)
aaa, bbb := make(chan []float32, 16), make(chan []float32, 16)
for i := 0; i < 16; i++ {
aaa <- make([]float32, Stride)
bbb <- make([]float32, Stride)
}
process := func(i int) {
aa, bb := <-aaa, <-bbb
end := i + Stride
convert(aa, a[i:end])
convert(bb, b[i:end])
aaa <- aa
bbb <- bb
done <- dot32(aa, bb)
}
flight, i := 0, 0
for i < len(a) && flight < 16 {
go process(i)
i += Stride
flight++
}
for i < len(a) {
sum += <-done
flight--
go process(i)
i += Stride
flight++
}
for i := 0; i < flight; i++ {
sum += <-done
}
return sum
}
func mdot16(a, b []uint16) float32 {
var sum float32
done := make(chan float32, 16)
process := func(i int) {
end := i + Stride
done <- dot16(a[i:end], b[i:end])
}
flight, i := 0, 0
for i < len(a) && flight < 16 {
go process(i)
i += Stride
flight++
}
for i < len(a) {
sum += <-done
flight--
go process(i)
i += Stride
flight++
}
for i := 0; i < flight; i++ {
sum += <-done
}
return sum
}
func dot16(a, b []uint16) float32 {
var sum float32
for i, value := range a {
x := math.Float32frombits(uint32(value) << 16)
y := math.Float32frombits(uint32(b[i]) << 16)
sum += x * y
}
return sum
}
func vmdot32(a, b []float32) float32 {
var sum float32
done := make(chan float32, 16)
process := func(i int) {
end := i + Stride
done <- dot32(a[i:end], b[i:end])
}
flight, i := 0, 0
for i < len(a) && flight < 16 {
go process(i)
i += Stride
flight++
}
for i < len(a) {
sum += <-done
flight--
go process(i)
i += Stride
flight++
}
for i := 0; i < flight; i++ {
sum += <-done
}
return sum
}
func _dot32(X, Y []float32) float32 {
var sum float32
for i, x := range X {
sum += x * Y[i]
}
return sum
}
func main() {
a, b := getVector16(), getVector16()
fmt.Println(vmdot16(a, b))
}
|
[
2
] |
package wechat
import (
"encoding/xml"
"io"
)
type MsgType string
const (
MsgText MsgType = "text"
MsgImage = "image"
MsgVoice = "voice"
MsgVideo = "video"
MsgLocation = "location"
MsgLink = "link"
MsgEvent = "event"
)
type MessageHeader struct {
MsgId string
MsgType MsgType
ToUserName string
FromUserName string
CreateTime int64
}
func (h MessageHeader) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
helper := encodeElementHelper{e, nil}
start.Name.Local = "ToUserName"
helper.Encode(start, xml.CharData(h.ToUserName))
start.Name.Local = "FromUserName"
helper.Encode(start, xml.CharData(h.FromUserName))
start.Name.Local = "CreateTime"
helper.Encode(start, h.CreateTime)
start.Name.Local = "MsgType"
helper.Encode(start, xml.CharData(h.MsgType))
return helper.Error()
}
type Message struct {
MessageHeader
Content string
PicUrl string
MediaId string
Format string
ThumbMediaId string
LocationX float64 `xml:"Location_X"`
LocationY float64 `xml:"Location_Y"`
Scale float64
Label string
Event EventType
EventKey string
Ticket string
Latitude float64
Longitude float64
Precision float64
}
func ParseMessage(r io.Reader) (Message, error) {
decoder := xml.NewDecoder(r)
var ret Message
err := decoder.Decode(&ret)
return ret, err
}
func (msg Message) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
if err := msg.MessageHeader.MarshalXML(e, start); err != nil {
return err
}
helper := encodeElementHelper{e, nil}
switch msg.MsgType {
case MsgText:
start.Name.Local = "Content"
helper.Encode(start, xml.CharData(msg.Content))
}
return helper.Error()
}
type encodeElementHelper struct {
e *xml.Encoder
err error
}
func (e *encodeElementHelper) Encode(start xml.StartElement, v interface{}) {
if e.err != nil {
return
}
e.err = e.e.EncodeElement(v, start)
}
func (e *encodeElementHelper) Error() error {
return e.err
}
|
[
7
] |
package proxy
import (
"fmt"
"github.com/HYmian/jhs/router"
)
type Schema struct {
db string
nodes map[string]*Node
rule *router.Router
}
func (s *Server) parseRules() error {
s.rules = make(map[string]*router.Rule)
for _, c := range s.cfg.ShardRule {
r := new(router.Rule)
r.Table = c.Table
r.Key = c.Key
r.Type = c.Type
r.Nodes = c.Nodes
if r.Type == router.HashRuleType {
r.Shard = &router.JHSHashShard{NodeShardNum: len(r.Nodes), TableShardNum: c.ShardNum}
} else if r.Type == router.RangeRuleType {
rs, err := router.ParseNumShardingSpec(c.Range)
if err != nil {
return err
}
if len(rs) != len(r.Nodes) {
return fmt.Errorf("range space %d not equal nodes %d", len(rs), len(r.Nodes))
}
} else {
r.Type = router.NoneRuleType
}
s.rules[r.Table] = r
}
return nil
}
|
[
5
] |
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package armasm
import (
"bytes"
"fmt"
"strings"
)
var saveDot = strings.NewReplacer(
".F16", "_dot_F16",
".F32", "_dot_F32",
".F64", "_dot_F64",
".S32", "_dot_S32",
".U32", "_dot_U32",
".FXS", "_dot_S",
".FXU", "_dot_U",
".32", "_dot_32",
)
// GNUSyntax returns the GNU assembler syntax for the instruction, as defined by GNU binutils.
// This form typically matches the syntax defined in the ARM Reference Manual.
func GNUSyntax(inst Inst) string {
var buf bytes.Buffer
op := inst.Op.String()
op = saveDot.Replace(op)
op = strings.Replace(op, ".", "", -1)
op = strings.Replace(op, "_dot_", ".", -1)
op = strings.ToLower(op)
buf.WriteString(op)
sep := " "
for i, arg := range inst.Args {
if arg == nil {
break
}
text := gnuArg(&inst, i, arg)
if text == "" {
continue
}
buf.WriteString(sep)
sep = ", "
buf.WriteString(text)
}
return buf.String()
}
func gnuArg(inst *Inst, argIndex int, arg Arg) string {
switch inst.Op &^ 15 {
case LDRD_EQ, LDREXD_EQ, STRD_EQ:
if argIndex == 1 {
// second argument in consecutive pair not printed
return ""
}
case STREXD_EQ:
if argIndex == 2 {
// second argument in consecutive pair not printed
return ""
}
}
switch arg := arg.(type) {
case Imm:
switch inst.Op &^ 15 {
case BKPT_EQ:
return fmt.Sprintf("%#04x", uint32(arg))
case SVC_EQ:
return fmt.Sprintf("%#08x", uint32(arg))
}
return fmt.Sprintf("#%d", int32(arg))
case ImmAlt:
return fmt.Sprintf("#%d, %d", arg.Val, arg.Rot)
case Mem:
R := gnuArg(inst, -1, arg.Base)
X := ""
if arg.Sign != 0 {
X = ""
if arg.Sign < 0 {
X = "-"
}
X += gnuArg(inst, -1, arg.Index)
if arg.Shift == ShiftLeft && arg.Count == 0 {
// nothing
} else if arg.Shift == RotateRightExt {
X += ", rrx"
} else {
X += fmt.Sprintf(", %s #%d", strings.ToLower(arg.Shift.String()), arg.Count)
}
} else {
X = fmt.Sprintf("#%d", arg.Offset)
}
switch arg.Mode {
case AddrOffset:
if X == "#0" {
return fmt.Sprintf("[%s]", R)
}
return fmt.Sprintf("[%s, %s]", R, X)
case AddrPreIndex:
return fmt.Sprintf("[%s, %s]!", R, X)
case AddrPostIndex:
return fmt.Sprintf("[%s], %s", R, X)
case AddrLDM:
if X == "#0" {
return R
}
case AddrLDM_WB:
if X == "#0" {
return R + "!"
}
}
return fmt.Sprintf("[%s Mode(%d) %s]", R, int(arg.Mode), X)
case PCRel:
return fmt.Sprintf(".%+#x", int32(arg)+4)
case Reg:
switch inst.Op &^ 15 {
case LDREX_EQ:
if argIndex == 0 {
return fmt.Sprintf("r%d", int32(arg))
}
}
switch arg {
case R10:
return "sl"
case R11:
return "fp"
case R12:
return "ip"
}
case RegList:
var buf bytes.Buffer
fmt.Fprintf(&buf, "{")
sep := ""
for i := 0; i < 16; i++ {
if arg&(1<<uint(i)) != 0 {
fmt.Fprintf(&buf, "%s%s", sep, gnuArg(inst, -1, Reg(i)))
sep = ", "
}
}
fmt.Fprintf(&buf, "}")
return buf.String()
case RegShift:
if arg.Shift == ShiftLeft && arg.Count == 0 {
return gnuArg(inst, -1, arg.Reg)
}
if arg.Shift == RotateRightExt {
return gnuArg(inst, -1, arg.Reg) + ", rrx"
}
return fmt.Sprintf("%s, %s #%d", gnuArg(inst, -1, arg.Reg), strings.ToLower(arg.Shift.String()), arg.Count)
case RegShiftReg:
return fmt.Sprintf("%s, %s %s", gnuArg(inst, -1, arg.Reg), strings.ToLower(arg.Shift.String()), gnuArg(inst, -1, arg.RegCount))
}
return strings.ToLower(arg.String())
}
|
[
5,
7
] |
package service
import (
"github.com/nairufan/yh-share/db/mongo"
"github.com/nairufan/yh-share/model"
)
const (
SequenceId = "document"
collectionSequence = "sequence"
)
func Increase() int64 {
session := mongo.Get()
defer session.Close()
sequence := &model.Sequence{}
if err := session.FindId(collectionSequence, SequenceId, sequence); err != nil {
sequence.Id = SequenceId
sequence.Value = 1
session.MustInsert(collectionSequence, sequence)
} else {
sequence.Value = sequence.Value + 1
session.MustUpdateId(collectionSequence, SequenceId, sequence)
}
return sequence.Value
}
|
[
0
] |
package main
import (
"fmt"
)
/*
你有50枚金币,需要分配给以下几个人:Matthew,Sarah,Augustus,Heidi,Emilie,Peter,Giana,Adriano,Aaron,Elizabeth。
分配规则如下:
a. 名字中每包含1个'e'或'E'分1枚金币
b. 名字中每包含1个'i'或'I'分2枚金币
c. 名字中每包含1个'o'或'O'分3枚金币
d: 名字中每包含1个'u'或'U'分4枚金币
写一个程序,计算每个用户分到多少金币,以及最后剩余多少金币?
程序结构如下,请实现 ‘dispatchCoin’ 函数
*/
var (
coins = 50
users = []string{
"Matthew", "Sarah", "Augustus", "Heidi", "Emilie", "Peter", "Giana", "Adriano", "Aaron", "Elizabeth",
}
distribution = make(map[string]int, len(users))
name = [...]string{"e", "E", "i", "I", "o", "O", "u", "U"}
)
func dispatchCoin() int {
sum := 0
for _, k := range users {
distribution[k] = 0
for _, key := range k {
key := string(rune(key))
v, _ := distribution[k]
switch key {
case name[0], name[1]:
distribution[k] = v + 1
sum = sum + 1
case name[2], name[3]:
distribution[k] = v + 2
sum = sum + 2
case name[4], name[5]:
distribution[k] = v + 3
sum = sum + 3
case name[6], name[7]:
distribution[k] = v + 4
sum = sum + 4
default:
continue
}
}
}
return coins - sum
}
func main() {
left := dispatchCoin()
fmt.Println("剩下:", left)
fmt.Println(distribution)
}
|
[
0
] |
package etcdDocumentAccessor
import (
"errors"
"github.com/monsooncommerce/etcdDocumentAccessor/etcdClientWrapper"
"golang.org/x/net/context"
)
type EtcdDocumentAccessor struct {
DocumentKey string
KeysAPI etcdClientWrapper.KeysAPIWrapper
}
func (e *EtcdDocumentAccessor) Get() (document string, err error) {
resp, err := e.KeysAPI.Get(context.Background(), e.DocumentKey, nil)
if err != nil {
return "", err
}
if resp != nil && resp.Node != nil {
return resp.Node.Value, nil
}
return "", errors.New("etcd response was nil or contained node that was nil")
}
func (e *EtcdDocumentAccessor) Set(value string) error {
resp, err := e.KeysAPI.Set(context.Background(), e.DocumentKey, value, nil)
if err != nil {
return err
}
if resp == nil || resp.Node == nil {
return errors.New("etcd response was nil or contained node that was nil")
}
return nil
}
func (e *EtcdDocumentAccessor) Watch() <-chan string {
responseChan := make(chan string, 1)
go func(responseChan chan string) {
watcher := e.KeysAPI.Watcher(e.DocumentKey, nil)
for {
resp, err := watcher.Next(context.Background())
if err != nil {
responseChan <- ""
} else if resp == nil || resp.Node == nil {
responseChan <- ""
} else {
responseChan <- resp.Node.Value
}
}
}(responseChan)
return responseChan
}
|
[
5
] |
package main
type Rows []int
func (r *Rows) GetRow(row int) int {
if len(*r) <= row {
return 0
}
return (*r)[row]
}
func (r *Rows) RowPP(row int) int {
r.size(row)
c := (*r)[row]
(*r)[row]++
return c
}
func (r *Rows) SetRow(row, col int) {
r.size(row)
(*r)[row] = col
}
func (r *Rows) size(row int) {
for len(*r) <= row {
*r = append(*r, 0)
}
}
func (r *Rows) Reset() {
*r = (*r)[:0]
}
type Box struct {
Row, Col int
}
func (b *Box) Init(row int) {
b.Row = row
b.Col = rows.RowPP(row)
}
func (b *Box) SetCol(col int) {
b.Col = col
if col >= rows.GetRow(b.Row) {
rows.SetRow(b.Row, col+1)
}
}
func (b *Box) AddCol(diff int) {
b.SetCol(b.Col + diff)
}
type Children struct {
Parents *Spouse
Children []Child
}
func (c *Children) Init(f *Family, parents *Spouse, row int) {
children := f.Children()
c.Parents = parents
c.Children = make([]Child, len(children))
for n, child := range children {
c.Children[n].Init(child, c, row)
}
if parents.Spouses != nil {
c.Shift(0)
}
}
func (c *Children) Shift(diff int) bool {
if len(c.Children) > 0 {
if pDiff := c.Parents.Col + diff - 1 - c.Children[len(c.Children)-1].LastX(); pDiff > 0 {
for i := len(c.Children) - 1; i >= 0; i-- {
if !c.Children[i].Shift(pDiff) {
return false
}
}
}
}
return true
}
func (c *Children) Draw() {
if len(c.Children) > 1 {
SiblingLine(c.Children[0].Row, c.Children[0].Col, c.Children[len(c.Children)-1].Col)
}
for _, child := range c.Children {
child.Draw()
}
}
type Child struct {
Siblings *Children
*Person
Spouses
Box
}
func (c *Child) Init(p *Person, siblings *Children, row int) {
c.Siblings = siblings
c.Person = p
c.Box.Init(row)
if p.Expand {
c.Spouses.Init(p.SpouseOf(), c, row)
}
}
func (c *Child) LastX() int {
if len(c.Spouses.Spouses) > 0 {
return c.Spouses.Spouses[len(c.Spouses.Spouses)-1].Col
}
return c.Col
}
func (c *Child) Shift(diff int) bool {
if len(c.Spouses.Spouses) > 0 {
if !c.Spouses.Shift(diff) {
return false
}
c.SetCol(c.Spouses.Spouses[0].Col - 1)
} else {
c.AddCol(diff)
}
return true
}
func (c *Child) Draw() {
SiblingUp(c.Row, c.Col)
PersonBox(c.Person, c.Row, c.Col, false)
c.Spouses.Draw()
}
type Spouses struct {
Spouse *Child
Spouses []Spouse
}
func (s *Spouses) Init(families []*Family, spouse *Child, row int) {
s.Spouse = spouse
s.Spouses = make([]Spouse, len(families))
for n, f := range families {
if spouse.Gender == 'F' {
s.Spouses[n].Init(f, f.Husband(), s, row)
} else {
s.Spouses[n].Init(f, f.Wife(), s, row)
}
}
if len(families) > 0 {
spouse.Col = s.Spouses[0].Col - 1
}
}
func (s *Spouses) Shift(diff int) bool {
for i := len(s.Spouses) - 1; i >= 0; i-- {
if !s.Spouses[i].Shift(diff) {
return false
}
}
return true
}
func (s *Spouses) Draw() {
if len(s.Spouses) > 0 {
Marriage(s.Spouse.Row, s.Spouse.Col, s.Spouses[len(s.Spouses)-1].Col)
for _, spouse := range s.Spouses {
spouse.Draw()
}
}
}
type Spouse struct {
Spouses *Spouses
*Person
Children
Box
}
func (s *Spouse) Init(f *Family, p *Person, spouses *Spouses, row int) {
s.Spouses = spouses
s.Person = p
s.Box.Init(row)
s.Children.Init(f, s, row+1)
if len(f.ChildrenIDs) > 0 {
firstChildPos := s.Children.Children[0].Col
if s.Col < firstChildPos {
s.SetCol(firstChildPos)
}
}
}
func (s *Spouse) Shift(diff int) bool {
all := true
if len(s.Children.Children) > 0 {
all = s.Children.Shift(diff)
}
s.AddCol(diff)
return all
}
func (s *Spouse) Draw() {
PersonBox(s.Person, s.Row, s.Col, true)
if len(s.Children.Children) > 0 {
if s.Col == s.Children.Children[0].Col {
DownRight(s.Row, s.Col)
} else if s.Col > s.Children.Children[len(s.Children.Children)-1].Col {
DownLeft(s.Row, s.Children.Children[len(s.Children.Children)-1].Col+1, s.Col)
} else {
DownLeft(s.Row, s.Col, s.Col)
}
s.Children.Draw()
}
}
|
[
5
] |
package fake
import "sync"
type FakeMetricSender struct {
counters map[string]uint64
values map[string]Metric
sync.RWMutex
}
type Metric struct {
Value float64
Unit string
}
func NewFakeMetricSender() *FakeMetricSender {
return &FakeMetricSender{
counters: make(map[string]uint64),
values: make(map[string]Metric),
}
}
func (fms *FakeMetricSender) SendValue(name string, value float64, unit string) error {
fms.Lock()
defer fms.Unlock()
fms.values[name] = Metric{Value: value, Unit: unit}
return nil
}
func (fms *FakeMetricSender) IncrementCounter(name string) error {
fms.Lock()
defer fms.Unlock()
fms.counters[name]++
return nil
}
func (fms *FakeMetricSender) AddToCounter(name string, delta uint64) error {
fms.Lock()
defer fms.Unlock()
fms.counters[name] = fms.counters[name] + delta
return nil
}
func (fms *FakeMetricSender) GetValue(name string) Metric {
fms.RLock()
defer fms.RUnlock()
return fms.values[name]
}
func (fms *FakeMetricSender) GetCounter(name string) uint64 {
fms.RLock()
defer fms.RUnlock()
return fms.counters[name]
}
|
[
0
] |
package lexer
import (
"blue/token"
"encoding/hex"
"strings"
)
// readChar gives us the next character and advances out position
// in the input string
func (l *Lexer) readChar() {
l.prevCh = l.ch
if l.readPos >= runeLen(l.input) {
l.ch = 0
} else {
l.ch = toRunes(l.input)[l.readPos]
}
l.pos = l.readPos
l.readPos += runeLen(string(l.ch))
}
// peekChar will return the rune that is in the readPosition without consuming any input
func (l *Lexer) peekChar() rune {
if l.readPos >= runeLen(l.input) {
return 0
}
return toRunes(l.input)[l.readPos]
}
// peekNextChar will return the rune right after the readPosition without consuming any input
func (l *Lexer) peekNextChar() rune {
if l.readPos >= runeLen(l.input) || l.readPos+1 >= runeLen(l.input) {
return 0
}
return toRunes(l.input)[l.readPos+1]
}
// readNumber will keep consuming valid digits of the input according to `isDigit`
// and return the string
// TODO: readNumber can be refactored to be cleaner
func (l *Lexer) readNumber() (token.Type, string) {
position := l.pos
if l.ch == '0' {
if l.peekChar() == 'x' && isHexChar(l.peekNextChar()) {
// consume the 0 and x and continue to the number
l.readChar()
l.readChar()
for isHexChar(l.ch) || (l.ch == '_' && isHexChar(l.peekChar())) {
l.readChar()
}
return token.HEX, string(toRunes(l.input)[position:l.pos])
} else if l.peekChar() == 'o' && isOctalChar(l.peekNextChar()) {
// consume the 0 and the o and continue to the number
l.readChar()
l.readChar()
for isOctalChar(l.ch) || (l.ch == '_' && isOctalChar(l.peekChar())) {
l.readChar()
}
return token.OCTAL, string(toRunes(l.input)[position:l.pos])
} else if l.peekChar() == 'b' && isBinaryChar(l.peekNextChar()) {
// consume the 0 and the b and continue to the number
l.readChar()
l.readChar()
for isBinaryChar(l.ch) || (l.ch == '_' && isBinaryChar(l.peekChar())) {
l.readChar()
}
return token.BINARY, string(toRunes(l.input)[position:l.pos])
}
}
dotFlag := false
for isDigit(l.ch) || (l.ch == '_' && isDigit(l.peekChar())) {
if l.peekChar() == '.' && !dotFlag && l.peekNextChar() != '.' {
dotFlag = true
l.readChar()
l.readChar()
}
l.readChar()
}
if dotFlag {
return token.FLOAT, string(toRunes(l.input)[position:l.pos])
}
return token.INT, string(toRunes(l.input)[position:l.pos])
}
// readIdentifier will keep consuming valid letters out of the input according to `isLetter`
// and return the string
func (l *Lexer) readIdentifier() string {
position := l.pos
for isLetter(l.ch) {
l.readChar()
}
return string(toRunes(l.input)[position:l.pos])
}
// readSingleLineComment will continue to consume input until the EOL is reached
func (l *Lexer) readSingleLineComment() {
for l.ch != 0 {
if l.ch == 0 {
break
}
if l.ch == '#' {
l.readChar()
for l.ch != '\n' {
l.readChar()
if l.ch == 0 {
break
}
}
break
}
l.readChar()
}
}
func (l *Lexer) readExecString() string {
b := strings.Builder{}
for {
l.readChar()
if l.ch == '`' || l.ch == 0 {
l.readChar()
break
}
b.WriteRune(l.ch)
}
return b.String()
}
func (l *Lexer) readRawString() string {
b := &strings.Builder{}
// Skip the first 2 " chars
l.readChar()
l.readChar()
for {
l.readChar()
if (l.ch == '"' && l.peekChar() == '"' && l.peekNextChar() == '"') || l.ch == 0 {
l.readChar()
l.readChar()
l.readChar()
break
}
b.WriteRune(l.ch)
}
// Skip the final part of the raw string token
// l.readChar()
return b.String()
}
// readString will consume tokens until the string is fully read
func (l *Lexer) readString() (string, error) {
b := &strings.Builder{}
for {
l.readChar()
// Support some basic escapes like \"
if l.ch == '\\' {
switch l.peekChar() {
case '"':
b.WriteByte('"')
case 'n':
b.WriteByte('\n')
case 'r':
b.WriteByte('\r')
case 't':
b.WriteByte('\t')
case '\\':
b.WriteByte('\\')
case 'x':
// Skip over the the '\\', 'x' and the next two bytes (hex)
l.readChar()
l.readChar()
l.readChar()
src := string([]rune{l.prevCh, l.ch})
dst, err := hex.DecodeString(src)
if err != nil {
return "", err
}
b.Write(dst)
continue
}
// Skip over the '\\' and the matched single escape char
l.readChar()
continue
} else {
if l.ch == '"' || l.ch == 0 {
break
}
}
b.WriteRune(l.ch)
}
return b.String(), nil
}
// skipWhitespace will continue to advance if the current byte is considered
// a whitespace character such as ' ', '\t', '\n', '\r'
func (l *Lexer) skipWhitespace() {
for l.ch == ' ' || l.ch == '\t' || l.ch == '\n' || l.ch == '\r' {
l.readChar()
}
}
// makeTwoCharToken takes a tokens type and returns the new token
// while advancing the readPosition and current char
func (l *Lexer) makeTwoCharToken(typ token.Type) token.Token {
ch := l.ch
// consume next char because we know it is an =
l.readChar()
return token.Token{Type: typ, Literal: string(ch) + string(l.ch)}
}
// makeThreeCharToken takes a tokens type and returns the new token
// while advancing the readPosition and current char to the proper position
func (l *Lexer) makeThreeCharToken(typ token.Type) token.Token {
ch := l.ch
l.readChar()
ch1 := l.ch
l.readChar()
return token.Token{Type: typ, Literal: string(ch) + string(ch1) + string(l.ch)}
}
|
[
4,
5
] |
package data_loader
import (
"archive/zip"
"encoding/json"
"fmt"
"github.com/ykhrustalev/highloadcup/models"
"github.com/ykhrustalev/highloadcup/repos"
"io"
"strings"
)
type Loader struct {
repo *repos.Repo
}
func NewLoader(repo *repos.Repo) *Loader {
return &Loader{
repo: repo,
}
}
func (l *Loader) Load(path string) error {
zf, err := zip.OpenReader(path)
if err != nil {
return err
}
defer zf.Close()
for _, file := range zf.File {
err = l.loadFile(file)
if err != nil {
return err
}
}
fmt.Printf("users: %d\n", l.repo.CountUsers())
fmt.Printf("location: %d\n", l.repo.CountLocations())
fmt.Printf("vists: %d\n", l.repo.CountVisits())
return nil
}
type UsersLoad struct {
Users []*models.User `json:"users"`
}
type LocationsLoad struct {
Locations []*models.Location `json:"locations"`
}
type VisitsLoad struct {
Visits []*models.Visit `json:"visits"`
}
func (l *Loader) loadFile(file *zip.File) error {
fc, err := file.Open()
if err != nil {
return err
}
defer fc.Close()
if strings.HasPrefix(file.Name, "users") {
l.loadUsers(fc)
fmt.Printf("load %s\n", file.Name)
} else if strings.HasPrefix(file.Name, "locations") {
l.loadLocations(fc)
fmt.Printf("load %s\n", file.Name)
} else if strings.HasPrefix(file.Name, "visits") {
l.loadVisits(fc)
fmt.Printf("load %s\n", file.Name)
}
return nil
}
func (l *Loader) loadUsers(reader io.Reader) error {
var obj UsersLoad
d := json.NewDecoder(reader)
err := d.Decode(&obj)
if err != nil {
return err
}
for _, item := range obj.Users {
l.repo.SaveUser(item)
}
return nil
}
func (l *Loader) loadLocations(reader io.Reader) error {
var obj LocationsLoad
d := json.NewDecoder(reader)
err := d.Decode(&obj)
if err != nil {
return err
}
for _, item := range obj.Locations {
l.repo.SaveLocation(item)
}
return nil
}
func (l *Loader) loadVisits(reader io.Reader) error {
var obj VisitsLoad
d := json.NewDecoder(reader)
err := d.Decode(&obj)
if err != nil {
return err
}
for _, item := range obj.Visits {
l.repo.SaveVisit(item)
}
return nil
}
|
[
5
] |
package main
import (
"fmt"
"strconv"
"strings"
"github.com/fancxxy/algo/list"
)
/*
f1(x) = 5x^2 + 4x^1 + 2
f2(x) = 5x^1 + 5
f1(x) + f2(x) = 5x^2 + 9x^1 +7
f1(x) * f2(x) = 25x^3 + 45x^2 + 30x^1 + 10
*/
type polynomial struct {
Coefficient int
Exponent int
}
func (p *polynomial) String() string {
if p.Exponent == 0 {
return strconv.Itoa(p.Coefficient)
}
return strconv.Itoa(p.Coefficient) + "x^" + strconv.Itoa(p.Exponent)
}
func addPolynomial(poly1, poly2 *list.List) *list.List {
var (
poly3 = list.New()
node1 = poly1.Front()
node2 = poly2.Front()
)
for node1 != nil && node2 != nil {
value1, value2 := node1.Value.(*polynomial), node2.Value.(*polynomial)
if value1.Exponent > value2.Exponent {
poly3.PushBack(&polynomial{
Coefficient: value1.Coefficient,
Exponent: value1.Exponent,
})
node1 = node1.Next()
} else if value1.Exponent < value2.Exponent {
poly3.PushBack(&polynomial{
Coefficient: value2.Coefficient,
Exponent: value2.Exponent,
})
node2 = node2.Next()
} else {
poly3.PushBack(&polynomial{
Coefficient: value1.Coefficient + value2.Coefficient,
Exponent: value1.Exponent,
})
node1 = node1.Next()
node2 = node2.Next()
}
}
for node1 != nil {
value1 := node1.Value.(*polynomial)
poly3.PushBack(&polynomial{
Coefficient: value1.Coefficient,
Exponent: value1.Exponent,
})
node1 = node1.Next()
}
for node2 != nil {
value2 := node2.Value.(*polynomial)
poly3.PushBack(&polynomial{
Coefficient: value2.Coefficient,
Exponent: value2.Exponent,
})
node2 = node2.Next()
}
return poly3
}
func multiplyPolynomial(poly1, poly2 *list.List) *list.List {
var (
poly3 = list.New()
node1 = poly1.Front()
node2 = poly2.Front()
)
for node1 != nil {
value1 := node1.Value.(*polynomial)
node2 = poly2.Front()
for node2 != nil {
value2 := node2.Value.(*polynomial)
poly3.PushBack(&polynomial{
Coefficient: value1.Coefficient * value2.Coefficient,
Exponent: value1.Exponent + value2.Exponent,
})
node2 = node2.Next()
}
node1 = node1.Next()
}
curr := poly3.Front()
for curr != nil && curr.Next() != nil {
currValue := curr.Value.(*polynomial)
// dup是可能需要被合并结点的结点
dup := curr.Next()
for dup != nil {
dupValue := dup.Value.(*polynomial)
if currValue.Exponent == dupValue.Exponent {
currValue.Coefficient += dupValue.Coefficient
poly3.Remove(dup)
}
dup = dup.Next()
}
curr = curr.Next()
}
return poly3
}
func formatPolynomial(poly *list.List) string {
var ret []string
for node := poly.Front(); node != nil; node = node.Next() {
ret = append(ret, node.Value.(*polynomial).String())
}
return strings.Join(ret, " + ")
}
func main() {
poly1 := list.New()
poly1.PushBack(&polynomial{Coefficient: 5, Exponent: 2})
poly1.PushBack(&polynomial{Coefficient: 4, Exponent: 1})
poly1.PushBack(&polynomial{Coefficient: 2, Exponent: 0})
poly2 := list.New()
poly2.PushBack(&polynomial{Coefficient: 5, Exponent: 1})
poly2.PushBack(&polynomial{Coefficient: 5, Exponent: 0})
fmt.Printf("(%s) + (%s) = %s\n",
formatPolynomial(poly1), formatPolynomial(poly2), formatPolynomial(addPolynomial(poly1, poly2)))
fmt.Printf("(%s) * (%s) = %s\n",
formatPolynomial(poly1), formatPolynomial(poly2), formatPolynomial(multiplyPolynomial(poly1, poly2)))
}
|
[
5
] |
package main
import (
"fmt"
"strconv"
"strings"
)
func checkIntForPalimdrome(num int) bool {
numStr := strconv.Itoa(num)
numArray := strings.Split(numStr, "")
numLength := len(numArray)
for i := 0; i < numLength/2; i++ {
if i >= numLength/2 {
break
} else if numArray[i] == numArray[numLength-i-1] {
continue
} else {
return false
}
}
return true
}
func palindrome(max int) int {
highest := 0
for i := max; i > 100; i-- {
for j := max; j > 100; j-- {
if checkIntForPalimdrome(i * j) {
if i < j {
break
}
if i*j > highest {
highest = i * j
break
}
}
}
}
return highest
}
func main() {
maxNum := 999
fmt.Println(palindrome(maxNum))
}
|
[
1,
5
] |
package main
import "fmt"
func main() {
var score int
fmt.Scanf("%d", &score)
var grade string
if score >= 90 {
grade = "A"
} else if score >= 80 {
grade = "B"
} else if score >= 70 {
grade = "C"
} else if score >= 60 {
grade = "D"
} else {
grade = "F"
}
fmt.Print(grade)
}
|
[
5
] |
package utils
import (
"encoding/json"
"net/http"
)
// PrintMessage Function for printing response message
func PrintMessage(w http.ResponseWriter, ResponseArray interface{}, status int) {
w.WriteHeader(status)
json.NewEncoder(w).Encode(ResponseArray)
return
}
|
[
2
] |
package controllers
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/ozzadar/platformer_mission_server/database"
r "gopkg.in/rethinkdb/rethinkdb-go.v6"
)
type Server struct {
DBName string
Session *r.Session
Router *mux.Router
}
func (server *Server) Initialize(DbContainerName, DbUser, DbPassword, DbHost, DbPort, DbName string, reseed bool) {
// TODO: pass in DbUser, DbPassword into database.Init
server.DBName = DbName
if DbContainerName == "" {
log.Println("No container name provided for DB, using HOST:PORT format")
server.Session = database.Init(DbName, fmt.Sprintf("%s:%s", DbHost, DbPort), reseed)
} else {
log.Println("Container name provided for DB, using CONTAINER format")
server.Session = database.Init(DbName, DbContainerName, reseed)
}
server.Router = mux.NewRouter()
server.initializeRoutes()
}
func (server *Server) Run(addr string) {
fmt.Println("Listening to port " + addr)
log.Fatal(http.ListenAndServe(addr, server.Router))
}
|
[
2
] |
package functions
func ToplaVariadic(sayilar ...int) int {
toplam := 0
for i := 0; i < len(sayilar); i++ {
toplam = toplam + sayilar[i]
}
return toplam
}
|
[
0
] |
/* Copyright 2021 The Kubernetes Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, 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 bucket
import (
"context"
"fmt"
"strings"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
utilversion "k8s.io/apimachinery/pkg/util/version"
kube "k8s.io/client-go/kubernetes"
"k8s.io/klog/v2"
"sigs.k8s.io/container-object-storage-interface-api/apis/objectstorage/v1alpha1"
buckets "sigs.k8s.io/container-object-storage-interface-api/client/clientset/versioned"
bucketapi "sigs.k8s.io/container-object-storage-interface-api/client/clientset/versioned/typed/objectstorage/v1alpha1"
"sigs.k8s.io/container-object-storage-interface-provisioner-sidecar/pkg/consts"
cosi "sigs.k8s.io/container-object-storage-interface-spec"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"github.com/pkg/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// BucketListener manages Bucket objects
type BucketListener struct {
provisionerClient cosi.ProvisionerClient
driverName string
kubeClient kube.Interface
bucketClient buckets.Interface
kubeVersion *utilversion.Version
}
// NewBucketListener returns a resource handler for Bucket objects
func NewBucketListener(driverName string, client cosi.ProvisionerClient) *BucketListener {
bl := &BucketListener{
driverName: driverName,
provisionerClient: client,
}
return bl
}
// Add attempts to create a bucket for a given bucket. This function must be idempotent
// Return values
// nil - Bucket successfully provisioned
// non-nil err - Internal error [requeue'd with exponential backoff]
func (b *BucketListener) Add(ctx context.Context, inputBucket *v1alpha1.Bucket) error {
bucket := inputBucket.DeepCopy()
var err error
klog.V(3).InfoS("Add Bucket",
"name", bucket.ObjectMeta.Name)
if bucket.Spec.BucketClassName == "" {
err = errors.New(fmt.Sprintf("BucketClassName not defined for bucket %s", bucket.ObjectMeta.Name))
klog.V(3).ErrorS(err, "BucketClassName not defined")
return err
}
if !strings.EqualFold(bucket.Spec.DriverName, b.driverName) {
klog.V(5).InfoS("Skipping bucket for driver",
"bucket", bucket.ObjectMeta.Name,
"driver", bucket.Spec.DriverName,
)
return nil
}
if bucket.Status.BucketReady {
klog.V(5).InfoS("BucketExists",
"bucket", bucket.ObjectMeta.Name,
"driver", bucket.Spec.DriverName,
)
return nil
}
bucketReady := false
var bucketID string
if bucket.Spec.ExistingBucketID != "" {
bucketReady = true
bucketID = bucket.Spec.ExistingBucketID
if bucket.Spec.Parameters == nil {
bucketClass, err := b.bucketClasses().Get(ctx, bucket.Spec.BucketClassName, metav1.GetOptions{})
if err != nil {
klog.V(3).ErrorS(err, "Error fetching bucketClass",
"bucketClass", bucket.Spec.BucketClassName,
"bucket", bucket.ObjectMeta.Name)
return err
}
if bucketClass.Parameters != nil {
var param map[string]string
for k, v := range bucketClass.Parameters {
param[k] = v
}
bucket.Spec.Parameters = param
}
}
} else {
req := &cosi.DriverCreateBucketRequest{
Parameters: bucket.Spec.Parameters,
Name: bucket.ObjectMeta.Name,
}
rsp, err := b.provisionerClient.DriverCreateBucket(ctx, req)
if err != nil {
if status.Code(err) != codes.AlreadyExists {
klog.V(3).ErrorS(err, "Driver failed to create bucket",
"bucket", bucket.ObjectMeta.Name)
return errors.Wrap(err, "Failed to create bucket")
}
}
if rsp == nil {
err = errors.New(fmt.Sprintf("DriverCreateBucket returned a nil response for bucket: %s", bucket.ObjectMeta.Name))
klog.V(3).ErrorS(err, "Internal Error from driver",
"bucket", bucket.ObjectMeta.Name)
return err
}
if rsp.BucketId != "" {
bucketID = rsp.BucketId
bucketReady = true
} else {
klog.V(3).ErrorS(err, "DriverCreateBucket returned an empty bucketID",
"bucket", bucket.ObjectMeta.Name)
err = errors.New(fmt.Sprintf("DriverCreateBucket returned an empty bucketID for bucket: %s", bucket.ObjectMeta.Name))
return err
}
// Now we update the BucketReady status of BucketClaim
if bucket.Spec.BucketClaim != nil {
ref := bucket.Spec.BucketClaim
bucketClaim, err := b.bucketClaims(ref.Namespace).Get(ctx, ref.Name, metav1.GetOptions{})
if err != nil {
klog.V(3).ErrorS(err, "Failed to get bucketClaim",
"bucketClaim", ref.Name,
"bucket", bucket.ObjectMeta.Name)
return err
}
bucketClaim.Status.BucketReady = true
if _, err = b.bucketClaims(bucketClaim.Namespace).UpdateStatus(ctx, bucketClaim, metav1.UpdateOptions{}); err != nil {
klog.V(3).ErrorS(err, "Failed to update bucketClaim",
"bucketClaim", ref.Name,
"bucket", bucket.ObjectMeta.Name)
return err
}
klog.V(5).Infof("Successfully updated status of bucketClaim: %s, bucket: %s", bucketClaim.ObjectMeta.Name, bucket.ObjectMeta.Name)
}
}
controllerutil.AddFinalizer(bucket, consts.BucketFinalizer)
if bucket, err = b.buckets().Update(ctx, bucket, metav1.UpdateOptions{}); err != nil {
klog.V(3).ErrorS(err, "Failed to update bucket finalizers", "bucket", bucket.ObjectMeta.Name)
return errors.Wrap(err, "Failed to update bucket finalizers")
}
klog.V(5).Infof("Successfully added finalizer to bucket: %s", bucket.ObjectMeta.Name)
// Setting the status here so that the updated object is used
bucket.Status.BucketReady = bucketReady
bucket.Status.BucketID = bucketID
// if this step fails, then controller will retry with backoff
if _, err = b.buckets().UpdateStatus(ctx, bucket, metav1.UpdateOptions{}); err != nil {
klog.V(3).ErrorS(err, "Failed to update bucket status",
"bucket", bucket.ObjectMeta.Name)
return errors.Wrap(err, "Failed to update bucket status")
}
klog.V(3).InfoS("Add Bucket success",
"bucket", bucket.ObjectMeta.Name,
"bucketID", bucketID,
"ns", bucket.ObjectMeta.Namespace)
return nil
}
// Update attempts to reconcile changes to a given bucket. This function must be idempotent
// Return values
// nil - Bucket successfully reconciled
// non-nil err - Internal error [requeue'd with exponential backoff]
func (b *BucketListener) Update(ctx context.Context, old, new *v1alpha1.Bucket) error {
klog.V(3).InfoS("Update Bucket",
"name", old.Name)
bucket := new.DeepCopy()
var err error
if !bucket.GetDeletionTimestamp().IsZero() {
if controllerutil.ContainsFinalizer(bucket, consts.BABucketFinalizer) {
bucketClaimNs := bucket.Spec.BucketClaim.Namespace
bucketClaimName := bucket.Spec.BucketClaim.Name
bucketAccessList, err := b.bucketAccesses(bucketClaimNs).List(ctx, metav1.ListOptions{})
for _, bucketAccess := range bucketAccessList.Items {
if strings.EqualFold(bucketAccess.Spec.BucketClaimName, bucketClaimName) {
err = b.bucketAccesses(bucketClaimNs).Delete(ctx, bucketAccess.Name, metav1.DeleteOptions{})
if err != nil {
klog.V(3).ErrorS(err, "Error deleting BucketAccess",
"name", bucketAccess.Name,
"bucket", bucket.ObjectMeta.Name)
return err
}
}
}
klog.V(5).Infof("Successfully deleted dependent bucketAccess of bucket:%s", bucket.ObjectMeta.Name)
controllerutil.RemoveFinalizer(bucket, consts.BABucketFinalizer)
klog.V(5).Infof("Successfully removed finalizer: %s of bucket: %s", consts.BABucketFinalizer, bucket.ObjectMeta.Name)
}
if controllerutil.ContainsFinalizer(bucket, consts.BucketFinalizer) {
err = b.deleteBucketOp(ctx, bucket)
if err != nil {
return err
}
controllerutil.RemoveFinalizer(bucket, consts.BucketFinalizer)
klog.V(5).Infof("Successfully removed finalizer: %s of bucket: %s", consts.BucketFinalizer, bucket.ObjectMeta.Name)
}
_, err = b.buckets().Update(ctx, bucket, metav1.UpdateOptions{})
if err != nil {
klog.V(3).ErrorS(err, "Error updating bucket after removing finalizers",
"bucket", bucket.ObjectMeta.Name)
return err
}
}
klog.V(3).InfoS("Update Bucket success",
"name", bucket.ObjectMeta.Name,
"ns", bucket.ObjectMeta.Namespace)
return nil
}
// Delete attemps to delete a bucket. This function must be idempotent
// Delete function is called when the bucket was not able to add finalizers while creation.
// Hence we will take care of removing the BucketClaim finalizer before deleting the Bucket object.
// Return values
// nil - Bucket successfully deleted
// non-nil err - Internal error [requeue'd with exponential backoff]
func (b *BucketListener) Delete(ctx context.Context, inputBucket *v1alpha1.Bucket) error {
klog.V(3).InfoS("Delete Bucket",
"name", inputBucket.ObjectMeta.Name,
"bucketclass", inputBucket.Spec.BucketClassName)
if inputBucket.Spec.BucketClaim != nil {
ref := inputBucket.Spec.BucketClaim
klog.V(3).Infof("Removing finalizer of bucketClaim: %s before deleting bucket: %s", ref.Name, inputBucket.ObjectMeta.Name)
bucketClaim, err := b.bucketClaims(ref.Namespace).Get(ctx, ref.Name, metav1.GetOptions{})
if err != nil {
klog.V(3).ErrorS(err, "Error getting bucketClaim for removing finalizer",
"bucket", inputBucket.ObjectMeta.Name,
"bucketClaim", ref.Name)
return err
}
if controllerutil.RemoveFinalizer(bucketClaim, consts.BCFinalizer) {
_, err := b.bucketClaims(bucketClaim.ObjectMeta.Namespace).Update(ctx, bucketClaim, metav1.UpdateOptions{})
if err != nil {
klog.V(3).ErrorS(err, "Error removing bucketClaim finalizer",
"bucket", inputBucket.ObjectMeta.Name,
"bucketClaim", bucketClaim.ObjectMeta.Name)
return err
}
}
}
return nil
}
// InitializeKubeClient initializes the kubernetes client
func (b *BucketListener) InitializeKubeClient(k kube.Interface) {
b.kubeClient = k
serverVersion, err := k.Discovery().ServerVersion()
if err != nil {
klog.V(3).ErrorS(err, "Cannot determine server version")
} else {
b.kubeVersion = utilversion.MustParseSemantic(serverVersion.GitVersion)
}
}
// InitializeBucketClient initializes the object storage bucket client
func (b *BucketListener) InitializeBucketClient(bc buckets.Interface) {
b.bucketClient = bc
}
func (b *BucketListener) deleteBucketOp(ctx context.Context, bucket *v1alpha1.Bucket) error {
if !strings.EqualFold(bucket.Spec.DriverName, b.driverName) {
klog.V(5).InfoS("Skipping bucket for provisioner",
"bucket", bucket.ObjectMeta.Name,
"driver", bucket.Spec.DriverName,
)
return nil
}
// We ask the driver to clean up the bucket from the storage provider
// only when the retain policy is set to Delete
if bucket.Spec.DeletionPolicy == v1alpha1.DeletionPolicyDelete {
req := &cosi.DriverDeleteBucketRequest{
BucketId: bucket.Status.BucketID,
DeleteContext: bucket.Spec.Parameters,
}
if _, err := b.provisionerClient.DriverDeleteBucket(ctx, req); err != nil {
if status.Code(err) != codes.NotFound {
klog.V(3).ErrorS(err, "Failed to delete bucket",
"bucket", bucket.ObjectMeta.Name,
)
return err
}
}
klog.V(5).Infof("Successfully deleted bucketID: %s from the object storage for bucket: %s", bucket.Status.BucketID, bucket.ObjectMeta.Name)
}
if bucket.Spec.BucketClaim != nil {
ref := bucket.Spec.BucketClaim
bucketClaim, err := b.bucketClaims(ref.Namespace).Get(ctx, ref.Name, metav1.GetOptions{})
if err != nil {
klog.V(3).ErrorS(err, "Error fetching bucketClaim",
"bucketClaim", ref.Name,
"bucket", bucket.ObjectMeta.Name)
return err
}
if controllerutil.RemoveFinalizer(bucketClaim, consts.BCFinalizer) {
if _, err := b.bucketClaims(bucketClaim.ObjectMeta.Namespace).Update(ctx, bucketClaim, metav1.UpdateOptions{}); err != nil {
klog.V(3).ErrorS(err, "Error removing finalizer from bucketClaim",
"bucketClaim", bucketClaim.ObjectMeta.Name,
"bucket", bucket.ObjectMeta.Name)
return err
}
}
klog.V(5).Infof("Successfully removed finalizer: %s from bucketClaim: %s for bucket: %s", consts.BCFinalizer, bucketClaim.ObjectMeta.Name, bucket.ObjectMeta.Name)
}
return nil
}
func (b *BucketListener) buckets() bucketapi.BucketInterface {
if b.bucketClient != nil {
return b.bucketClient.ObjectstorageV1alpha1().Buckets()
}
panic("uninitialized listener")
}
func (b *BucketListener) bucketClasses() bucketapi.BucketClassInterface {
if b.bucketClient != nil {
return b.bucketClient.ObjectstorageV1alpha1().BucketClasses()
}
panic("uninitialized listener")
}
func (b *BucketListener) bucketClaims(namespace string) bucketapi.BucketClaimInterface {
if b.bucketClient != nil {
return b.bucketClient.ObjectstorageV1alpha1().BucketClaims(namespace)
}
panic("uninitialized listener")
}
func (b *BucketListener) bucketAccesses(namespace string) bucketapi.BucketAccessInterface {
if b.bucketClient != nil {
return b.bucketClient.ObjectstorageV1alpha1().BucketAccesses(namespace)
}
panic("uninitialized listener")
}
|
[
1
] |
package logger
import (
"os"
"time"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// NewLogger instanciate a new zap.Logger that will output to both console and graylog.
// If GraylogEndpoint == "", no data will be send to graylog.
func NewLogger(GraylogEndpoint string, GraylogLevel, CLILevel Level) (*zap.Logger, error) {
c := zap.NewProductionConfig()
c.Level = zap.NewAtomicLevelAt(zapcore.Level(CLILevel))
log, err := c.Build()
if err != nil {
return nil, err
}
if GraylogEndpoint == "" {
return log, nil
}
graylogWriter, err := NewGELFWriter(GraylogEndpoint)
if err != nil {
return nil, err
}
log = log.WithOptions(zap.WrapCore(func(c zapcore.Core) zapcore.Core {
return zapcore.NewTee(
c,
zapcore.NewSampler(
zapcore.NewCore(NewGELFEncoder(), graylogWriter, zap.NewAtomicLevelAt(zapcore.Level(GraylogLevel))),
time.Second,
100,
100,
),
)
}))
// Add hostname if we can get it.
if host, err := os.Hostname(); err == nil {
log = log.With(zap.String("host", host))
}
return log, nil
}
|
[
2
] |
package main
import ( "fmt"; "os"; "strconv"; "time" )
const MAXSIZE = 20
var repeat = 10
var size = 14
var cutOff = 7
type Board struct {
Queens uint
Limit uint
Left uint
Down uint
Right uint
Kill uint
}
func initBoard(width uint) Board {
return Board {
Queens: width,
Limit: 1 << width,
Left: 0,
Down: 0,
Right: 0,
Kill: 0,
}
}
func put (b Board, bit uint) Board {
r := Board{}
r.Queens = b.Queens - 1
r.Limit = b.Limit
r.Left = (b.Left | bit) >> 1
r.Down = (b.Down | bit)
r.Right = (b.Right | bit) << 1
r.Kill = r.Left | r.Down | r.Right
return r
}
func ssum (board Board) int {
sum := 0
var bit uint = 1
for {
if bit >= board.Limit { break }
if (board.Kill & bit) == 0 { sum += solve(put(board, bit)) }
bit <<= 1
}
return sum
}
func psum (board Board, bit uint) int {
for {
if bit >= board.Limit { break }
if (board.Kill & bit) == 0 {
t := make(chan int)
go func(t chan int) { t <- solve(put(board, bit)) } (t)
n := psum(board, bit << 1)
return n + <- t
}
bit <<= 1
}
return 0
}
func solve (board Board) int {
if board.Queens == 0 {
return 1
} else if board.Queens <= uint(cutOff) {
return ssum(board)
} else {
return psum(board, 1)
}
}
func doit() int {
b := initBoard(uint(size))
return solve(b)
}
func rep() {
for i := 0; i < repeat; i++ {
t1 := time.Now()
r := doit()
t2 := time.Now()
fmt.Printf(" - {result: %d, time: %.6f}\n", r, t2.Sub(t1).Seconds())
}
}
func main() {
if len(os.Args) > 1 { repeat, _ = strconv.Atoi(os.Args[1]) }
if len(os.Args) > 2 { size, _ = strconv.Atoi(os.Args[2]) }
if len(os.Args) > 3 { cutOff, _ = strconv.Atoi(os.Args[3]) }
fmt.Printf(" bench: nqueen_go_value\n size: %d\n cutoff: %d\n results:\n",
size, cutOff);
rep()
}
|
[
5
] |
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package encodecounter
import (
"bufio"
"encoding/binary"
"fmt"
"internal/coverage"
"internal/coverage/slicewriter"
"internal/coverage/stringtab"
"internal/coverage/uleb128"
"io"
"os"
"sort"
)
// This package contains APIs and helpers for encoding initial portions
// of the counter data files emitted at runtime when coverage instrumentation
// is enabled. Counter data files may contain multiple segments; the file
// header and first segment are written via the "Write" method below, and
// additional segments can then be added using "AddSegment".
type CoverageDataWriter struct {
stab *stringtab.Writer
w *bufio.Writer
csh coverage.CounterSegmentHeader
tmp []byte
cflavor coverage.CounterFlavor
segs uint32
debug bool
}
func NewCoverageDataWriter(w io.Writer, flav coverage.CounterFlavor) *CoverageDataWriter {
r := &CoverageDataWriter{
stab: &stringtab.Writer{},
w: bufio.NewWriter(w),
tmp: make([]byte, 64),
cflavor: flav,
}
r.stab.InitWriter()
r.stab.Lookup("")
return r
}
// CounterVisitor describes a helper object used during counter file
// writing; when writing counter data files, clients pass a
// CounterVisitor to the write/emit routines, then the expectation is
// that the VisitFuncs method will then invoke the callback "f" with
// data for each function to emit to the file.
type CounterVisitor interface {
VisitFuncs(f CounterVisitorFn) error
}
// CounterVisitorFn describes a callback function invoked when writing
// coverage counter data.
type CounterVisitorFn func(pkid uint32, funcid uint32, counters []uint32) error
// Write writes the contents of the count-data file to the writer
// previously supplied to NewCoverageDataWriter. Returns an error
// if something went wrong somewhere with the write.
func (cfw *CoverageDataWriter) Write(metaFileHash [16]byte, args map[string]string, visitor CounterVisitor) error {
if err := cfw.writeHeader(metaFileHash); err != nil {
return err
}
return cfw.AppendSegment(args, visitor)
}
func padToFourByteBoundary(ws *slicewriter.WriteSeeker) error {
sz := len(ws.BytesWritten())
zeros := []byte{0, 0, 0, 0}
rem := uint32(sz) % 4
if rem != 0 {
pad := zeros[:(4 - rem)]
if nw, err := ws.Write(pad); err != nil {
return err
} else if nw != len(pad) {
return fmt.Errorf("error: short write")
}
}
return nil
}
func (cfw *CoverageDataWriter) patchSegmentHeader(ws *slicewriter.WriteSeeker) error {
// record position
off, err := ws.Seek(0, io.SeekCurrent)
if err != nil {
return fmt.Errorf("error seeking in patchSegmentHeader: %v", err)
}
// seek back to start so that we can update the segment header
if _, err := ws.Seek(0, io.SeekStart); err != nil {
return fmt.Errorf("error seeking in patchSegmentHeader: %v", err)
}
if cfw.debug {
fmt.Fprintf(os.Stderr, "=-= writing counter segment header: %+v", cfw.csh)
}
if err := binary.Write(ws, binary.LittleEndian, cfw.csh); err != nil {
return err
}
// ... and finally return to the original offset.
if _, err := ws.Seek(off, io.SeekStart); err != nil {
return fmt.Errorf("error seeking in patchSegmentHeader: %v", err)
}
return nil
}
func (cfw *CoverageDataWriter) writeSegmentPreamble(args map[string]string, ws *slicewriter.WriteSeeker) error {
if err := binary.Write(ws, binary.LittleEndian, cfw.csh); err != nil {
return err
}
hdrsz := uint32(len(ws.BytesWritten()))
// Write string table and args to a byte slice (since we need
// to capture offsets at various points), then emit the slice
// once we are done.
cfw.stab.Freeze()
if err := cfw.stab.Write(ws); err != nil {
return err
}
cfw.csh.StrTabLen = uint32(len(ws.BytesWritten())) - hdrsz
akeys := make([]string, 0, len(args))
for k := range args {
akeys = append(akeys, k)
}
sort.Strings(akeys)
wrULEB128 := func(v uint) error {
cfw.tmp = cfw.tmp[:0]
cfw.tmp = uleb128.AppendUleb128(cfw.tmp, v)
if _, err := ws.Write(cfw.tmp); err != nil {
return err
}
return nil
}
// Count of arg pairs.
if err := wrULEB128(uint(len(args))); err != nil {
return err
}
// Arg pairs themselves.
for _, k := range akeys {
ki := uint(cfw.stab.Lookup(k))
if err := wrULEB128(ki); err != nil {
return err
}
v := args[k]
vi := uint(cfw.stab.Lookup(v))
if err := wrULEB128(vi); err != nil {
return err
}
}
if err := padToFourByteBoundary(ws); err != nil {
return err
}
cfw.csh.ArgsLen = uint32(len(ws.BytesWritten())) - (cfw.csh.StrTabLen + hdrsz)
return nil
}
// AppendSegment appends a new segment to a counter data, with a new
// args section followed by a payload of counter data clauses.
func (cfw *CoverageDataWriter) AppendSegment(args map[string]string, visitor CounterVisitor) error {
cfw.stab = &stringtab.Writer{}
cfw.stab.InitWriter()
cfw.stab.Lookup("")
var err error
for k, v := range args {
cfw.stab.Lookup(k)
cfw.stab.Lookup(v)
}
ws := &slicewriter.WriteSeeker{}
if err = cfw.writeSegmentPreamble(args, ws); err != nil {
return err
}
if err = cfw.writeCounters(visitor, ws); err != nil {
return err
}
if err = cfw.patchSegmentHeader(ws); err != nil {
return err
}
if err := cfw.writeBytes(ws.BytesWritten()); err != nil {
return err
}
if err = cfw.writeFooter(); err != nil {
return err
}
if err := cfw.w.Flush(); err != nil {
return fmt.Errorf("write error: %v", err)
}
cfw.stab = nil
return nil
}
func (cfw *CoverageDataWriter) writeHeader(metaFileHash [16]byte) error {
// Emit file header.
ch := coverage.CounterFileHeader{
Magic: coverage.CovCounterMagic,
Version: coverage.CounterFileVersion,
MetaHash: metaFileHash,
CFlavor: cfw.cflavor,
BigEndian: false,
}
if err := binary.Write(cfw.w, binary.LittleEndian, ch); err != nil {
return err
}
return nil
}
func (cfw *CoverageDataWriter) writeBytes(b []byte) error {
if len(b) == 0 {
return nil
}
nw, err := cfw.w.Write(b)
if err != nil {
return fmt.Errorf("error writing counter data: %v", err)
}
if len(b) != nw {
return fmt.Errorf("error writing counter data: short write")
}
return nil
}
func (cfw *CoverageDataWriter) writeCounters(visitor CounterVisitor, ws *slicewriter.WriteSeeker) error {
// Notes:
// - this version writes everything little-endian, which means
// a call is needed to encode every value (expensive)
// - we may want to move to a model in which we just blast out
// all counters, or possibly mmap the file and do the write
// implicitly.
ctrb := make([]byte, 4)
wrval := func(val uint32) error {
var buf []byte
var towr int
if cfw.cflavor == coverage.CtrRaw {
binary.LittleEndian.PutUint32(ctrb, val)
buf = ctrb
towr = 4
} else if cfw.cflavor == coverage.CtrULeb128 {
cfw.tmp = cfw.tmp[:0]
cfw.tmp = uleb128.AppendUleb128(cfw.tmp, uint(val))
buf = cfw.tmp
towr = len(buf)
} else {
panic("internal error: bad counter flavor")
}
if sz, err := ws.Write(buf); err != nil {
return err
} else if sz != towr {
return fmt.Errorf("writing counters: short write")
}
return nil
}
// Write out entries for each live function.
emitter := func(pkid uint32, funcid uint32, counters []uint32) error {
cfw.csh.FcnEntries++
if err := wrval(uint32(len(counters))); err != nil {
return err
}
if err := wrval(pkid); err != nil {
return err
}
if err := wrval(funcid); err != nil {
return err
}
for _, val := range counters {
if err := wrval(val); err != nil {
return err
}
}
return nil
}
if err := visitor.VisitFuncs(emitter); err != nil {
return err
}
return nil
}
func (cfw *CoverageDataWriter) writeFooter() error {
cfw.segs++
cf := coverage.CounterFileFooter{
Magic: coverage.CovCounterMagic,
NumSegments: cfw.segs,
}
if err := binary.Write(cfw.w, binary.LittleEndian, cf); err != nil {
return err
}
return nil
}
|
[
5
] |
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google
import (
"fmt"
"yunion.io/x/pkg/errors"
"yunion.io/x/pkg/utils"
api "yunion.io/x/onecloud/pkg/apis/compute"
"yunion.io/x/onecloud/pkg/cloudprovider"
"yunion.io/x/onecloud/pkg/multicloud"
)
type SVpc struct {
multicloud.SVpc
globalnetwork *SGlobalNetwork
region *SRegion
}
func (vpc *SVpc) GetName() string {
return fmt.Sprintf("%s(%s)", vpc.globalnetwork.Name, vpc.region.Name)
}
func (vpc *SVpc) GetId() string {
return vpc.globalnetwork.GetGlobalId()
}
func (vpc *SVpc) GetGlobalId() string {
return fmt.Sprintf("%s/%s", vpc.region.GetGlobalId(), vpc.GetId())
}
func (vpc *SVpc) Refresh() error {
return nil
}
func (vpc *SVpc) GetStatus() string {
return api.VPC_STATUS_AVAILABLE
}
func (vpc *SVpc) Delete() error {
return vpc.region.Delete(vpc.globalnetwork.SelfLink)
}
func (vpc *SVpc) GetCidrBlock() string {
return ""
}
func (vpc *SVpc) IsEmulated() bool {
return false
}
func (vpc *SVpc) GetIsDefault() bool {
return false
}
func (vpc *SVpc) GetRegion() cloudprovider.ICloudRegion {
return vpc.region
}
func (vpc *SVpc) GetIRouteTables() ([]cloudprovider.ICloudRouteTable, error) {
return nil, cloudprovider.ErrNotImplemented
}
func (vpc *SVpc) GetISecurityGroups() ([]cloudprovider.ICloudSecurityGroup, error) {
firewalls, err := vpc.region.GetFirewalls(vpc.globalnetwork.SelfLink, 0, "")
if err != nil {
return nil, errors.Wrap(err, "GetFirewalls")
}
isecgroups := []cloudprovider.ICloudSecurityGroup{}
allInstance := false
tags := []string{}
for _, firewall := range firewalls {
if len(firewall.TargetServiceAccounts) > 0 {
secgroup := &SSecurityGroup{vpc: vpc, ServiceAccount: firewall.TargetServiceAccounts[0]}
isecgroups = append(isecgroups, secgroup)
} else if len(firewall.TargetTags) > 0 && !utils.IsInStringArray(firewall.TargetTags[0], tags) {
secgroup := &SSecurityGroup{vpc: vpc, Tag: firewall.TargetTags[0]}
tags = append(tags, firewall.TargetTags[0])
isecgroups = append(isecgroups, secgroup)
} else if !allInstance {
secgroup := &SSecurityGroup{vpc: vpc}
isecgroups = append(isecgroups, secgroup)
allInstance = true
}
}
return isecgroups, nil
}
func (vpc *SVpc) getWire() *SWire {
return &SWire{vpc: vpc}
}
func (vpc *SVpc) GetIWires() ([]cloudprovider.ICloudWire, error) {
wire := vpc.getWire()
return []cloudprovider.ICloudWire{wire}, nil
}
func (vpc *SVpc) GetIWireById(id string) (cloudprovider.ICloudWire, error) {
if id != vpc.getWire().GetGlobalId() {
return nil, cloudprovider.ErrNotFound
}
return &SWire{vpc: vpc}, nil
}
|
[
5
] |
// Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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 artifacts
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
)
type roundTripFunc func(r *http.Request) (*http.Response, error)
func (s roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) {
return s(r)
}
func newMockClient(rt roundTripFunc) *http.Client {
return &http.Client{Transport: rt}
}
func newResponseBody(content string) io.ReadCloser {
return ioutil.NopCloser(strings.NewReader(content))
}
func TestDownloadArtifact(t *testing.T) {
binContent := "001100"
getSignedURLRequestURI := "/android/internal/build/v3/builds/1/xyzzy/attempts/latest/artifacts/foo/url?redirect=false"
downloadRequestURI := "/android-build/builds/X/Y/Z"
url := "https://someurl.fake"
mockClient := newMockClient(func(r *http.Request) (*http.Response, error) {
res := &http.Response{
StatusCode: http.StatusOK,
}
reqURI := r.URL.RequestURI()
if reqURI == getSignedURLRequestURI {
resURL := url + downloadRequestURI
res.Body = newResponseBody(`{"signedUrl": "` + resURL + `"}`)
} else if reqURI == downloadRequestURI {
res.Body = newResponseBody(binContent)
} else {
t.Fatalf("invalide request URI: %q\n", reqURI)
}
return res, nil
})
srv := NewAndroidCIBuildAPI(mockClient, url)
var b bytes.Buffer
srv.DownloadArtifact("foo", "1", "xyzzy", io.Writer(&b))
if diff := cmp.Diff(binContent, b.String()); diff != "" {
t.Errorf("content mismatch (-want +got):\n%s", diff)
}
}
func TestDownloadArtifactWithErrorResponse(t *testing.T) {
errorMessage := "No latest build attempt for build 1"
url := "https://something.fake"
mockClient := newMockClient(func(r *http.Request) (*http.Response, error) {
errJSON := `{
"error": {
"code": 401,
"message": "` + errorMessage + `"
}
}`
return &http.Response{
StatusCode: http.StatusNotFound,
Body: newResponseBody(errJSON),
}, nil
})
srv := NewAndroidCIBuildAPI(mockClient, url)
var b bytes.Buffer
err := srv.DownloadArtifact("foo", "1", "xyzzy", io.Writer(&b))
if !strings.Contains(err.Error(), errorMessage) {
t.Errorf("expected to contain <<%q>> in error: %#v", errorMessage, err)
}
}
func TestBuildDownloadArtifactSignedURL(t *testing.T) {
baseURL := "http://localhost:1080"
t.Run("regular build id", func(t *testing.T) {
expected := "http://localhost:1080/android/internal/build/v3/builds/1/xyzzy/attempts/latest/artifacts/foo/url?redirect=false"
got := BuildDownloadArtifactSignedURL(baseURL, "foo", "1", "xyzzy")
if diff := cmp.Diff(expected, got); diff != "" {
t.Errorf("url mismatch (-want +got):\n%s", diff)
}
})
t.Run("url-escaped android build params", func(t *testing.T) {
expected := "http://localhost:1080/android/internal/build/v3/builds/1%3F/xyzzy%3F/attempts/latest/artifacts/foo/url?redirect=false"
got := BuildDownloadArtifactSignedURL(baseURL, "foo", "1?", "xyzzy?")
if diff := cmp.Diff(expected, got); diff != "" {
t.Errorf("url mismatch (-want +got):\n%s", diff)
}
})
}
func TestCredentialsAddedToRequest(t *testing.T) {
credentials := "random string"
mockClient := newMockClient(func(r *http.Request) (*http.Response, error) {
res := &http.Response{
StatusCode: http.StatusOK,
}
if diff := cmp.Diff(r.Header["Authorization"], []string{fmt.Sprintf("Bearer %s", credentials)}); diff != "" {
t.Errorf("Authorization header missing or malformed: %v", r.Header["Authorization"])
}
return res, nil
})
downloadRequestURI := "/android-build/builds/X/Y/Z"
url := "https://someurl.fake"
opts := AndroidCIBuildAPIOpts{Credentials: credentials}
srv := NewAndroidCIBuildAPIWithOpts(mockClient, url, opts)
_, err := srv.doGETCommon(downloadRequestURI)
if err != nil {
t.Errorf("GET failed: %v", err)
}
}
func TestEmptyCredentialsIgnored(t *testing.T) {
credentials := ""
mockClient := newMockClient(func(r *http.Request) (*http.Response, error) {
res := &http.Response{
StatusCode: http.StatusOK,
}
if _, ok := res.Header["Authorization"]; ok {
t.Errorf("Unexpected Authorization header in request: %v", res.Header["Authorization"])
}
return res, nil
})
downloadRequestURI := "/android-build/builds/X/Y/Z"
url := "https://someurl.fake"
opts := AndroidCIBuildAPIOpts{Credentials: credentials}
srv := NewAndroidCIBuildAPIWithOpts(mockClient, url, opts)
_, err := srv.doGETCommon(downloadRequestURI)
if err != nil {
t.Errorf("GET failed: %v", err)
}
}
|
[
5
] |
package main
/* import (
"fmt"
"bufio"
"log"
"os"
) */
type Nodo struct {
datos string
padre string
hijo map[int]string
coste int
// set_hijos(hijos)
}
func (n *Nodo) Set_Hijos(hijos map[int]*Nodo){
n.hijo=make(map[int]string)
for _,K:=range hijos{
n.hijo[len(n.hijo)]=K.datos
}
// fmt.Println(n)
if len(n.hijo)!=0{
for _,Y:=range hijos{
Y.padre=n.datos
// log.Println(Y)
}
}
// bufio.NewReader(os.Stdin).ReadBytes('\n')
}
func (n *Nodo) Set_Padre(Padre string){
n.padre = Padre
}
func (n *Nodo) Set_Datos(Datos string){
n.datos = Datos
}
func (n *Nodo) Set_Coste(Coste int){
n.coste = Coste
}
func (n *Nodo) get_Hijos() map[int]string{
return n.hijo
}
func (n *Nodo) Get_Padre()string{
return n.padre
}
func (n *Nodo) Get_Datos()string{
return n.datos
}
func (n *Nodo) Get_Coste() int{
return n.coste
}
func (n *Nodo) igual(nodo Nodo) bool{
if n.Get_Datos()==nodo.Get_Datos(){
return true
}else{
return false
}
}
func (n *Nodo) En_Lista(lista map[int]Nodo) bool{
en_la_lista:=false
for _,X:=range lista{
if n.igual(X){
en_la_lista=true
}
}
return en_la_lista
}
func Reverse(Resultados [][4]int){
for i, j := 0, len(Resultados)-1; i < j; i, j = i+1, j-1 {
Resultados[i], Resultados[j] = Resultados[j], Resultados[i]
}
}
func BuscarPadre(hijo string) Nodo{
var padre Nodo
for _,x := range (Nodos_Visitados){
if x.datos==hijo{
padre=x
break
}
}
return padre
}
|
[
2
] |
// Code generated by mockery v1.0.0. DO NOT EDIT.
package mocks
import context "context"
import mock "github.com/stretchr/testify/mock"
import sbac "chainspace.io/chainspace-go/sbac"
import service "chainspace.io/chainspace-go/service"
// Service is an autogenerated mock type for the Service type
type Service struct {
mock.Mock
}
// Check provides a mock function with given fields: ctx, tx
func (_m *Service) Check(ctx context.Context, tx *sbac.Transaction) (bool, error) {
ret := _m.Called(ctx, tx)
var r0 bool
if rf, ok := ret.Get(0).(func(context.Context, *sbac.Transaction) bool); ok {
r0 = rf(ctx, tx)
} else {
r0 = ret.Get(0).(bool)
}
var r1 error
if rf, ok := ret.Get(1).(func(context.Context, *sbac.Transaction) error); ok {
r1 = rf(ctx, tx)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// CheckAndSign provides a mock function with given fields: ctx, tx
func (_m *Service) CheckAndSign(ctx context.Context, tx *sbac.Transaction) (bool, []byte, error) {
ret := _m.Called(ctx, tx)
var r0 bool
if rf, ok := ret.Get(0).(func(context.Context, *sbac.Transaction) bool); ok {
r0 = rf(ctx, tx)
} else {
r0 = ret.Get(0).(bool)
}
var r1 []byte
if rf, ok := ret.Get(1).(func(context.Context, *sbac.Transaction) []byte); ok {
r1 = rf(ctx, tx)
} else {
if ret.Get(1) != nil {
r1 = ret.Get(1).([]byte)
}
}
var r2 error
if rf, ok := ret.Get(2).(func(context.Context, *sbac.Transaction) error); ok {
r2 = rf(ctx, tx)
} else {
r2 = ret.Error(2)
}
return r0, r1, r2
}
// Handle provides a mock function with given fields: peerID, msg
func (_m *Service) Handle(peerID uint64, msg *service.Message) (*service.Message, error) {
ret := _m.Called(peerID, msg)
var r0 *service.Message
if rf, ok := ret.Get(0).(func(uint64, *service.Message) *service.Message); ok {
r0 = rf(peerID, msg)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*service.Message)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(uint64, *service.Message) error); ok {
r1 = rf(peerID, msg)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// Name provides a mock function with given fields:
func (_m *Service) Name() string {
ret := _m.Called()
var r0 string
if rf, ok := ret.Get(0).(func() string); ok {
r0 = rf()
} else {
r0 = ret.Get(0).(string)
}
return r0
}
|
[
4
] |
package handlers
import (
"banking-system/internal/dto"
"banking-system/internal/interfaces/iservices"
"context"
"net/http"
"sync"
"github.com/google/uuid"
"github.com/labstack/echo"
log "github.com/sirupsen/logrus"
)
type AccountHandler struct {
IAccountService iservices.IAccountService
}
var AccountHandlerInstance *AccountHandler
var AccountHandlerOnce sync.Once
func NewAccountHandler(
IAccountService iservices.IAccountService,
) *AccountHandler {
if AccountHandlerInstance == nil {
AccountHandlerOnce.Do(func() {
AccountHandlerInstance = &AccountHandler{
IAccountService: IAccountService,
}
})
}
return AccountHandlerInstance
}
func (handler *AccountHandler) CreateAccount(c echo.Context) error {
log.Info("Method: Create account")
ctx := context.WithValue(httpContext, USER_ID, c.Get(USER_ID))
requestBody := new(dto.AccountRequestDto)
bindErr := c.Bind(requestBody)
if bindErr != nil {
return c.NoContent(http.StatusBadRequest)
}
acc, err := handler.IAccountService.Create(ctx, requestBody)
if err != nil {
return c.NoContent(http.StatusBadRequest)
}
return c.JSON(http.StatusCreated, acc)
}
func (handler *AccountHandler) GetBalance(c echo.Context) error {
log.Info("Method: Get balance")
ctx := context.WithValue(httpContext, USER_ID, c.Get(USER_ID))
accountId, err := uuid.Parse(c.Param("id"))
if err != nil {
return c.NoContent(http.StatusBadRequest)
}
acc, err := handler.IAccountService.GetAccount(ctx, accountId)
if err != nil {
return c.NoContent(http.StatusBadRequest)
}
return c.JSON(http.StatusOK, &struct {
Balance uint `json:"balance"`
}{
Balance: acc.Balance,
})
}
|
[
2
] |
package component
import (
"fmt"
"net/http"
"github.com/bububa/wechat/internal/debug/api"
mpoauth2 "github.com/bububa/wechat/mp/oauth2"
"github.com/bububa/wechat/oauth2"
"github.com/bububa/wechat/util"
)
// GetSession 获取小程序会话
func GetSession(Endpoint *Endpoint, code string) (session *mpoauth2.Session, err error) {
session = &mpoauth2.Session{}
if err = getSession(session, Endpoint.SessionCodeUrl(code), nil); err != nil {
return
}
return
}
// GetSessionWithClient 获取小程序会话
func GetSessionWithClient(Endpoint *Endpoint, code string, httpClient *http.Client) (session *mpoauth2.Session, err error) {
session = &mpoauth2.Session{}
if err = getSession(session, Endpoint.SessionCodeUrl(code), httpClient); err != nil {
return
}
return
}
func getSession(session *mpoauth2.Session, url string, httpClient *http.Client) (err error) {
if httpClient == nil {
httpClient = util.DefaultHttpClient
}
api.DebugPrintGetRequest(url, false)
httpResp, err := httpClient.Get(url)
if err != nil {
return
}
defer httpResp.Body.Close()
if httpResp.StatusCode != http.StatusOK {
return fmt.Errorf("http.Status: %s", httpResp.Status)
}
var result struct {
oauth2.Error
mpoauth2.Session
}
if err = api.DecodeJSONHttpResponse(httpResp.Body, &result, false); err != nil {
return
}
if result.ErrCode != oauth2.ErrCodeOK {
return &result.Error
}
*session = result.Session
return
}
|
[
2
] |
package main
import "fmt"
func FindFirstK(arr []int, k int) int {
length := len(arr) - 1
beg, end := 0, length
for beg <= end {
mid := (beg + end) / 2
if arr[mid] == k {
if (mid > 0 && arr[mid-1] != k) || mid == 0 {
return mid
} else {
end = mid - 1 // todo :找第一个调整尾节点
}
} else if arr[mid] > k {
end = mid - 1
} else {
beg = mid + 1
}
}
return -1
}
func FindLastK(arr []int, k int) int {
length := len(arr) - 1
beg, end := 0, length
for beg <= end {
mid := (beg + end) / 2
if arr[mid] == k {
if (mid < length && arr[mid+1] != k) || mid == length {
return mid
} else {
beg = mid + 1 // todo :找最后一个调整头节点
}
} else if arr[mid] > k {
end = mid - 1
} else {
beg = mid + 1
}
}
return -1
}
func getNumersOfk(arr []int, k int) int {
first := FindFirstK(arr, k)
last := FindLastK(arr, k)
fmt.Println(first, last)
if first != -1 && last != -1 {
return last - first + 1
}
return -1
}
func main() {
arr := []int{1, 3, 5, 7, 9, 9, 9, 9, 12, 34, 35, 57, 90}
n := getNumersOfk(arr, 1)
fmt.Println(n)
}
|
[
5
] |
package main
import (
"os"
"io"
"bufio"
"fmt"
)
func main() {
sum := 0.0
line_reader := bufio.NewReader(os.Stdin)
for {
line, error := line_reader.ReadString('\n')
if ( error != nil ) {
if ( error != io.EOF ) {
fmt.Println(error)
}
break
} else {
var n = 0.0
fmt.Sscanf(line, "%f", &n)
sum = sum + n
}
}
fmt.Printf("%f\n", sum)
}
|
[
0
] |
package config
import (
"github.com/spf13/viper"
)
func InitDefaultConfig(ConfigViper *viper.Viper) {
ConfigViper.SetDefault("Num", 2)
}
|
[
2
] |
// Copyright 2014, Successfulmatch Inc. All rights reserved.
// Author TonyXu<[email protected]>,
// Build on dev-0.0.1
// MIT Licensed
// The Go mysql proxy main model file.
package models
import (
"fmt"
"errors"
"strconv"
"sync"
"log"
"git.masontest.com/branches/gomysqlproxy/app/models/schema"
"git.masontest.com/branches/gomysqlproxy/app/models/host"
"git.masontest.com/branches/gomysqlproxy/app/models/client"
"git.masontest.com/branches/gomysqlproxy/app/models/redis"
"git.masontest.com/branches/gomysqlproxy/app/models/planbuilder"
)
type MysqlProxy struct {
TableTotal uint64
SizeTotal uint64 // 单位:MB
CurGId uint64 // 当前全局表主ID,为新表主ID,不能减少
TableIds []string // 表主ID
Tables []*schema.MysqlTable `json:"-"`
ShardDBIds []string // Shard库的主ID
ShardDBs []*schema.MysqlShardDB `json:"-"` // 已生成的shard库
ShardDBCnt int // shard db 计数器
TablesMap map[string]*schema.MysqlTable `json:"-"`
}
var (
MyProxy *MysqlProxy
isUpdated = false
)
func CheckError(err error) {
if err != nil {
panic(fmt.Sprintf("init the table error in mysql.go: %s", err))
}
}
func NewMysqlProxy() *MysqlProxy {
proxy := &MysqlProxy {}
proxy.Init()
host.GetAndLogHostStatus()
return proxy
}
// To init the necessary data.
func (m *MysqlProxy) Init() {
m.InitMain()
m.InitMysqlDB()
m.InitMysqlTable()
m.InitConnPooling()
if isUpdated {
// save mysql proxy.
err := redis.UpdateDB("main", redis.EncodeData(m), "MysqlProxy")
CheckError(err)
}
// panic(fmt.Sprintf("OK: %#v", m))
}
// get the table status.
func (m *MysqlProxy) GetStatus() (map[string]interface{}, error) {
result := map[string]interface{}{}
result["main"] = redis.EncodeData(m)
tables := []string{}
shardDB := []string{}
for _, table := range m.Tables {
tables = append(tables, redis.EncodeData(table))
}
for _, db := range m.ShardDBs {
shardDB = append(shardDB, redis.EncodeData(db))
}
result["tables"] = tables
result["sharddbs"] = shardDB
return result, nil
}
// restore the main proxy data.
func (m *MysqlProxy) InitMain() {
pr, err := redis.ReadDB("MysqlProxy", "main")
CheckError(err)
if len(pr) == 0 { return }
for _, proxy := range pr {
proxy = proxy["main"].(map[string]interface {})
m.TableTotal = uint64(proxy["TableTotal"].(float64))
m.SizeTotal = uint64(proxy["SizeTotal"].(float64))
m.CurGId = uint64(proxy["CurGId"].(float64))
if ttableIds, isOk := proxy["TableIds"].([]interface{}); isOk && len(ttableIds) > 0 {
m.TableIds = redis.RestorePrimaryId(ttableIds)
} else {
m.TableIds = []string{}
}
if dbIds, isOk := proxy["ShardDBIds"].([]interface{}); isOk && len(dbIds) > 0 {
m.ShardDBIds = redis.RestorePrimaryId(dbIds)
} else {
m.ShardDBIds = []string{}
}
m.ShardDBCnt = int(proxy["ShardDBCnt"].(float64))
schema.ShardDBCnt = m.ShardDBCnt
}
// panic(fmt.Sprintf("%#v", m))
}
// get the current db cluster data infomations
func (m *MysqlProxy) InitMysqlDB() {
// panic(fmt.Sprintf("%#v, %#v", m.ShardDBIds, len(m.ShardDBIds)))
if len(m.ShardDBIds) == 0 {
// init the shard DB
shardDBs := []*schema.MysqlShardDB{}
shardDBIds := []string{}
m.ShardDBCnt = 0
for _, group := range host.Groups {
m.ShardDBCnt++
shardDb, err := m.BuildNewShardDB(&group, "shard" + strconv.Itoa(m.ShardDBCnt))
CheckError(err)
shardDBs = append(shardDBs, shardDb)
shardDBIds = append(shardDBIds, shardDb.Id)
}
m.ShardDBs = shardDBs
m.ShardDBIds = shardDBIds
// to prepare save new data.
isUpdated = true
// add shard dbs map.
schema.Sdbs = shardDBs
} else {
// 分析数据,并恢复至MysqlProxy结构体中.
shardDBs := []*schema.MysqlShardDB{}
for _, sid := range m.ShardDBIds {
dbs, err := redis.ReadDB("MysqlShardDB", sid)
CheckError(err)
if len(dbs) != 1 { panic("no found relation shard db for id:" + sid) }
sdb := dbs[0][sid].(map[string]interface {})
groupId := sdb["HostGroupId"].(string)
curGroup, err := host.GetHostGroupById(groupId)
CheckError(err)
shardDB := &schema.MysqlShardDB{
Id: sdb["Id"].(string),
Name: sdb["Name"].(string),
TableTotal: uint64(sdb["TableTotal"].(float64)),
SizeTotal: uint64(sdb["SizeTotal"].(float64)),
HostGroupId:groupId,
Created: int64(sdb["Created"].(float64)),
HostGroup: curGroup,
}
shardDBs = append(shardDBs, shardDB)
}
m.ShardDBs = shardDBs
// add shard dbs map.
schema.Sdbs = shardDBs
}
// listen the sharddb change status.
locker := &sync.Mutex{}
go func() {
for {
newShardDB := <-schema.NewShardDBCh
locker.Lock()
defer locker.Unlock()
m.ShardDBIds = append(m.ShardDBIds, newShardDB.Id)
m.ShardDBs = append(m.ShardDBs, newShardDB)
schema.Sdbs = m.ShardDBs
err := redis.UpdateDB("main", redis.EncodeData(m), "MysqlProxy")
if err != nil {
log.Printf("new shard db listener error:%s", err)
}
m.ShardDBCnt++
schema.ShardDBCnt = m.ShardDBCnt
fmt.Printf("current shard total: %d\n", schema.ShardDBCnt)
}
}()
// listen the table drop action.
go func() {
for {
dropedTable := <-schema.DropedTableCh
m.DeleteTable(dropedTable)
}
}()
// panic(fmt.Sprintf("in init shard db: %#v, %#v", m))
}
func (m *MysqlProxy) DeleteTable(table *schema.MysqlTable) {
curTables := []*schema.MysqlTable{}
curTableIds := []string{}
for _, one := range m.Tables {
if one.Name != table.Name {
curTables = append(curTables, one)
}
}
for _, one := range m.TableIds {
if one != table.Id {
curTableIds = append(curTableIds, one)
}
}
// delete the relations.
m.TableIds = curTableIds
m.Tables = curTables
err := redis.UpdateDB("main", redis.EncodeData(m), "MysqlProxy")
if err != nil { fmt.Printf("Delete table error when write redis: %s\n", err); return }
schema.Tables = curTables
// delete selfs.
table.Destroy()
}
// to init or restore the table infomation.
func (m *MysqlProxy) InitMysqlTable() {
if len(m.TableIds) == 0 { return }
// 分析数据,并恢复至MysqlProxy结构体中.
tables := []*schema.MysqlTable{}
for _, tid := range m.TableIds {
tbs, err := redis.ReadDB("MysqlTable", tid)
CheckError(err)
if len(tbs) != 1 { panic("no found relation table for id: " + tid) }
tb := tbs[0][tid].(map[string]interface {})
// panic(fmt.Sprintf("%#v", tbs))
shardTbIds := []string{}
if std, isOk := tb["ShardIds"].([]interface{}); isOk && len(std) > 0 {
shardTbIds = redis.RestorePrimaryId(std)
}
shardTb := []*schema.MysqlShardTable{}
table := &schema.MysqlTable{
Id: tb["Id"].(string),
Name: tb["Name"].(string),
CurGId: uint64(tb["CurGId"].(float64)),
RowTotal: uint64(tb["RowTotal"].(float64)),
ShardIds: shardTbIds,
Created: int64(tb["Created"].(float64)),
Shards: shardTb,
}
if len(shardTbIds) > 0 {
// create new shard table
shardTb, err = m.GetShardTableByIds(shardTbIds)
CheckError(err)
table.Shards = shardTb
err = table.RestoreColumnsByDB()
CheckError(err)
}
// fmt.Printf("Init table `%s` done\n", table.Name)
tables = append(tables, table)
}
m.Tables = tables
schema.Tables = m.Tables
}
// to get shard table info.
func (m *MysqlProxy) GetShardTableByIds(ids []string) ([]*schema.MysqlShardTable, error) {
if len(ids) == 0 { return nil, nil }
tables := []*schema.MysqlShardTable{}
for _, id := range ids {
tbs, err := redis.ReadDB("MysqlShardTable", id)
if err != nil { return nil, err }
if len(tbs) != 1 { return nil, errors.New("no found the shard table for id: " + id) }
tb := tbs[0][id].(map[string]interface {})
shardDbId := tb["ShardDBId"].(string)
shardDb,err := m.GetShardDbById(shardDbId)
if err != nil { return nil, err }
shardTable := &schema.MysqlShardTable{
Id: tb["Id"].(string),
Name: tb["Name"].(string),
RowTotal: uint64(tb["RowTotal"].(float64)),
ShardDBId: shardDbId,
Created: int64(tb["Created"].(float64)),
ShardDB: shardDb,
}
tables = append(tables, shardTable)
}
return tables, nil
}
func (m *MysqlProxy) UpdateToRedisDB() error {
return redis.UpdateDB("main", redis.EncodeData(m), "MysqlProxy")
}
// get the shard db by ids.
func (m *MysqlProxy) GetShardDbById(sid string) (*schema.MysqlShardDB, error) {
if sid == "" { return nil, errors.New("Sorry, the shard db id connot is empty") }
sdb, err := redis.ReadDB("MysqlShardDB", sid)
if err != nil { return nil, err }
if len(sdb) != 1 { return nil, errors.New("Load shard db wrong!") }
tsdb := sdb[0][sid].(map[string]interface {})
groupId := tsdb["HostGroupId"].(string)
curGroup, err := host.GetHostGroupById(groupId)
if err != nil { return nil, err }
shardDB := &schema.MysqlShardDB{
Id: tsdb["Id"].(string),
Name: tsdb["Name"].(string),
TableTotal: uint64(tsdb["TableTotal"].(float64)),
SizeTotal: uint64(tsdb["SizeTotal"].(float64)),
HostGroupId:groupId,
Created: int64(tsdb["Created"].(float64)),
HostGroup: curGroup,
}
schema.ShardDBCnt++
return shardDB, nil
}
// to init the connection pooling.
func (m *MysqlProxy) InitConnPooling() {
// because the database/sql support the connection pooling
// so just to use it.
// 这里决定不采用预先就将所有的链接生成,还是使用到时再初始化连接.
}
func (m *MysqlProxy) BuildNewShardDB(group *host.Group, name string) (*schema.MysqlShardDB, error) {
if name == "" { return nil, errors.New("Sorry, can not build the no name databases") }
// init the shard db to host.
master := group.Master[0]
db, err := (&master).ConnToDB("mysql")
if err != nil { return nil, err }
stmt, err := db.Prepare(fmt.Sprintf("CREATE DATABASE `%s` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci", name))
if err != nil { return nil, err }
_, err = stmt.Exec()
if err != nil { return nil, err }
stmt.Close()
shardDbId := redis.BuildPrimaryKey(name, true)
shardDb := &schema.MysqlShardDB{
Id: shardDbId,
Name: name,
TableTotal: 0,
SizeTotal: 0,
HostGroupId: group.Id,
Created: redis.GetCurTime(),
HostGroup: group,
}
// save this new shard database to tracker.
err = redis.WriteDB(shardDbId, redis.EncodeData(shardDb), "MysqlShardDB")
if err != nil { return nil, err }
(&master).CloseDB()
schema.ShardDBCnt++
return shardDb, nil
}
// add a new table to mysql proxy
func (m *MysqlProxy) AddTable(tab *schema.MysqlTable) error {
tables := m.Tables
tableIds := m.TableIds
if tables == nil {
tables = []*schema.MysqlTable{ tab }
tableIds = []string{ tab.Id }
} else {
tables = append(tables, tab)
tableIds = append(tableIds, tab.Id)
}
m.Tables = tables
schema.Tables = tables
m.TableIds = tableIds
return m.UpdateToRedisDB()
}
// to exel the sql
func (m *MysqlProxy) Exec(args []string, user *client.Client) (interface{}, error) {
execPlan, err := planbuilder.GetExecPlan(args, user)
if err != nil { return nil, err }
result, err := execPlan.Do()
if err != nil { return nil, err }
switch result.(type) {
case *schema.MysqlTable:
err = m.AddTable(result.(*schema.MysqlTable))
if err == nil { result = "create succesfully!" }
}
return result, err
}
// to execute exeplan
// func (m *MysqlProxy) DoExecPlan(plan *planbuilder.ExecPlan
|
[
7
] |
package controller
import (
"context"
"time"
"go.uber.org/zap"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
)
type Controller struct {
PodNamespace string
Client *kubernetes.Clientset
Filter PodFilter
InformerFactory informers.SharedInformerFactory
Logger *zap.Logger
RebuildSettings *RebuildSettings
CTX context.Context
CreateNew bool
CalcCount int
}
type PodFilter struct {
annotation string
namespace string
}
type RebuildSettings struct {
PodCount int
MinioUser string
MinioPassword string
ProcessImage string
MinioEndpoint string
JaegerHost string
JaegerPort string
JaegerOn string
ProcessPodCpuRequest string
ProcessPodCpuLimit string
ProcessPodMemoryRequest string
ProcessPodMemoryLimit string
MessageBrokerUser string
MessageBrokerPassword string
}
func NewPodController(logger *zap.Logger, podNamespace string, rs *RebuildSettings) (*Controller, error) {
config, err := rest.InClusterConfig()
if err != nil {
return nil, err
}
client, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, err
}
filter := PodFilter{
annotation: "rebuild-pod",
namespace: podNamespace,
}
informerFactory := informers.NewSharedInformerFactoryWithOptions(client, 0, informers.WithNamespace(podNamespace))
if err != nil {
return nil, err
}
controller := &Controller{
PodNamespace: podNamespace,
Client: client,
Filter: filter,
InformerFactory: informerFactory,
Logger: logger,
RebuildSettings: rs,
}
return controller, nil
}
func (c *Controller) Run() {
c.Logger.Info("Starting the controller")
go c.createInitialPods()
informer := c.InformerFactory.Core().V1().Pods().Informer()
informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: c.handleSchedAdd,
UpdateFunc: c.recreatePod,
DeleteFunc: c.handleSchedDelete,
})
informer.Run(c.CTX.Done())
<-c.CTX.Done()
}
func (c *Controller) createInitialPods() {
nestedloop := 0
sleepnum := 2 // Second
c.CalcCount = c.RebuildSettings.PodCount
for {
c.CreateNew = false
count := c.podCount("status.phase=Running", "manager=podcontroller")
count += c.podCount("status.phase=Pending", "manager=podcontroller")
for i := 0; i < c.RebuildSettings.PodCount-count; i++ {
c.CreatePod()
}
c.CalcCount = count
c.CreateNew = true
if nestedloop > 60 {
nestedloop = 0
// Create a pod interface for the given namespace
podInterface := c.Client.CoreV1().Pods(c.PodNamespace)
// List the pods in the given namespace
podList, err := podInterface.List(c.CTX, metav1.ListOptions{LabelSelector: "manager=podcontroller"})
if err != nil {
c.Logger.Sugar().Warnf("Initia Running error : %v", err)
}
for _, pod := range podList.Items {
// Calculate the age of the pod
podCreationTime := pod.GetCreationTimestamp()
age := time.Since(podCreationTime.Time).Round(time.Second)
Duration, _ := time.ParseDuration(age.String())
// Get the status of each of the pods
podStatus := pod.Status
if podStatus.Phase == "Running" || podStatus.Phase == "Pending" || podStatus.Phase == "ContainerCreating" {
if Duration > time.Duration(180)*time.Second {
if podStatus.Phase == "Pending" || podStatus.Phase == "ContainerCreating" {
c.Logger.Sugar().Infof(" Duration delete: %v", Duration)
c.Client.CoreV1().Pods(pod.ObjectMeta.Namespace).Delete(c.CTX, pod.ObjectMeta.Name, metav1.DeleteOptions{})
}
}
continue
} else {
c.Client.CoreV1().Pods(pod.ObjectMeta.Namespace).Delete(c.CTX, pod.ObjectMeta.Name, metav1.DeleteOptions{})
}
}
}
time.Sleep(time.Duration(sleepnum) * time.Second)
nestedloop = nestedloop + sleepnum
}
}
func (c *Controller) handleSchedAdd(newObj interface{}) {
c.Logger.Sugar().Infof("handleSchedAdd is : %v", newObj)
pod := newObj.(*v1.Pod)
c.Logger.Sugar().Infof("new pod status : %v", pod.Status.Phase)
}
func (c *Controller) recreatePod(oldObj, newObj interface{}) {
podold := oldObj.(*v1.Pod)
pod := newObj.(*v1.Pod)
if pod.Status.Phase == "Running" || pod.Status.Phase == "Pending" {
return
}
if c.CreateNew {
if c.CalcCount < c.RebuildSettings.PodCount {
c.CreatePod()
}
}
if (pod.ObjectMeta.Labels["manager"] == "podcontroller") && c.isPodUnhealthy(pod) {
go c.deletePod(pod)
return
}
if (podold.ObjectMeta.Labels["manager"] == "podcontroller") && c.isPodUnhealthy(podold) {
go c.deletePod(podold)
return
}
if c.okToRecreate(pod) {
go c.deletePod(pod)
if c.CreateNew {
c.CalcCount = c.CalcCount - 1
}
return
}
if c.okToRecreate(podold) {
go c.deletePod(podold)
return
}
}
func (c *Controller) okToRecreate(pod *v1.Pod) bool {
return (pod.ObjectMeta.Labels["manager"] == "podcontroller") && // we need to filter out just rebuild pods
(c.isPodUnhealthy(pod) || // which are either unhealthy
(pod.Status.Phase == "Succeeded" || pod.Status.Phase == "Failed" || pod.Status.Phase == "Unknown")) // Or completed
}
func (c *Controller) isPodUnhealthy(pod *v1.Pod) bool {
// Check if any of Containers is in CrashLoop
statuses := append(pod.Status.InitContainerStatuses, pod.Status.ContainerStatuses...)
for _, containerStatus := range statuses {
if containerStatus.RestartCount >= 5 {
if containerStatus.State.Waiting != nil && containerStatus.State.Waiting.Reason == "CrashLoopBackOff" {
return true
}
}
}
return false
}
func (c *Controller) handleSchedDelete(obj interface{}) {
pod := obj.(*v1.Pod)
c.Logger.Sugar().Warnf("delete pod name is : %v", pod.Name)
c.Logger.Sugar().Infof("delete pod status : %v", pod.Status.Phase)
}
func (c *Controller) deletePod(pod *v1.Pod) error {
if pod.ObjectMeta.Labels["manager"] == "podcontroller" {
c.Logger.Info("Deleting pod", zap.String("podName", pod.ObjectMeta.Name))
return c.Client.CoreV1().Pods(pod.ObjectMeta.Namespace).Delete(c.CTX, pod.ObjectMeta.Name, metav1.DeleteOptions{})
} else {
c.Logger.Sugar().Warnf("can not delete pod name is : %v its not bleong to podcontroller", pod.Name)
return nil
}
}
|
[
0
] |
package integration
import (
"errors"
"time"
"github.com/fresh8/go-cache/cacher"
)
func RunSuite(cache cacher.Cacher) error {
expectedData := []byte("initial value")
missCount := 0
regen := func() ([]byte, error) {
missCount = missCount + 1
return expectedData, nil
}
if missCount != 0 {
return errors.New("cache miss should be 0 when not called")
}
data, err := cache.Get("example-thing", time.Now().Add(5*time.Second), regen)()
if missCount != 1 {
return errors.New("cache miss should be 1 on first call")
}
if string(data) != string(expectedData) {
return errors.New("returned data does not match expected data")
}
data, err = cache.Get("example-thing", time.Now().Add(5*time.Second), regen)()
if missCount != 1 {
return errors.New("cache miss should be 1 on second call within 5 seconds")
}
if string(data) != string(expectedData) {
return errors.New("returned data does not match expected data")
}
err = cache.Expire("example-thing")
if err != nil {
return err
}
data, err = cache.Get("example-thing", time.Now().Add(5*time.Second), regen)()
if missCount != 2 {
return errors.New("cache miss should be 2 on call post-expire")
}
if string(data) != string(expectedData) {
return errors.New("returned data does not match expected data")
}
newExpectedData := []byte("new data")
regen = func() ([]byte, error) {
missCount = missCount + 1
return newExpectedData, nil
}
time.Sleep(6 * time.Second)
data, err = cache.Get("example-thing", time.Now().Add(5*time.Second), regen)()
time.Sleep(1 * time.Second)
if missCount != 3 {
return errors.New("cache miss should be 3 on call post-expire")
}
if string(data) != string(expectedData) {
return errors.New("returned data should be stale")
}
data, err = cache.Get("example-thing", time.Now().Add(5*time.Second), regen)()
if missCount != 3 {
return errors.New("cache miss should still be 3 after new regen")
}
if string(data) != string(newExpectedData) {
return errors.New("returned data should not be stale")
}
return nil
}
|
[
0
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.