How does the next object work in Linked List? How is it able to make another class objects point to the next address? - class

class Node
{
public int data;
public Node next;
public Node(int idata) {
data = idata;
next = null;
}
}
Node newnode = new Node(val);
newnode.next = null;
Like if I'm creating a new object newnode of the class Node , how is it able to use .next to find the next address of the list?

In your example code next is just null. Actually, it was not necessary to explicitly do newnode.next = null;, as it already was initialised to null in the Node constructor.
It becomes more interesting when you assign another new node to the next property of the node you have created:
Node newnode = new Node(1);
newnode.next = new Node(2);
In Java objects are accessed with references. newnode is such a reference, and newnode.next is also such a reference. Both are references to Node instances (if not null).
We could extend the linked list further:
newnode.next.next = new Node(3);
newnode.next.next.next = new Node(4);
When you realise that next is a property that can hold a value like any variable, then there is really no magic to it.
You could for instance also first create Node instances that are disconnected, and only after their creation link them together:
Node a = new Node(1);
Node b = new Node(2);
Node c = new Node(3);
Node d = new Node(4);
a.next = b;
b.next = c;
c.next = d;

Related

Leetcode 653. Two Sum IV - Input is a BST Why we need set?

I don't understand why how HashSet works in this question
Here's the link to this problem https://leetcode.com/problems/two-sum-iv-input-is-a-bst/
Here's the solution to this problem
the codes are
public class Solution {
public boolean findTarget(TreeNode root, int k) {
Set < Integer > set = new HashSet();
Queue < TreeNode > queue = new LinkedList();
queue.add(root);
while (!queue.isEmpty()) {
if (queue.peek() != null) {
TreeNode node = queue.remove();
if (set.contains(k - node.val))
return true;
set.add(node.val);
queue.add(node.right);
queue.add(node.left);
} else
queue.remove();
}
return false;
}
}
Why we need to declare another HashSet for this problem? Do we put all the tree node in the hashset? Why this step is not shown in the code?
Also, since we didn't explicitly put any value in the set, how can we code for "set. contains()"? Am I missing some basics for hashset?
From the code, we simply traversed the tree using an extra queue and then we add the valid value/answer into the hashset. But we only need to return the boolean answer for this question. Thats why I am confused.

OPC UA.NET custom Node Manager creating

I'm trying to use UA-.NETStandardLibrary by OPC Foundation to create my own OPC UA Server that will maintain some variables.
I've created a server class inherited from StandardServer and node manager inherited from CustomNodeManager2.
There were some node managers in their examples, I removed them and add my own one. The server starts normally and doesn't contain any nodes except from standard ones, as planned. So, my problem is how to create my own variable node from code (not from xml, as in examples) and be able update its value on demand.
For example, I want to add a folder with couple of nodes inside.
Does anyone have a code snippet which demonstrates how to do it? I don't want anybody write it for me, I will appreciate only if you just tell me about a right way to make it.
Thanks a lot.
I am pretty sure the snippets you are looking for are included. Here is my testing code and I am 100% positive, I didn't write the second piece of code. Anyway, if this helps you...
{
var ticker_seq = createVariable(myFolder, "MyFolder/Ticker", "Ticker", BuiltInType.UInt64, ValueRanks.Scalar);
variables.Add(ticker_seq);
subscriptions.Add(clock.Ticker.Subscribe(val =>
{
lock (Lock)
{
ticker_seq.Value = val;
ticker_seq.Timestamp = DateTime.UtcNow;
ticker_seq.ClearChangeMasks(SystemContext, false);
}
}));
}
and creation
private BaseDataVariableState createVariable(NodeState parent, string path, string name, NodeId dataType, int valueRank)
{
BaseDataVariableState variable = new BaseDataVariableState(parent);
variable.SymbolicName = name;
variable.ReferenceTypeId = ReferenceTypes.Organizes;
variable.TypeDefinitionId = VariableTypeIds.BaseDataVariableType;
variable.NodeId = new NodeId(path, NamespaceIndex);
variable.BrowseName = new QualifiedName(path, NamespaceIndex);
variable.DisplayName = new LocalizedText("en", name);
variable.WriteMask = AttributeWriteMask.DisplayName | AttributeWriteMask.Description;
variable.UserWriteMask = AttributeWriteMask.DisplayName | AttributeWriteMask.Description;
variable.DataType = dataType;
variable.ValueRank = valueRank;
variable.AccessLevel = AccessLevels.CurrentReadOrWrite;
variable.UserAccessLevel = AccessLevels.CurrentReadOrWrite;
variable.Historizing = false;
variable.Value = 0;
variable.StatusCode = StatusCodes.Good;
variable.Timestamp = DateTime.UtcNow;
if (parent != null)
{
parent.AddChild(variable);
}
return variable;
}
creating the folder:
private FolderState CreateFolder(NodeState parent, string path, string name)
{
FolderState folder = new FolderState(parent);
folder.SymbolicName = name;
folder.ReferenceTypeId = ReferenceTypes.Organizes;
folder.TypeDefinitionId = ObjectTypeIds.FolderType;
folder.NodeId = new NodeId(path, NamespaceIndex);
folder.BrowseName = new QualifiedName(path, NamespaceIndex);
folder.DisplayName = new LocalizedText("en", name);
folder.WriteMask = AttributeWriteMask.None;
folder.UserWriteMask = AttributeWriteMask.None;
folder.EventNotifier = EventNotifiers.None;
if (parent != null)
{
parent.AddChild(folder);
}
return folder;
}

How to create a directory on the basis of path in cq5?

I have a String which is the path of the page for example /content/xperia/public/events/eventeditor. I am gererating the XML of this page and saving it to DAM, but I want to save it in the similar tree structure under /content.
I tried the following code
String page = "/content/xperia/public/events/eventeditor";
page = page.replace("/content", "/content/dam");
if (adminSession.nodeExists(page+ "/"+ "jcr:content")) {
Node node = adminSession.getNode(page+ "/"+ "jcr:content");
node.setProperty("jcr:data", sb.toString());
} else {
Node feedNode = JcrUtil.createPath(page,"nt:file", adminSession);
Node dataNode = JcrUtil.createPath(feedNode.getPath() + "/"+ "jcr:content", "nt:resource", adminSession);
dataNode.setProperty("jcr:data",sb.toString());
}
But it gives the following error
No matching child node definition found for
{http://www.jcp.org/jcr/1.0}content
Because there is no such path in the repository. Is there a way through which I can create a directory on the fly. Because to save this file, I need to create the entire tree xperia/public/events under /content/dam and then save eventeditor.xml in that directory .
Please suggest.
There are a few issues with your code. The JcrUtil.createPath(String absolutePath, String nodeType, Session session) creates all the non-existent intermediate path with the given NodeType.
This means that all the nodes xperia, public and events are created with type nt:file instead of sling:OrderedFolder.
You can use the createPath(String absolutePath, boolean createUniqueLeaf, String intermediateNodeType, String nodeType, Session session, boolean autoSave) method instead, to specify the type of intermediary nodes that are to be created.
String page = "/content/xperia/public/events/eventeditor";
page = page.replace("/content", "/content/dam");
page += ".xml";
if (adminSession.nodeExists(page+ "/"+ "jcr:content")) {
Node node = adminSession.getNode(page+ "/"+ "jcr:content");
node.setProperty("jcr:data", sb.toString());
} else {
Node feedNode = JcrUtil.createPath(page, true, "sling:OrderedFolder", "nt:file", adminSession, false);
Node dataNode = feedNode.addNode("jcr:content", "nt:resource");
dataNode.setProperty("jcr:data",sb.toString());
}
adminSession.save();

JSTree creating duplicate nodes when loading data with create_node

I'm having an issue when I'm trying to load my initial data for JSTree; I have 2 top level nodes attached to the root node but when I load them it looks like the last node added is being duplicated within JSTree. At first it looked as if it was my fault for not specifically declaring a new object each time but I've fixed that. I'm using .net MVC so the initial data is coming from the model that is passed to my view (that is the data passed into the data parameter of the method).
this.loadInitialData = function (data) {
var tree = self.getTree();
for (var i = 0; i < data.length; i++) {
var node = new Object();
node.id = data[i].Id;
node.parent = data[i].Parent;
node.text = data[i].Text;
node.state = {
opened: data[i].State.Opened,
disabled: data[i].State.Disabled,
selected: data[i].State.Selected
};
node.li_attr = { "node-type": data[i].NodeType };
node.children = [];
for (var j = 0; j < data[i].Children.length; j++) {
var childNode = new Object();
childNode.id = data[i].Children[j].Id;
childNode.parent = data[i].Children[j].Parent;
childNode.text = data[i].Children[j].Text;
childNode.li_attr = { "node-type": data[i].Children[j].NodeType };
childNode.children = data[i].Children[j].HasChildren;
node.children.push(childNode);
}
tree.create_node("#", node, "last");
}
}
My initial code was declaring node like the following:
var node = {
id: data[i].Id
}
I figured that was the cause of what I'm seeing but fixing it has not changed anything. Here is what is happening when I run the application; on the first pass of the method everything looks like it is working just fine.
But after the loop is run for the second (and last) time here is the final result.
It looks like the node objects are just a copy of each other, but when I run the code through the debugger I see the object being initialized each time. Does anyone have an idea what would cause this behavior in JSTree? Should I be using a different method to create my initial nodes besides create_node?
Thanks in advance.
I found the issue; I didn't realize but I was setting my id property to the same id for both node groups. After I fixed it everything started working as expected.

.Net Entity Framework SaveChanges is adding without add method

I'm new to the entity framework and I'm really confused about how savechanges works. There's probably a lot of code in my example which could be improved, but here's the problem I'm having.
The user enters a bunch of picks. I make sure the user hasn't already entered those picks.
Then I add the picks to the database.
var db = new myModel()
var predictionArray = ticker.Substring(1).Split(','); // Get rid of the initial comma.
var user = Membership.GetUser();
var userId = Convert.ToInt32(user.ProviderUserKey);
// Get the member with all his predictions for today.
var memberQuery = (from member in db.Members
where member.user_id == userId
select new
{
member,
predictions = from p in member.Predictions
where p.start_date == null
select p
}).First();
// Load all the company ids.
foreach (var prediction in memberQuery.predictions)
{
prediction.CompanyReference.Load();
}
var picks = from prediction in predictionArray
let data = prediction.Split(':')
let companyTicker = data[0]
where !(from i in memberQuery.predictions
select i.Company.ticker).Contains(companyTicker)
select new Prediction
{
Member = memberQuery.member,
Company = db.Companies.Where(c => c.ticker == companyTicker).First(),
is_up = data[1] == "up", // This turns up and down into true and false.
};
// Save the records to the database.
// HERE'S THE PART I DON'T UNDERSTAND.
// This saves the records, even though I don't have db.AddToPredictions(pick)
foreach (var pick in picks)
{
db.SaveChanges();
}
// This does not save records when the db.SaveChanges outside of a loop of picks.
db.SaveChanges();
foreach (var pick in picks)
{
}
// This saves records, but it will insert all the picks exactly once no matter how many picks you have.
//The fact you're skipping a pick makes no difference in what gets inserted.
var counter = 1;
foreach (var pick in picks)
{
if (counter == 2)
{
db.SaveChanges();
}
counter++;
}
I've tested and the SaveChanges doesn't even have to be in the loop.
The below code works, too.
foreach (var pick in picks)
{
break;
}
db.SaveChanges()
There's obviously something going on with the context I don't understand. I'm guessing I've somehow loaded my new picks as pending changes, but even if that's true I don't understand I have to loop over them to save changes.
Can someone explain this to me?
Here's updated working code based on Craig's responses:
1) Remove the Type then loop over the results and populate new objects.
var picks = (from prediction in predictionArray
let data = prediction.Split(':')
let companyTicker = data[0]
where !(from i in memberQuery.predictions
select i.Company.ticker).Contains(companyTicker)
select new //NO TYPE HERE
{
Member = memberQuery.member,
Company = db.Companies.Where(c => c.ticker == companyTicker).First(),
is_up = data[1] == "up", // This turns up and down into true and false.
}).ToList();
foreach (var prediction in picks)
{
if (includePrediction)
{
var p = new Prediction{
Member = prediction.Member,
Company = prediction.Company,
is_up = prediction.is_up
};
db.AddToPredictions(p);
}
}
2) Or if I don't want the predictions to be saved, I can detach the predictions.
foreach (var prediction in picks) {
if (excludePrediction)
{
db.Detach(prediction)
}
}
The reason is here:
select new Prediction
{
Member = memberQuery.member,
These lines will (once the IEnumerable is iterated; LINQ is lazy) :
Instantiate a new Prediction
Associate that Prediction with an existing Member, *which is attached to db.
Associating an instance of an entity with an attached entity automatically adds that entity to the context of the associated, attached entity.
So as soon as you start iterating over predictionArray, the code above executes and you have a new entity in your context.