how to update the value of variable of struct with mapping in solidity - mapping

I want to update the value of "amount" using setter Function after mapping with data1
pragma solidity ^0.8.0;
contract acc_data{
struct person{
string name;
uint age;
address add;
uint amount;
}
person public p1;
mapping(address=>person) public data1;
function map()public{
data1[p1.add]=p1;
}
function structsetter()public {
p1.name="rohit";
p1.age=22;
p1.add=0x5B38Da6a701c568545dCfcB03FcB875f56beddC4;
p1.amount=0;
}
function setter() public {
p1.amount=7;
}

You can do like this:
function setter() public {
data1[p1.add].amount=7;
}

Related

Jackson Object mapper how to Serialize object as String which is having nested object?

I have json like following
{"data": [
{
"instance": { ...
"inner"" {....
.............}
}
}]
"isvalid":true
"nextVal" : <some num>
}
and POJO like
class A{
private String data;
private boolean isvalid;
private String nextVal;
//with getter setters and proper jackson annotations
}
These can have variable structure inside data, so with object mapper.read I want to take entire data object in string!
have tried direct serialization to my simple object which obviously gives error and also tried JSONNode
mapper.readValue(jsonString, JsonNode.class);
String content = node.get("data").textValue();
This returns blank
anyway I can achieve that to take entire data object value in string with objectmapper?
I tried toString and returned just fine what I wanted - entire data object as String
JsonNode node = (ObjectNode) mapper.readValue(jsonString, JsonNode.class);
node.get("data").toString();
The reason it returns blank is because, data is an array. You need to deseralise it in to JsonArray. Assuming your JSON structure as below,
{
"data": [
{"instance": {
"inner": {
"id": "1"
}
}
}],
"isvalid": true,
"nextVal": 1
}
This will be deserialised using below code (in JSONNode),
List<JsonNode> list = node.findValues("data");
for(JsonNode n: list){
JsonNode in1 = n.findValue("instance");
JsonNode in2 = in1.findValue("inner");
String abc = in2.findValue("id").textValue();
System.out.println(abc);
}
You need to have the POJO structure as shown above. The data will be list of instance object. instance object will have to have inner object.
Update:
Outer node = mapper.readValue(jsonstr, Outer.class);
The classes which needs to be created would be as shown below.
public class Outer {
private List<Data> data;
Boolean valid;
Integer nextval;
public List<Data> getData() {
return data;
}
public void setData(List<Data> data) {
this.data = data;
}
public Boolean isValid() {
return valid;
}
public void setValid(Boolean valid) {
this.valid = valid;
}
public Integer getNextval() {
return nextval;
}
public void setNextval(Integer nextval) {
this.nextval = nextval;
}
}
public class Data {
Instance instance;
public Instance getInstance() {
return instance;
}
public void setInstance(Instance instance) {
this.instance = instance;
}
}
public class Instance {
private Inner inner;
public Inner getInner() {
return inner;
}
public void setInner(Inner inner) {
this.inner = inner;
}
}
public class Inner {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}

Class-based enums in Vala?

I'm wondering how to create class-based enums in Vala.
In Java you can do the following:
public class Main {
public static void main(String[] args) {
Action action = Action.COMPRESS;
System.out.printf("Action name: %s, index %d", action.getName(), action.getIndex());
}
}
class Action {
public static final Action COMPRESS = new Action("Compress", 60);
public static final Action DECOMPRESS = new Action("Decompress", 70);
private String name;
private int index;
private Action(String name, int index) {
this.name = name;
this.index = index;
}
public String getName() {
return name;
}
public int getIndex() {
return index;
}
}
But when I try the following in Vala, COMPRESS and DECOMPRESS are always null when accessing from outside the Action class.
public static int main(string[] args) {
stderr.printf("Action name: %s\n", UC.Action.COMPRESS.get_name());
}
public class UC.Action : GLib.Object {
public static UC.Action COMPRESS = new UC.Action("Compress");
public static UC.Action DECOMPRESS = new UC.Action("Decompress");
private string name;
[CCode (construct_function = null)]
private Action(string name) {
this.name = name;
}
public string get_name() {
return name;
}
}
That code outputs the following: Performing (null).
Any ideas how to accomplish this?
In Vala, static class members are initialized during the class_init GObject function, so they're not available until that has been called.
The easiest work-around is to just create an instance; you can throw it away immediately since all you're after is the side-effects.

How to use this in a dart constructor with private variables

When I try to create a constructor in dart like Student(this._name) it doesn't work with private variables.
I have already tried using setters but it doesn't work either.
class Student{
var _id;
var _name;
Student(this.id, this.name);
void set id(int id) => _id = id;
void set name(String name) => _name = name;
}
This is not supported because it would expose private implementation to the outside.
If you'd rename var _id; to var _userId; you would break code that uses your class just by renaming a private field.
See instead the comment below my answer.
class Student{
var _id;
var _name;
Student({this._id, this._name}); // error
void set id(int id) => _id = id;
void set name(String name) => _name = name;
}
The alternative
class Student{
var _id;
var _name;
Student({int id, String name}) : _id = id, _name = name;
void set id(int id) => _id = id;
void set name(String name) => _name = name;
}
You can use this notation
class Student {
String _id;
String _name;
Student({required String id, required String name})
: _id = id,
_name = name;
}
Some of you maybe struggle if the class was inheritance, you just need add coma (,) after initialize your private.
Example
class Animal {
String _name;
int _age;
}
class Dog extends Animal {
String _race;
Dog(String name, int age, {String? race}) : _race = race ?? "Wild", super(name, age);
}
Hope this code can help you.
This notation is not valid because the variable is not private and its elements are just as accessible again.
DartLang says: AVOID wrapping fields in getters and setters just to be "safe".

SDN 4 doesn't create relationship with properties

I am new to Neo4J. I have built a project that uses spring-data-neo4j (4.0.0.BUILD-SNAPSHOT - version), spring-boot (1.2.3.RELEASE - version) and succeeded to create node entities, add properties to node entities and add relationships. It works fine. Now I want to create properties for the relationships. I have used sdn4 university as a reference, here is the link https://github.com/neo4j-examples/sdn4-university .
I want to create a property called "challengedBy" for relationship PLAY_MATCH (Start node is Match and end node is Player). You can have a look on below class.
#RelationshipEntity(type = "PLAY_MATCH")
public class PlayMatch extends Entity {
//Entity is a class with the id property for the node / relationship
#Property
private String challengedBy;
#StartNode
private Match match;
#EndNode
private Player player1;
}
I have created a controller in the project /api/playmatch to create only the relationship between match and a player. So when I pass the values for an existing match node and a player node, the relationship is not created at all.
Any help will be appreciated..
PlayMatch code is
#RelationshipEntity(type = "PLAY_MATCH")
public class PlayMatch extends Entity{
#Property
private String challengedBy;
#StartNode
private Match match;
#EndNode
private Player player1;
public PlayMatch() {
}
public PlayMatch(String challengedBy, Match match,
Player player1) {
super();
this.challengedBy = challengedBy;
this.match = match;
this.player1 = player1;
}
// after this i have getters & setters and toString method for above fields.
}
Match code is
#NodeEntity(label = "Match")
public class Match extends Entity {
private String createdBy;
private Long createdTime;
private String status;
private int noOfGames;
private int noOfPoints;
private String type;
private Long date;
#Relationship(type="PLAY_MATCH",direction= Relationship.UNDIRECTED)
private PlayMatch playMatch;
public Match() {
}
public Match(String createdBy, Long createdTime, String status,
int noOfGames, int noOfPoints, String type, Long date) {
super();
this.createdBy = createdBy;
this.createdTime = createdTime;
this.status = status;
this.noOfGames = noOfGames;
this.noOfPoints = noOfPoints;
this.type = type;
this.date = date;
}
public PlayMatch getPlayMatch() {
return playMatch;
}
public void setPlayMatch(PlayMatch playMatch) {
this.playMatch = playMatch;
}
// after this i have getters & setters and toString method for above fields.
}
Player code is
#NodeEntity(label = "Player")
public class Player extends Entity {
private String address;
private String preferredSport;
private float height;
private float weight;
private String phone;
private String photo;
#Relationship(type="PLAY_MATCH")
private PlayMatch playMatch;
public PlayMatch getPlayMatch() {
return playMatch;
}
public void setPlayMatch(PlayMatch playMatch) {
this.playMatch = playMatch;
}
public Player() {
}
public Player(String address, String preferredSport, float height,
float weight, String phone, String photo) {
super();
this.address = address;
this.preferredSport = preferredSport;
this.height = height;
this.weight = weight;
this.phone = phone;
this.photo = photo;
}
// after this i have getters & setters and toString method for above fields.
}
I think you have playmatch relationship within the player end node as well. If you comment the following code in the player node. It should work. I have also attached a json sample to pass from the UI in the match URL (/api/match) instead of (/api/playmatch)
#Relationship(type="PLAY_MATCH")
private PlayMatch playMatch;
public PlayMatch getPlayMatch() {
return playMatch;
}
public void setPlayMatch(PlayMatch playMatch) {
this.playMatch = playMatch;
}
Sample JSON
{
"type": "typename",
"status": "statusname",
"createdTime": 1435928223021,
"noOfGames": 5,
"noOfPoints": 19,
"playMatch": {"challengedBy" : "John", "player1" : {"id":732}, "match":{"type": "typename",
"status": "statusname",
"createdTime": 1435928223021,
"noOfGames": 5,
"noOfPoints": 19}}
}
this should create a new match and a new relationship with property challengedBy to an existing player node with id 732.
check it out and let me know if this works.

Mapping native C structure to JNA

Very long post...
I have the following C structs that I've mapped into JNA.
These structures are used on Windows to get the raw input, from mouse, keyboard and other HID devices.
The problem is that I don't get anything in the RAWINPUT.data.keyboard (RAWKEYBAORD) structure. I haven't tested with mouse yet.
Regarding the RAWMOUSE structure, it's been modified after technomage's previous comments.
But I don't get any data in the field I expected, when debugging I can see there are data.
I think I might have mapped the structs incorrectly, or doing something wrong in the usage of them.
Can someone tell me if my mapping is correct or can use some corrections ?
I've written a DLL in C code previously, which I used in Java using JNI.
But I rather loose the DLL and use Java.
The two method below are mapped like this:
C code:
UINT WINAPI GetRawInputData(
_In_ HRAWINPUT hRawInput,
_In_ UINT uiCommand,
_Out_opt_ LPVOID pData,
_Inout_ PUINT pcbSize,
_In_ UINT cbSizeHeader
);
Java code:
int GetRawInputData(RawInputLibrary.HRAWINPUT hRawInput, int uiCommand, Memory pData, IntByReference pcbSize, int cbSizeHeader);
C code:
BOOL WINAPI RegisterRawInputDevices(
_In_ PCRAWINPUTDEVICE pRawInputDevices,
_In_ UINT uiNumDevices,
_In_ UINT cbSize
);
Java Code
boolean RegisterRawInputDevices(RawInputLibrary.RAWINPUTDEVICE pRawInputDevices, int uiNumDevices, int cbSize);
When I dump the buffer I can see the following the value for the key pressed.The 42, in memory block 6, is the letter b pressed on the keyboard, and that value changes according to the key I press. Here is the dump of the RAWINPUT structure:
RawInputLibrary$RAWINPUT(allocated#0x525ecb8 (44 bytes) (shared from allocated#0x525ecb8 (44 bytes))) {
RawInputLibrary$RAWINPUTHEADER header#0=RawInputLibrary$RAWINPUTHEADER(allocated#0x525ecb8 (16 bytes) (shared from allocated#0x525ecb8 (44 bytes) (shared from allocated#0x525ecb8 (44 bytes)))) {
int dwType#0=1
int dwSize#4=20
WinNT$HANDLE hDevice#8=native#0x3da0cb3 (com.sun.jna.platform.win32.WinNT$HANDLE#3da0cb3)
WinDef$WPARAM wParam#c=1
}
RawInputLibrary$RAWINPUT$DataUnion data#10=RawInputLibrary$RAWINPUT$DataUnion(allocated#0x525ecc8 (28 bytes) (shared from allocated#0x525ecb8 (44 bytes) (shared from allocated#0x525ecb8 (44 bytes)))) {
RawInputLibrary$RAWMOUSE mouse#0=RawInputLibrary$RAWMOUSE(auto-allocated#0x525ed48 (28 bytes)) {
short usFlags#0=0
NativeLong ulButtons#4=0
short usButtonFlags#8=0
short usButtonData#a=0
NativeLong ulRawButtons#c=0
NativeLong lLastX#10=0
NativeLong lLastY#14=0
NativeLong ulExtraInformation#18=0
}
RawInputLibrary$RAWKEYBOARD keyboard#0=RawInputLibrary$RAWKEYBOARD(auto-allocated#0x525ed70 (16 bytes)) {
short MakeCode#0=0
short Flags#2=0
short Reserved#4=0
short VKey#6=0
int Message#8=0
NativeLong ExtraInformation#c=0
}
RawInputLibrary$RAWHID hid#0=RawInputLibrary$RAWHID(auto-allocated#0x525ed88 (12 bytes)) {
int dwSizeHid#0=0
int dwCount#4=0
byte bRawData[1]#8=[B#50fe39
}
}
}
memory dump
[01000000]
[20000000]
[b30cda03]
[01000000]
[30000000]
[00004200]
[00010000]
[00000000]
[00000000]
[00000000]
[00000000]
These are the structs I've mapped. The C counter part can be seen here (not posting them in order to keep the post smaller): https://msdn.microsoft.com/en-us/library/windows/desktop/ff468899(v=vs.85).aspx
public static class HRAWINPUT extends PointerType {
public HRAWINPUT(Pointer address) {
super(address);
}
public HRAWINPUT() {
super();
}
}
public class RAWINPUT extends Structure {
public static class ByReference extends RAWINPUT implements Structure.ByReference {}
public static class ByValue extends RAWINPUT implements Structure.ByValue {}
public RawInputLibrary.RAWINPUTHEADER header;
public DataUnion data;
public static class DataUnion extends Union {
public static class ByReference extends DataUnion implements Structure.ByReference {}
public static class ByValue extends DataUnion implements Structure.ByValue {}
public RawInputLibrary.RAWMOUSE mouse;
public RawInputLibrary.RAWKEYBOARD keyboard;
public RawInputLibrary.RAWHID hid;
public DataUnion() {
super();
}
public DataUnion(RawInputLibrary.RAWMOUSE mouse) {
super();
this.mouse = mouse;
setType(RawInputLibrary.RAWMOUSE.class);
}
public DataUnion(RawInputLibrary.RAWKEYBOARD keyboard) {
super();
this.keyboard = keyboard;
setType(RawInputLibrary.RAWKEYBOARD.class);
}
public DataUnion(RawInputLibrary.RAWHID hid) {
super();
this.hid = hid;
setType(RawInputLibrary.RAWHID.class);
}
protected List<? > getFieldOrder() {
return Arrays.asList("mouse", "keyboard", "hid");
}
}
public RAWINPUT() {
super();
}
public RAWINPUT(Pointer p) {
super(p);
useMemory(p); //using this doesn't make any difference, but maybe I need to do something similar to this in the data struct ?
read();
}
public RAWINPUT(RawInputLibrary.RAWINPUTHEADER header, DataUnion data) {
super();
this.header = header;
this.data = data;
}
protected List<? > getFieldOrder() {
return Arrays.asList("header", "data");
}
}
public static class RAWINPUTHEADER extends Structure {
public static class ByReference extends RAWINPUTHEADER implements Structure.ByReference {}
public static class ByValue extends RAWINPUTHEADER implements Structure.ByValue {}
public int dwType;
public int dwSize;
public WinNT.HANDLE hDevice;
public WinDef.WPARAM wParam;
public RAWINPUTHEADER() {
super();
}
public RAWINPUTHEADER(int dwType, int dwSize, WinNT.HANDLE hDevice, WinDef.WPARAM wParam) {
super();
this.dwType = dwType;
this.dwSize = dwSize;
this.hDevice = hDevice;
this.wParam = wParam;
}
protected List<?> getFieldOrder() {
return Arrays.asList("dwType", "dwSize", "hDevice", "wParam");
}
}
public static class RAWHID extends Structure {
public static class ByReference extends RAWHID implements Structure.ByReference {}
public static class ByValue extends RAWHID implements Structure.ByValue {}
public int dwSizeHid;
public int dwCount;
public byte[] bRawData = new byte[1];
public RAWHID() {
super();
}
public RAWHID(int dwSizeHid, int dwCount, byte bRawData[]) {
super();
this.dwSizeHid = dwSizeHid;
this.dwCount = dwCount;
if ((bRawData.length != this.bRawData.length)) {
throw new IllegalArgumentException("Wrong array size !");
}
this.bRawData = bRawData;
}
protected List<? > getFieldOrder() {
return Arrays.asList("dwSizeHid", "dwCount", "bRawData");
}
}
public static class RAWKEYBOARD extends Structure {
public static class ByReference extends RAWKEYBOARD implements Structure.ByReference {}
public static class ByValue extends RAWKEYBOARD implements Structure.ByValue {}
public short MakeCode;
public short Flags;
public short Reserved;
public short VKey;
public int Message;
public NativeLong ExtraInformation;
public RAWKEYBOARD() {
super();
}
public RAWKEYBOARD(short MakeCode, short Flags, short Reserved, short VKey, int Message, NativeLong ExtraInformation) {
super();
this.MakeCode = MakeCode;
this.Flags = Flags;
this.Reserved = Reserved;
this.VKey = VKey;
this.Message = Message;
this.ExtraInformation = ExtraInformation;
}
protected List<?> getFieldOrder() {
return Arrays.asList("MakeCode", "Flags", "Reserved", "VKey", "Message", "ExtraInformation");
}
}
public static class RAWMOUSE extends Structure {
public static class ByReference extends RAWMOUSE implements Structure.ByReference {}
public static class ByValue extends RAWMOUSE implements Structure.ByValue {}
public short usFlags;
public NativeLong ulButtons;
public short usButtonFlags;
public short usButtonData;
public NativeLong ulRawButtons;
public NativeLong lLastX;
public NativeLong lLastY;
public NativeLong ulExtraInformation;
public RAWMOUSE() {
super();
}
public RAWMOUSE(short usFlags, NativeLong ulButtons, short usButtonFlags, short usButtonData, NativeLong ulRawButtons, NativeLong lLastX, NativeLong lLastY, NativeLong ulExtraInformation) {
super();
this.usFlags = usFlags;
this.ulButtons = ulButtons;
this.usButtonFlags = usButtonFlags;
this.usButtonData = usButtonData;
this.ulRawButtons = ulRawButtons;
this.lLastX = lLastX;
this.lLastY = lLastY;
this.ulExtraInformation = ulExtraInformation;
}
protected List<?> getFieldOrder() {
return Arrays.asList("usFlags", "ulButtons", "usButtonFlags", "usButtonData", "ulRawButtons", "lLastX", "lLastY", "ulExtraInformation");
}
}
The code below is an extract of thew code I'm using to test.
private class WndProc implements User32.WindowProc {
public WndProc() {
}
#Override
public LRESULT callback(HWND hwnd, int msg, WPARAM wparam, LPARAM lparam) {
switch (msg) {
case User32.WM_CREATE: {
if (hwnd != null) {
log.debug("Registering raw input device notifications...");
RawInputLibrary.RAWINPUTDEVICE.ByReference rawInputDevice = new RawInputLibrary.RAWINPUTDEVICE.ByReference();
//create an array of the struct in memory and fill it with data, and then parse the reference to the native call
RawInputLibrary.RAWINPUTDEVICE[] pRawInputDevice = (RawInputLibrary.RAWINPUTDEVICE[]) rawInputDevice.toArray(1);
pRawInputDevice[0].dwFlags = RawInputLibrary.RIDEV_INPUTSINK; // receive system wide keystrokes
pRawInputDevice[0].usUsagePage = 1; // generic desktop controls
pRawInputDevice[0].usUsage = 6; // keyboard
pRawInputDevice[0].hwndTarget = hwnd;
// register interest in raw data input
if (!rawInputLib.RegisterRawInputDevices(rawInputDevice, 1, rawInputDevice.size())) {
rawInputRegistrationSuccess = false;
log.error("Failed to register for raw input messages");
} else {
log.debug("Done registering raw input device notifications...");
}
} else {
log.debug("window handle is not defined");
}
break;
}
case RawInputLibrary.WM_INPUT: {
log.debug("Got raw input device message...");
IntByReference dwSize = new IntByReference();
int rawInputHeaderSize = new RawInputLibrary.RAWINPUTHEADER().size();
RawInputLibrary.HRAWINPUT hRawInput = new RawInputLibrary.HRAWINPUT(lparam.toPointer());
if (rawInputLib.GetRawInputData(hRawInput, RawInputLibrary.RID_INPUT, null, dwSize, rawInputHeaderSize) < 0) {
break;
}
if (dwSize.getValue() == 0) {
break;
}
IntByReference bufferSize = new IntByReference(Math.max(dwSize.getValue(), new RawInputLibrary.RAWINPUT().size()));
Memory buffer = new Memory(bufferSize.getValue());
if (rawInputLib.GetRawInputData(hRawInput, RawInputLibrary.RID_INPUT, buffer, bufferSize, rawInputHeaderSize) == -1) {
buffer.clear();
break;
}
RawInputLibrary.RAWINPUT rawinput = new RawInputLibrary.RAWINPUT(buffer);
int event = rawinput.data.keyboard.Message;
switch(event) {
case User32.WM_KEYDOWN:
case User32.WM_SYSKEYDOWN:
log.debug("Got raw input keyboard pressed");
switch(rawinput.data.keyboard.VKey){
//Shift
case 160:
case 161:
// inform listener about shift key pressed
break;
//Ignore special characters
case 144: //Numlock
break;
default:
// inform listener about key pressed
break;
}
break;
case User32.WM_KEYUP:
case User32.WM_SYSKEYUP:
if (rawinput.data.keyboard.VKey == 160 || rawinput.data.keyboard.VKey == 161) {
// inform listener about shift key released
}
break;
default:
break;
}
break;
}
default : {
return user32Lib.DefWindowProc(hwnd, msg, wparam, lparam);
}
}
return new LRESULT(0);
}
}

Resources