Example #1
0
func TestParseInfo(t *testing.T) {
	expectations := map[string]*TVNameParseResult{
		"Sleepy.Hollow.S03E01.720p.HDTV.x264-AVS": {
			Name:        "Sleepy Hollow",
			CleanedName: "Sleepy Hollow S03E01 720p HDTV x264-AVS",
			Country:     "",
			Episode:     "1",
			Season:      "3",
			Airdate:     "",
		},
		"NBC.Nightly.News.2016.02.17.WEB-DL.x264-2Maverick": {
			Name:        "NBC Nightly News",
			CleanedName: "NBC Nightly News 2016 02 17 WEB-DL x264-2Maverick",
			Country:     "",
			Episode:     "02/17",
			Season:      "2016",
			Airdate:     "2016.02.17",
		},
	}
	for name, v := range expectations {
		res, err := ParseInfo(name)
		if err != nil {
			t.Fatalf("Error %v", err)
		}
		if !reflect.DeepEqual(v, res) {
			t.Errorf("Diff in Parse output for %s", name)
			fmt.Println("Expected:")
			spew.Dump(v)
			fmt.Println("Got:")
			spew.Dump(res)
		}
	}
}
Example #2
0
func main() {
	fileSet := token.NewFileSet()
	astFile, err := parser.ParseFile(fileSet, "minimal.go", nil, parser.ParseComments)
	if err != nil {
		panic(err)
	}
	ast.Print(fileSet, astFile)

	return

	astFile.Decls = append(astFile.Decls[:0], append([]ast.Decl{&ast.FuncDecl{
		Name: ast.NewIdent("MyNewFunc"),
		Type: &ast.FuncType{
			Func: 15,
			Params: &ast.FieldList{
				Opening: 29,
				Closing: 30,
			},
		},
	}}, astFile.Decls[0:]...)...)

	offset := astFile.Decls[0].End() - astFile.Decls[0].Pos()
	intoffset := int(offset)
	fmt.Println("offset", offset)
	astFile.Comments[0].List[0].Slash += offset
	// astFile.Comments[0].List[0].Slash = 18
	astFile.Decls[1].(*ast.GenDecl).TokPos += offset
	astFile.Decls[1].(*ast.GenDecl).Lparen += offset
	astFile.Decls[1].(*ast.GenDecl).Rparen += offset
	fileSetFile := fileSet.File(1)
	newFileSet := token.NewFileSet()
	newFileSetFile := newFileSet.AddFile("whatever", 1, fileSetFile.Size()+int(offset))
	newFileSetFile.SetLines([]int{
		0,
		13,
		14,
		15,
		15 + intoffset,
		20 + intoffset,
		21 + intoffset,
		32 + intoffset,
		33 + intoffset,
	}) // hardcoded for now

	fmt.Println("astFile:")
	spew.Dump(astFile)
	fmt.Println()
	fmt.Println()
	fmt.Println("fileSet:")
	spew.Dump(fileSet)
	buf := new(bytes.Buffer)

	err = printer.Fprint(buf, newFileSet, astFile)
	if err != nil {
		panic(err)
	}

	fmt.Println(buf)

}
func (c *ColorChannel) SetColor(state *channels.ColorState) error {

	if state.Mode != "hue" {
		return fmt.Errorf("TODO: Only color mode 'hue' is supported atm.")
	}

	spew.Dump("setting color", state)

	hue := uint32(*state.Hue * float64(math.MaxUint8-1))
	saturation := uint32(*state.Saturation * float64(math.MaxUint8-1))

	request := &gateway.DevSetColorReq{
		DstAddress: &gateway.GwAddressStructT{
			AddressType: gateway.GwAddressTypeT_UNICAST.Enum(),
			IeeeAddr:    c.device.deviceInfo.IeeeAddress,
		},
		HueValue:        &hue,
		SaturationValue: &saturation,
	}

	spew.Dump(request)

	response := &gateway.GwZigbeeGenericRspInd{}
	err := c.device.driver.gatewayConn.SendAsyncCommand(request, response, 2*time.Second)
	if err != nil {
		return fmt.Errorf("Error setting color state : %s", err)
	}
	if response.Status.String() != "STATUS_SUCCESS" {
		return fmt.Errorf("Failed to set color state. status: %s", response.Status.String())
	}

	return c.fetchState()
}
Example #4
0
func ReadBinlog(reader io.Reader) (err error) {
	c := &proto.BufReader{Reader: bufio.NewReader(reader)}
	buf := &bytes.Buffer{}
	r := &proto.BufReader{Reader: bufio.NewReader(buf)}
	tmp := make([]byte, 4)
	_, err = c.Read(tmp)
	if err != nil {
		return
	}

	// http://dev.mysql.com/doc/internals/en/binlog-file-header.html
	if bytes.Compare(tmp, []byte{0xfe, 0x62, 0x69, 0x6e}) != 0 {
		err = ErrFileHeader
		return
	}

	h := &EventHeader{}
	h.Read(c)
	spew.Dump(h)
	_, err = io.CopyN(buf, c, int64(h.EventSize))
	if err != nil {
		panic(err)
	}
	f := &FormatDescriptionEvent{}
	f.Read(r)
	spew.Dump(f)
	return
}
Example #5
0
func main() {
	parser := yasha.ParserFromFile("/home/manveru/Dropbox/Public/d2rp_test_replays/813230338.dem")
	parser.OnFileInfo = func(fileinfo *dota.CDemoFileInfo) { spew.Dump(fileinfo) }
	parser.OnSayText2 = func(tick int, obj *dota.CUserMsg_SayText2) { spew.Dump(tick, obj) }
	parser.OnChatEvent = func(tick int, obj *dota.CDOTAUserMsg_ChatEvent) { spew.Dump(tick, obj) }
	parser.Parse()
}
Example #6
0
func TestPubKeys(t *testing.T) {
	for _, test := range pubKeyTests {
		pk, err := btcec.ParsePubKey(test.key, btcec.S256())
		if err != nil {
			if test.isValid {
				t.Errorf("%s pubkey failed when shouldn't %v",
					test.name, err)
			}
			continue
		}
		if !test.isValid {
			t.Errorf("%s counted as valid when it should fail",
				test.name)
			continue
		}
		var pkStr []byte
		switch test.format {
		case btcec.TstPubkeyUncompressed:
			pkStr = (*btcec.PublicKey)(pk).SerializeUncompressed()
		case btcec.TstPubkeyCompressed:
			pkStr = (*btcec.PublicKey)(pk).SerializeCompressed()
		case btcec.TstPubkeyHybrid:
			pkStr = (*btcec.PublicKey)(pk).SerializeHybrid()
		}
		if !bytes.Equal(test.key, pkStr) {
			t.Errorf("%s pubkey: serialized keys do not match.",
				test.name)
			spew.Dump(test.key)
			spew.Dump(pkStr)
		}
	}
}
Example #7
0
func main() {
	a := []interface{}{1, 1.1, "abc", 2, 2.2, "def", 3, 3.3}
	fmt.Println(sumOfArray(a))
	fmt.Println(sumOfFloat(a))

	fmt.Printf("\n--- omake ---\n\n")
	masano := newHuman("masano")
	dog := newAnimal("pochi")
	monster := newMonster("godzilla")

	var g greeter
	g = masano
	ret1, ok1 := g.(greeter) // greeter を実装しているかチェック。
	spew.Dump(ret1, ok1)
	g.greet()

	fmt.Println()
	g = dog
	ret2, ok2 := g.(*animal) // animal 構造体かどうかチェック。メソッドレシーバが *animal なのでここは *animal になるっぽい。よくわからんが。
	spew.Dump(ret2, ok2)
	g.greet()

	fmt.Println()
	// インターフェースじゃなかったらキャストすればよい。
	ret3, ok3 := interface{}(monster).(greeter)     // greeter を実装しているかチェック。
	ret4, ok4 := interface{}(monster.name).(string) // monster.name は string かチェック。
	spew.Dump(ret3, ok3, ret4, ok4)
}
Example #8
0
func main() {
	var a Figure = newTriangle(10, 10) // Triangle 構造体はインタフェース Figure を実装しているので、Figure 型になれる。
	fmt.Println(a.kindOf())
	fmt.Println(a.area())
	a.print()

	// 以下の図形も同様。
	var b Figure = newRectangle(10, 10)
	fmt.Println(b.kindOf())
	fmt.Println(b.area())
	b.print()

	c := newCircle(100) // この場合は何型なんだ?
	fmt.Println(c.kindOf())
	fmt.Println(c.area())
	c.print()

	fmt.Println()
	spew.Dump(a, b, c) // 別に Figure 型になる、というわけではないのか。
	fmt.Println()

	var interfaced Figure
	interfaced = newTriangle(1, 1)
	spew.Dump(interfaced) // 明示的にインターフェース型の変数を用意してそれに代入しても、Triangle 型は Triangle 型のようだ。
	fmt.Println()

	// 各図形は Figure インターフェースを実装した Figure 型だぜ。
	// これで sumOfArea() が使えるぜ。
	var figures []Figure = []Figure{a, b, c}
	// やったぜ。
	fmt.Println(sumOfArea(figures))
}
Example #9
0
func (c *Client) SetTags(uid string, fields map[string]interface{}) error {
	session := c.MgoSession.New()
	defer session.Close()

	store := session.DB(c.Cfg.Mongo.Db).C("Storage")

	fields["version"] = 0
	timestamp := int64(time.Now().Unix() / 1000)
	change := mgo.Change{
		Update: bson.M{
			"$set": bson.M{"last_visit": timestamp},
			"$inc": bson.M(fields),
		},
		ReturnNew: true,
		Upsert:    true,
	}
	resultUps := Storage{}
	info, err := store.Find(bson.M{"uid": uid}).Apply(change, &resultUps)

	if c.Debug {
		fmt.Print("set tags info: ")
		spew.Dump(info)
		fmt.Print("resultUps: ")
		spew.Dump(resultUps)
	}

	if err != nil {
		panic(err)
	}

	return nil
}
Example #10
0
func TestWidth(t *testing.T) {
	s0 := "つのだ☆HIRO"
	s1 := "11111111111"
	spew.Dump(s0)
	spew.Dump(s1)
	// above not align for setting East Asian Ambiguous to wide!!

	if strWidth(s0) != strWidth(s1) {
		t.Error("str len failed")
	}

	len1 := []rune{'a', '2', '&', '「', 'オ', '。'} //will false: 'ᆵ', 'ᄚ', 'ᄒ'
	for _, v := range len1 {
		if charWidth(v) != 1 {
			t.Error("len1 failed")
		}
	}

	len2 := []rune{'漢', '字', '한', '자', '你', '好', 'だ', '。', '%', 's', 'E', 'ョ', '、', 'ヲ'}
	for _, v := range len2 {
		if charWidth(v) != 2 {
			t.Error("len2 failed")
		}
	}
}
Example #11
0
func TestReplSetGetStatusResponseRewriterSuccess(t *testing.T) {
	proxyMapper := fakeProxyMapper{
		m: map[string]string{
			"a": "1",
			"b": "2",
			"c": "3",
		},
	}
	in := bson.M{
		"members": []interface{}{
			bson.M{
				"name":     "a",
				"stateStr": "PRIMARY",
			},
			bson.M{
				"name": "b",
			},
			bson.M{
				"name":     "c",
				"stateStr": "ARBITER",
			},
		},
	}
	out := bson.M{
		"members": []interface{}{
			bson.M{
				"name":     "1",
				"stateStr": "PRIMARY",
			},
			bson.M{
				"name": "2",
			},
			bson.M{
				"name":     "3",
				"stateStr": "ARBITER",
			},
		},
	}
	r := &ReplSetGetStatusResponseRewriter{
		ProxyMapper: proxyMapper,
		ReplyRW:     &ReplyRW{},
	}

	var client bytes.Buffer
	if err := r.Rewrite(&client, fakeSingleDocReply(in)); err != nil {
		t.Fatal(err)
	}
	actualOut := bson.M{}
	doc := client.Bytes()[headerLen+len(emptyPrefix):]
	if err := bson.Unmarshal(doc, &actualOut); err != nil {
		t.Fatal(err)
	}
	if !reflect.DeepEqual(out, actualOut) {
		spew.Dump(out)
		spew.Dump(actualOut)
		t.Fatal("did not get expected output")
	}
}
Example #12
0
func main() {
	a := "hello, world"
	b := []byte{'h', 'y'}
	// byte スライスは ASCII 文字しかダメってこと?
	// でも file.go はちゃんとできてるぞ?
	// c := []byte{'你', '你'}
	// あー違う、文字列を []byte にするんだから、こうだ。
	c := []byte("你好")

	fmt.Printf("[%s]\n", a)
	fmt.Printf("[%20s]\n", a)
	fmt.Printf("[%-20s]\n", a)
	fmt.Printf("[%q]\n", a)
	fmt.Printf("[%20q]\n", a)
	fmt.Printf("[%-20q]\n", a)

	fmt.Printf("[%s]\n", b)
	fmt.Printf("[%20s]\n", b)
	fmt.Printf("[%-20s]\n", b)
	fmt.Printf("[%q]\n", b)
	fmt.Printf("[%20q]\n", b)
	fmt.Printf("[%-20q]\n", b)

	fmt.Printf("[%s]\n", c)
	fmt.Printf("[%20s]\n", c)
	fmt.Printf("[%-20s]\n", c)
	fmt.Printf("[%q]\n", c)
	fmt.Printf("[%20q]\n", c)
	fmt.Printf("[%-20q]\n", c)

	// "你好" はたぶん 1 文字 3 byte なんですかね。
	fmt.Println()
	fmt.Println("你好 な []byte をループで回す")
	for _, v := range c {
		spew.Dump(v)
	}

	// ふむふむ!
	// 文字(列)は []byte (uint8: 0 - 255) である。
	// 16 進数表記に直したらご覧の通りです!
	fmt.Println()
	fmt.Println("你を 16 進数で")
	fmt.Printf("%x\n", "你")
	fmt.Println("你の []byte を 16 進数で")
	fmt.Printf("%x %x %x\n", c[0], c[1], c[2])

	// で、rune ってのはコードポイント(Unicode 規格における、その文字の ID みたいなもん)を int32 な値で示している。
	// コードポイントの文脈では、16 進数な rune 値がコードポイントになる。
	// たとえば '你' は int32: 20320 で 16 進数だと 4f60 である。
	// コードポイントはつまり、U+4f60 となる。
	fmt.Println()
	fmt.Println("你 の rune")
	spew.Dump('你')
	fmt.Println("你 の rune を 16 進数で")
	fmt.Printf("%x\n", '你')
	fmt.Println("你 の rune をコードポイントで")
	fmt.Printf("%U\n", '你')
}
Example #13
0
// Test groups creation
func testScaled(t *testing.T) {
	//Init
	RemoveAllGroups()
	RemoveAllPriceRules()
	groupID := "ProductsToScale"
	//createGroup
	group := new(Group)
	group.Type = ProductGroup
	group.ID = groupID
	group.Name = groupID

	//create pricerule
	priceRule := NewPriceRule(PriceRuleIDSale)
	priceRule.Name = map[string]string{
		"de": PriceRuleIDSale,
		"fr": PriceRuleIDSale,
		"it": PriceRuleIDSale,
	}
	priceRule.Type = TypePromotionOrder
	priceRule.Description = priceRule.Name
	priceRule.Action = ActionScaled

	priceRule.ScaledAmounts = append(priceRule.ScaledAmounts, ScaledAmountLevel{FromValue: 100.0, ToValue: 150.0, Amount: 10, IsScaledAmountPercentage: true})
	priceRule.ScaledAmounts = append(priceRule.ScaledAmounts, ScaledAmountLevel{FromValue: 150.01, ToValue: 100000.0, Amount: 50, IsScaledAmountPercentage: true})

	priceRule.MaxUses = 10
	priceRule.MaxUsesPerCustomer = 10
	priceRule.WhichXYFree = XYCheapestFree
	priceRule.IncludedProductGroupIDS = []string{groupID}
	priceRule.IncludedCustomerGroupIDS = []string{}

	//insert as well
	group.AddGroupItemIDs([]string{ProductID1SKU1})

	err := group.Upsert()
	if err != nil {
		log.Println(err)
	}

	//create order
	orderVo, err := createMockOrderScaled(t)
	if err != nil {
		panic(err)
	}

	now := time.Now()
	discountsVo, summary, err := ApplyDiscounts(orderVo, []string{""}, "", 0.05)
	timeTrack(now, "Apply scaled voucher")
	defer removeOrder(orderVo)
	if err != nil {
		panic(err)
	}

	fmt.Println("discounts for scaled percentage")
	spew.Dump(discountsVo)
	spew.Dump(*summary)
}
Example #14
0
func TestCanvasUnset(t *testing.T) {
	c := NewCanvas()
	c.Set(0, 0)
	c.Set(0, 1)
	c.Set(0, 2)
	c.Unset(0, 2)
	spew.Dump(c)
	c.Unset(0, 3)
	spew.Dump(c)
}
Example #15
0
func main() {
	fmt.Println("Welcome to huexample")

	brokerDetailsSlice, err := hue.DiscoverBridges()
	if err != nil {
		fmt.Println("Error while discovering bridges:", err)
		return
	}

	if len(brokerDetailsSlice) == 0 {
		fmt.Println("No bridge details found. Stopping.")
		return
	}

	fmt.Printf("Found %d bridges:\n", len(brokerDetailsSlice))
	spew.Dump(brokerDetailsSlice)

	fmt.Printf("Continueing with first bridge found, id: %s\n", brokerDetailsSlice[0].ID)

	fmt.Println("Going to create user with empty username, bridge will generate a username.")
	bridge := hue.NewBridge(brokerDetailsSlice[0].InternalIPAddress)
	newUsername, err := bridge.CreateNewUser("huexample", "")
	if err != nil {
		fmt.Printf("have error: %s\n", err)
		return
	}
	fmt.Printf("Successfully created new user. Got username: %s\n", newUsername)

	// update the Username field on Bridge instance with the user we just created
	bridge.Username = newUsername

	bridgeConfiguration, err := bridge.FetchConfiguration()
	if err != nil {
		fmt.Printf("have error: %s\n", err)
		return
	}

	fmt.Printf("Bridge name is '%s'.\n", bridgeConfiguration.Name)
	fmt.Printf("Bridge has %d users.\n", len(bridgeConfiguration.Whitelist))

	lights, err := bridge.Lights()
	if err != nil {
		fmt.Printf("have error: %s\n", err)
		return
	}
	fmt.Printf("Have %d lights.\n", len(lights))

	spew.Dump(lights[0].Attributes())

	// err = lights[0].SetName("Lange lamp")
	// if err != nil {
	// 	fmt.Printf("Have error: %s\n", err)
	// }

}
Example #16
0
func checkBlock(client *btcrpcclient.Client, blockNum int64) {
	blockHash, err := client.GetBlockHash(653895)
	if err != nil {
		logger.Crit(err.Error())
		return
	}
	block, err := client.GetBlock(blockHash)
	if err != nil {
		logger.Crit(err.Error())
		return
	}

	txs := block.Transactions()

	var processedBlock = &message.ProcessedBlock{make([]*message.ProcessedTx, len(txs))}

	logger.Info("Processing txs...")
	for txIndex, tx := range txs {
		vouts := tx.MsgTx().TxOut
		result := make([]*message.TxResult, len(vouts))
		for i, vout := range vouts {
			addr := NewAddrFromPkScript(vout.PkScript, true)
			if addr != nil {
				result[i] = &message.TxResult{
					&message.TxResult_Transfer{
						&message.ValueTransfer{
							addr.String(),
							int32(vout.Value),
						},
					},
				}
			} else {
				result[i] = &message.TxResult{
					&message.TxResult_Msg{
						&message.OpReturnMsg{string(decodePkScript(vout.PkScript))},
					},
				}
			}
		}
		processedBlock.Txs[txIndex] = &message.ProcessedTx{
			tx.Sha().String(),
			result,
		}
	}
	spew.Dump(processedBlock)
	data, err := proto.Marshal(processedBlock)
	if err != nil {
		logger.Crit(err.Error())
	} else {
		logger.Info("Publish to ZMQ...")
		spew.Dump(sender)
		sender.SendBytes(data, 0)
	}
	logger.Info("Process done.")
}
Example #17
0
func TestFileCreate(t *testing.T) {
	client := cuckoo.NewClientWithBasicAuthentication("https://localhost/api", "user", "password")

	res, err := client.FileCreate("pafish.exe")
	if err != nil {
		spew.Dump(err)
		t.Fail()
	}

	spew.Dump(res)
}
Example #18
0
func main() {
	dropbox.Debug = true

	client, err := dropbox.NewClient(dropbox.ClientOptions{
		Key:    config.Application.Key,
		Secret: config.Application.Secret,
		Token:  config.BearerToken.Token,
		Uid:    config.BearerToken.UserId,
		Root:   "sandbox",
	})

	failIf(err)

	datastoreManager := client.GetDatastoreManager()

	{ // demo OpenDefaultDatastore
		println("calling datastoreManager.OpenDefaultDatastore")
		ds, err := datastoreManager.OpenDefaultDatastore()
		failIf(err)
		spew.Dump(ds)
		print("\n\n")
	}

	{ // demo ListDatastores
		println("calling datastoreManager.ListDatastores")
		infos, err := datastoreManager.ListDatastores()
		failIf(err)
		spew.Dump(infos)
		print("\n\n")
	}

	{ // demo DeleteDatastore
		println("calling datastoreManager.DeleteDatastore")
		err = datastoreManager.DeleteDatastore("default")
		failIf(err)
		print("\n\n")
	}

	{ // demo CreateDatastore and DeleteDatastore
		println("calling datastoreManager.CreateDatastore")
		ds, err := datastoreManager.CreateDatastore()
		failIf(err)
		spew.Dump(ds)

		println("calling datastoreManager.DeleteDatastore")
		err = datastoreManager.DeleteDatastore(ds.GetId())
		failIf(err)

		print("\n\n")
	}

	println("DatastoreManager smoke test finished!")
}
Example #19
0
func callBackUser(id int, endpoint string) {
	spew.Dump(id)
	spew.Dump(endpoint)
	anaconda.SetConsumerKey(CONSUMER_KEY)
	anaconda.SetConsumerSecret(CONSUMER_SECRET)
	api := anaconda.NewTwitterApi(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
	_, err := api.PostDMToUserId(endpoint, int64(id))
	//spew.Dump(message)
	if err != nil {
		spew.Dump(err)
	}
}
Example #20
0
func main() {
	var p Point
	var q Point = Point{10, 10}
	r := Point{x: 100, y: 100}

	spew.Dump(p, q, r)
	spew.Dump(p.x, p.y, q.x, q.y, r.x, r.y)

	spew.Println(distance(p, q))
	spew.Println(distance(p, r))
	spew.Println(distance(q, r))
}
func main() {
	//* '''os.Args''' は非加工のコマンドライン引数へのアクセスを提供します。このスライスの最初の値はプログラムへのパスであり、'''os.Args[1:]''' がプログラムに対する引数を保持している点に注意してください。
	argsWithProg := os.Args
	argsWithoutProg := os.Args[1:]

	//* あなたは通常のインデックスと同様に個々の引数を取得できます。
	arg := os.Args[3] // これ引数が 2 個以下なら panic じゃん。
	spew.Println(arg)

	spew.Dump(argsWithProg)
	spew.Dump(argsWithoutProg)
}
Example #22
0
func main() {
	a := 10
	b := 20
	c := [8]int{1, 2, 3, 4, 5, 6, 7, 8}

	spew.Dump(a, b, c)

	swap(&a, &b)
	timesArray(10, &c)

	spew.Dump(a, b, c)
}
Example #23
0
func (model *NagelSchreckenberg) SimulateStep() {
	var vehicle *Vehicle
	spew.Dump(model)
	for i, zone := range model.zones {
		vehicle = zone.vehicle
		if vehicle != nil {
			// Step 1: Increase velocity by a unit
			if vehicle.velocity < model.maxSpeed {
				vehicle.velocity++
			}
			// Step 2: If velocity > distance to next car,
			// reduce velocity by a unit to avoid collision.
			y := i + 1
			for model.zones[y].vehicle == nil {
				if y == len(model.zones)-1 {
					y = 0
				} else {
					y++
				}
			}
			if vehicle.velocity >= (y - i) {
				vehicle.velocity--
			}
			// Step 3: if velocity > 0 decrease with probability pDecrease
			randGen := rand.New(rand.NewSource(time.Now().UnixNano()))
			p := randGen.Float64()
			if p <= model.pDecrease && vehicle.velocity > 0 {
				vehicle.velocity--
			}
		}
	}
	fmt.Println()
	spew.Dump(model)
	fmt.Println()
	// Step 4: All vehicles move ahead by their velocity in parallel
	for i, zone := range model.zones {
		vehicle = zone.vehicle
		if vehicle == nil {
			continue
		}
		moveTo := i + vehicle.velocity
		if moveTo > len(model.zones)-1 {
			moveTo = moveTo - len(model.zones)
		}
		if moveTo > 0 {
			model.zones[moveTo].vehicle = vehicle
			model.zones[i].vehicle = nil
		}
	}
	spew.Dump(model)
	fmt.Println()
}
Example #24
0
func main() {
	fileSet := token.NewFileSet()
	astFile, err := parser.ParseFile(fileSet, os.Args[1], nil, parser.ParseComments)
	if err != nil {
		panic(err)
	}
	spew.Config.ContinueOnMethod = true
	spew.Dump(fileSet)
	fmt.Println()
	fmt.Println()
	fmt.Println()
	spew.Dump(astFile)
}
Example #25
0
func (c *MediaController) GetStatus(timeout time.Duration) ([]*MediaStatus, error) {

	spew.Dump("getting media Status")

	message, err := c.channel.Request(&getMediaStatus, timeout)
	if err != nil {
		return nil, fmt.Errorf("Failed to get receiver status: %s", err)
	}

	spew.Dump("got media Status", message)

	return c.onStatus(message)
}
Example #26
0
func main() {
	m := 10
	n := 20
	var p *int = &m
	var q *int = &n
	spew.Dump(m, p, n, q)

	*p = 100
	spew.Dump(m, p)

	fmt.Println(p == q)
	fmt.Println(p != q)
}
Example #27
0
func main() {
	client := &userstream.Client{
		ConsumerKey:       CONSUMER_KEY,
		ConsumerSecret:    CONSUMER_SECRET,
		AccessToken:       ACCESS_TOKEN,
		AccessTokenSecret: ACCESS_TOKEN_SECRET,
	}

	client.UserStream(func(event interface{}) {
		spew.Dump(event)
		switch event.(type) {
		case *twitter.Tweet:
			tweet := event.(*twitter.Tweet)
			fmt.Printf("%s: %s\n", tweet.User.ScreenName, tweet.Text)
		case *userstream.Delete:
			tweetDelete := event.(*userstream.Delete)
			fmt.Printf("[delete] %d\n", tweetDelete.Id)
		case *userstream.Favorite:
			favorite := event.(*userstream.Favorite)
			fmt.Printf("[favorite] %s => %s : %s\n",
				favorite.Source.ScreenName, favorite.Target.ScreenName, favorite.TargetObject.Text)
		case *userstream.Unfavorite:
			unfavorite := event.(*userstream.Unfavorite)
			fmt.Printf("[unfavorite] %s => %s : %s\n",
				unfavorite.Source.ScreenName, unfavorite.Target.ScreenName, unfavorite.TargetObject.Text)
		case *userstream.Follow:
			follow := event.(*userstream.Follow)
			fmt.Printf("[follow] %s => %s Id:%d\n", follow.Source.ScreenName, follow.Target.ScreenName, follow.Target.Id)
			//			time.Sleep(time.Millisecond * 6000)
			user, er := client.FollowUserId(follow.Source.Id)
			if er != nil {
				spew.Dump(er)
			} else {
				spew.Dump(user)
			}
		case *userstream.Unfollow:
			unfollow := event.(*userstream.Unfollow)
			fmt.Printf("[unfollow] %s => %s\n", unfollow.Source.ScreenName, unfollow.Target.ScreenName)
		case *userstream.ListMemberAdded:
			listMemberAdded := event.(*userstream.ListMemberAdded)
			fmt.Printf("[list_member_added] %s (%s)\n",
				listMemberAdded.TargetObject.FullName, listMemberAdded.TargetObject.Description)
		case *userstream.ListMemberRemoved:
			listMemberRemoved := event.(*userstream.ListMemberRemoved)
			fmt.Printf("[list_member_removed] %s (%s)\n",
				listMemberRemoved.TargetObject.FullName, listMemberRemoved.TargetObject.Description)
		case *userstream.Record:
			//process(event)
		}
	})
}
Example #28
0
File: read.go Project: zqzca/back
func (c *wscon) ReadPump() {
	defer c.Unregister()

	// c.ws.SetReadLimit(maxMessageSize)
	// c.ws.SetReadDeadline(time.Now().Add(pongWait))
	// c.ws.SetPongHandler(func(string) error { c.ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })
	for {
		var r io.Reader
		op, r, err := c.ws.NextReader()

		if err != nil {
			fmt.Println("cant go further")
			fmt.Println(err.Error())
			break
		}

		message, err := ioutil.ReadAll(r)

		switch op {
		case websocket.TextMessage:
			var s p2psession

			if err = json.Unmarshal(message, &s); err != nil {
				fmt.Println(err.Error())
				fmt.Println("Failed to decode json: ", message)
				break
			}

			s.ID = uuid.NewV4().String()
			s.ID = "foo"
			s.ws = c
			s.createdAt = time.Now()

			api.sessions[s.ID] = s

			m := &p2pmsg{
				ID:  s.ID,
				Msg: "created",
			}

			spew.Dump(s)
			spew.Dump(m)
			data, _ := json.Marshal(m)
			c.write(websocket.TextMessage, data)
		case websocket.BinaryMessage:
			fmt.Println("Ignoring binary message")
		default:
			fmt.Println("other")
		}
	}
}
Example #29
0
func Demo() {
	dbh, err := NewMemoryDBHandle("testing", true)
	if err != nil {
		glog.Fatalf("Error: %s", err)
	}

	dbh.ORM.Begin()
	p1 := Person{
		Name: "apw",
	}

	created, id, err := dbh.ORM.ReadOrCreate(&p1, "Name")
	if err != nil {
		glog.Fatal(err)
	}

	if created {
		fmt.Println("New Insert an object. Id:", id)
	} else {
		fmt.Println("Get an object. Id:", id)
	}
	spew.Dump(p1)

	n1 := Note{
		Person:   &p1,
		Text:     "testing\nfoo",
		Category: "test",
	}

	_, err = dbh.ORM.Insert(&n1)
	if err != nil {
		glog.Fatal(err)
	}

	spew.Dump(n1)
	dbh.ORM.Commit()

	fmt.Println("**********************************")

	p := Person{Id: p1.Id}
	err = dbh.ORM.Read(&p)
	if err != nil {
		glog.Fatal(err)
	}
	dbh.ORM.LoadRelated(&p, "Notes")

	spew.Dump(p.Notes)
	for _, n := range p.Notes {
		fmt.Printf("Note: %s - %s", p.Name, n.Text)
	}
}
Example #30
0
// MAIN_START OMIT
func main() {
	motoX := &Phone{
		Model:    "Moto X",
		Hardware: Hardware{Memory: 16, Ram: 2, NFC: true},
		OS:       OS{Type: "Android", Version: "5.0.0"}}

	iphone6 := &Phone{
		Model:    "iPhone 6",
		Hardware: Hardware{Memory: 16, Ram: 1, NFC: false},
		OS:       OS{Type: "iOS", Version: "9.0.0"}}

	spew.Dump(motoX)
	spew.Dump(iphone6)
}