Q: What is the most efficient/elegant way to parse a flat table into a tree? Assume you have a flat table that stores an ordered tree hierarchy:
Id   Name         ParentId   Order
 1   'Node 1'            0      10
 2   'Node 1.1'          1      10
 3   'Node 2'            0      20
 4   'Node 1.1.1'        2      10
 5   'Node 2.1'          3      10
 6   'Node 1.2'          1      20

Here's a diagram, where we have [id] Name.  Root node 0 is fictional.

                       [0] ROOT
                          /    \
              [1] Node 1          [3] Node 2
              /       \                   \
    [2] Node 1.1     [6] Node 1.2      [5] Node 2.1
          /
 [4] Node 1.1.1

What minimalistic approach would you use to output that to HTML (or text, for that matter) as a correctly ordered, correctly indented tree?
Assume further you only have basic data structures (arrays and hashmaps), no fancy objects with parent/children references, no ORM, no framework, just your two hands. The table is represented as a result set, which can be accessed randomly.
Pseudo code or plain English is okay, this is purely a conceptional question.
Bonus question: Is there a fundamentally better way to store a tree structure like this in a RDBMS?

EDITS AND ADDITIONS
To answer one commenter's (Mark Bessey's) question: A root node is not necessary, because it is never going to be displayed anyway. ParentId = 0 is the convention to express "these are top level". The Order column defines how nodes with the same parent are going to be sorted.
The "result set" I spoke of can be pictured as an array of hashmaps (to stay in that terminology). For my example was meant to be already there. Some answers go the extra mile and construct it first, but thats okay.
The tree can be arbitrarily deep. Each node can have N children. I did not exactly have a "millions of entries" tree in mind, though.
Don't mistake my choice of node naming ('Node 1.1.1') for something to rely on. The nodes could equally well be called 'Frank' or 'Bob', no naming structure is implied, this was merely to make it readable.
I have posted my own solution so you guys can pull it to pieces.

A: There are really good solutions which exploit the internal btree representation of sql indices. This is based on some great research done back around 1998.
Here is an example table (in mysql).
CREATE TABLE `node` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `tw` int(10) unsigned NOT NULL,
  `pa` int(10) unsigned DEFAULT NULL,
  `sz` int(10) unsigned DEFAULT NULL,
  `nc` int(11) GENERATED ALWAYS AS (tw+sz) STORED,
  PRIMARY KEY (`id`),
  KEY `node_tw_index` (`tw`),
  KEY `node_pa_index` (`pa`),
  KEY `node_nc_index` (`nc`),
  CONSTRAINT `node_pa_fk` FOREIGN KEY (`pa`) REFERENCES `node` (`tw`) ON DELETE CASCADE
)

The only fields necessary for the tree representation are:

*

*tw: The Left to Right DFS Pre-order index, where root = 1.

*pa: The reference (using tw) to the parent node, root has null.

*sz: The size of the node's branch including itself.

*nc: is used as syntactic sugar. it is tw+sz and represents the tw of the node's "next child".

Here is an example 24 node population, ordered by tw:
+-----+---------+----+------+------+------+
| id  | name    | tw | pa   | sz   | nc   |
+-----+---------+----+------+------+------+
|   1 | Root    |  1 | NULL |   24 |   25 |
|   2 | A       |  2 |    1 |   14 |   16 |
|   3 | AA      |  3 |    2 |    1 |    4 |
|   4 | AB      |  4 |    2 |    7 |   11 |
|   5 | ABA     |  5 |    4 |    1 |    6 |
|   6 | ABB     |  6 |    4 |    3 |    9 |
|   7 | ABBA    |  7 |    6 |    1 |    8 |
|   8 | ABBB    |  8 |    6 |    1 |    9 |
|   9 | ABC     |  9 |    4 |    2 |   11 |
|  10 | ABCD    | 10 |    9 |    1 |   11 |
|  11 | AC      | 11 |    2 |    4 |   15 |
|  12 | ACA     | 12 |   11 |    2 |   14 |
|  13 | ACAA    | 13 |   12 |    1 |   14 |
|  14 | ACB     | 14 |   11 |    1 |   15 |
|  15 | AD      | 15 |    2 |    1 |   16 |
|  16 | B       | 16 |    1 |    1 |   17 |
|  17 | C       | 17 |    1 |    6 |   23 |
| 359 | C0      | 18 |   17 |    5 |   23 |
| 360 | C1      | 19 |   18 |    4 |   23 |
| 361 | C2(res) | 20 |   19 |    3 |   23 |
| 362 | C3      | 21 |   20 |    2 |   23 |
| 363 | C4      | 22 |   21 |    1 |   23 |
|  18 | D       | 23 |    1 |    1 |   24 |
|  19 | E       | 24 |    1 |    1 |   25 |
+-----+---------+----+------+------+------+

Every tree result can be done non-recursively.
For instance, to get a list of ancestors of node at tw='22'
Ancestors
select anc.* from node me,node anc
where me.tw=22 and anc.nc >= me.tw and anc.tw <= me.tw
order by anc.tw;
+-----+---------+----+------+------+------+
| id  | name    | tw | pa   | sz   | nc   |
+-----+---------+----+------+------+------+
|   1 | Root    |  1 | NULL |   24 |   25 |
|  17 | C       | 17 |    1 |    6 |   23 |
| 359 | C0      | 18 |   17 |    5 |   23 |
| 360 | C1      | 19 |   18 |    4 |   23 |
| 361 | C2(res) | 20 |   19 |    3 |   23 |
| 362 | C3      | 21 |   20 |    2 |   23 |
| 363 | C4      | 22 |   21 |    1 |   23 |
+-----+---------+----+------+------+------+

Siblings and children are trivial - just use pa field ordering by tw.
Descendants
For example the set (branch) of nodes that are rooted at tw = 17.
select des.* from node me,node des
where me.tw=17 and des.tw < me.nc and des.tw >= me.tw
order by des.tw;
+-----+---------+----+------+------+------+
| id  | name    | tw | pa   | sz   | nc   |
+-----+---------+----+------+------+------+
|  17 | C       | 17 |    1 |    6 |   23 |
| 359 | C0      | 18 |   17 |    5 |   23 |
| 360 | C1      | 19 |   18 |    4 |   23 |
| 361 | C2(res) | 20 |   19 |    3 |   23 |
| 362 | C3      | 21 |   20 |    2 |   23 |
| 363 | C4      | 22 |   21 |    1 |   23 |
+-----+---------+----+------+------+------+

Additional Notes
This methodology is extremely useful for when there are a far greater number of reads than there are inserts or updates.
Because the insertion, movement, or updating of a node in the tree requires the tree to be adjusted, it is necessary to lock the table before commencing with the action.
The insertion/deletion cost is high because the tw index and sz (branch size) values will need to be updated on all the nodes after the insertion point, and for all ancestors respectively.
Branch moving involves moving the tw value of the branch out of range, so it is also necessary to disable foreign key constraints when moving a branch.  There are, essentially four queries required to move a branch:

*

*Move the branch out of range.

*Close the gap that it left. (the remaining tree is now normalised).

*Open the gap where it will go to.

*Move the branch into it's new position.

Adjust Tree Queries
The opening/closing of gaps in the tree is an important sub-function used by create/update/delete methods, so I include it here.
We need two parameters - a flag representing whether or not we are downsizing or upsizing, and the node's tw index. So, for example tw=18 (which has a branch size of 5). Let's assume that we are downsizing (removing tw) - this means that we are using '-' instead of '+' in the updates of the following example.
We first use a (slightly altered) ancestor function to update the sz value.
update node me, node anc set anc.sz = anc.sz - me.sz from
node me, node anc where me.tw=18
and ((anc.nc >= me.tw and anc.tw < me.pa) or (anc.tw=me.pa));

Then we need to adjust the tw for those whose tw is higher than the branch to be removed.
update node me, node anc set anc.tw = anc.tw - me.sz from
node me, node anc where me.tw=18 and anc.tw >= me.tw;

Then we need to adjust the parent for those whose pa's tw is higher than the branch to be removed.
update node me, node anc set anc.pa = anc.pa - me.sz from
node me, node anc where me.tw=18 and anc.pa >= me.tw;

A: Well given the choice, I'd be using objects. I'd create an object for each record where each object has a children collection and store them all in an assoc array (/hashtable) where the Id is the key. And blitz through the collection once, adding the children to the relevant children fields. Simple.
But because you're being no fun by restricting use of some good OOP, I'd probably iterate based on:
function PrintLine(int pID, int level)
    foreach record where ParentID == pID
        print level*tabs + record-data
        PrintLine(record.ID, level + 1)

PrintLine(0, 0)

Edit: this is similar to a couple of other entries, but I think it's slightly cleaner. One thing I'll add: this is extremely SQL-intensive. It's nasty. If you have the choice, go the OOP route.

A: If you use nested sets (sometimes referred to as Modified Pre-order Tree Traversal) you can extract the entire tree structure or any subtree within it in tree order with a single query, at the cost of inserts being more expensive, as you need to manage columns which describe an in-order path through thee tree structure.
For django-mptt, I used a structure like this:

id  parent_id  tree_id  level  lft  rght
--  ---------  -------  -----  ---  ----
 1       null        1      0    1    14
 2          1        1      1    2     7
 3          2        1      2    3     4
 4          2        1      2    5     6
 5          1        1      1    8    13
 6          5        1      2    9    10
 7          5        1      2    11   12

Which describes a tree which looks like this (with id representing each item):

 1
 +-- 2
 |   +-- 3
 |   +-- 4
 |
 +-- 5
     +-- 6
     +-- 7

Or, as a nested set diagram which makes it more obvious how the lft and rght values work:

 __________________________________________________________________________
|  Root 1                                                                  |
|   ________________________________    ________________________________   |
|  |  Child 1.1                     |  |  Child 1.2                     |  |
|  |   ___________    ___________   |  |   ___________    ___________   |  |
|  |  |  C 1.1.1  |  |  C 1.1.2  |  |  |  |  C 1.2.1  |  |  C 1.2.2  |  |  |
1  2  3___________4  5___________6  7  8  9___________10 11__________12 13 14
|  |________________________________|  |________________________________|  |
|__________________________________________________________________________|

As you can see, to get the entire subtree for a given node, in tree order, you simply have to select all rows which have lft and rght values between its lft and rght values. It's also simple to retrieve the tree of ancestors for a given node.
The level column is a bit of denormalisation for convenience more than anything and the tree_id column allows you to restart the lft and rght numbering for each top-level node, which reduces the number of columns affected by inserts, moves and deletions, as the lft and rght columns have to be adjusted accordingly when these operations take place in order to create or close gaps. I made some development notes at the time when I was trying to wrap my head around the queries required for each operation.
In terms of actually working with this data to display a tree, I created a tree_item_iterator utility function which, for each node, should give you sufficient information to generate whatever kind of display you want.
More info about MPTT:

*

*Trees in SQL

*Storing Hierarchical Data in a Database

*Managing Hierarchical Data in MySQL

A: Now that MySQL 8.0 supports recursive queries, we can say that all popular SQL databases support recursive queries in standard syntax.
WITH RECURSIVE MyTree AS (
    SELECT * FROM MyTable WHERE ParentId IS NULL
    UNION ALL
    SELECT m.* FROM MyTABLE AS m JOIN MyTree AS t ON m.ParentId = t.Id
)
SELECT * FROM MyTree;

I tested recursive queries in MySQL 8.0 in my presentation Recursive Query Throwdown in 2017.
Below is my original answer from 2008:

There are several ways to store tree-structured data in a relational database.  What you show in your example uses two methods:

*

*Adjacency List (the "parent" column) and

*Path Enumeration (the dotted-numbers in your name column).

Another solution is called Nested Sets, and it can be stored in the same table too.  Read "Trees and Hierarchies in SQL for Smarties" by Joe Celko for a lot more information on these designs.
I usually prefer a design called Closure Table (aka "Adjacency Relation") for storing tree-structured data.  It requires another table, but then querying trees is pretty easy.
I cover Closure Table in my presentation Models for Hierarchical Data with SQL and PHP and in my book SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming.
CREATE TABLE ClosureTable (
  ancestor_id   INT NOT NULL REFERENCES FlatTable(id),
  descendant_id INT NOT NULL REFERENCES FlatTable(id),
  PRIMARY KEY (ancestor_id, descendant_id)
);

Store all paths in the Closure Table, where there is a direct ancestry from one node to another.  Include a row for each node to reference itself.  For example, using the data set you showed in your question:
INSERT INTO ClosureTable (ancestor_id, descendant_id) VALUES
  (1,1), (1,2), (1,4), (1,6),
  (2,2), (2,4),
  (3,3), (3,5),
  (4,4),
  (5,5),
  (6,6);

Now you can get a tree starting at node 1 like this:
SELECT f.*
FROM FlatTable f
  JOIN ClosureTable a ON (f.id = a.descendant_id)
WHERE a.ancestor_id = 1;

The output (in MySQL client) looks like the following:
+----+
| id |
+----+
|  1 |
|  2 |
|  4 |
|  6 |
+----+

In other words, nodes 3 and 5 are excluded, because they're part of a separate hierarchy, not descending from node 1.

Re: comment from e-satis about immediate children (or immediate parent).  You can add a "path_length" column to the ClosureTable to make it easier to query specifically for an immediate child or parent (or any other distance).
INSERT INTO ClosureTable (ancestor_id, descendant_id, path_length) VALUES
  (1,1,0), (1,2,1), (1,4,2), (1,6,1),
  (2,2,0), (2,4,1),
  (3,3,0), (3,5,1),
  (4,4,0),
  (5,5,0),
  (6,6,0);

Then you can add a term in your search for querying the immediate children of a given node.  These are descendants whose path_length is 1.
SELECT f.*
FROM FlatTable f
  JOIN ClosureTable a ON (f.id = a.descendant_id)
WHERE a.ancestor_id = 1
  AND path_length = 1;

+----+
| id |
+----+
|  2 |
|  6 |
+----+

Re comment from @ashraf: "How about sorting the whole tree [by name]?"
Here's an example query to return all nodes that are descendants of node 1, join them to the FlatTable that contains other node attributes such as name, and sort by the name.
SELECT f.name
FROM FlatTable f
JOIN ClosureTable a ON (f.id = a.descendant_id)
WHERE a.ancestor_id = 1
ORDER BY f.name;

Re comment from @Nate:
SELECT f.name, GROUP_CONCAT(b.ancestor_id order by b.path_length desc) AS breadcrumbs
FROM FlatTable f
JOIN ClosureTable a ON (f.id = a.descendant_id)
JOIN ClosureTable b ON (b.descendant_id = a.descendant_id)
WHERE a.ancestor_id = 1
GROUP BY a.descendant_id
ORDER BY f.name

+------------+-------------+
| name       | breadcrumbs |
+------------+-------------+
| Node 1     | 1           |
| Node 1.1   | 1,2         |
| Node 1.1.1 | 1,2,4       |
| Node 1.2   | 1,6         |
+------------+-------------+

A user suggested an edit today. SO moderators approved the edit, but I am reversing it.
The edit suggested that the ORDER BY in the last query above should be ORDER BY b.path_length, f.name, presumably to make sure the ordering matches the hierarchy. But this doesn't work, because it would order "Node 1.1.1" after "Node 1.2".
If you want the ordering to match the hierarchy in a sensible way, that is possible, but not simply by ordering by the path length. For example, see my answer to MySQL Closure Table hierarchical database - How to pull information out in the correct order.

A: This was written quickly, and is neither pretty nor efficient (plus it autoboxes alot, converting between int and Integer is annoying!), but it works.
It probably breaks the rules since I'm creating my own objects but hey I'm doing this as a diversion from real work :)
This also assumes that the resultSet/table is completely read into some sort of structure before you start building Nodes, which wouldn't be the best solution if you have hundreds of thousands of rows.
public class Node {

    private Node parent = null;

    private List<Node> children;

    private String name;

    private int id = -1;

    public Node(Node parent, int id, String name) {
        this.parent = parent;
        this.children = new ArrayList<Node>();
        this.name = name;
        this.id = id;
    }

    public int getId() {
        return this.id;
    }

    public String getName() {
        return this.name;
    }

    public void addChild(Node child) {
        children.add(child);
    }

    public List<Node> getChildren() {
        return children;
    }

    public boolean isRoot() {
        return (this.parent == null);
    }

    @Override
    public String toString() {
        return "id=" + id + ", name=" + name + ", parent=" + parent;
    }
}

public class NodeBuilder {

    public static Node build(List<Map<String, String>> input) {

        // maps id of a node to it's Node object
        Map<Integer, Node> nodeMap = new HashMap<Integer, Node>();

        // maps id of a node to the id of it's parent
        Map<Integer, Integer> childParentMap = new HashMap<Integer, Integer>();

        // create special 'root' Node with id=0
        Node root = new Node(null, 0, "root");
        nodeMap.put(root.getId(), root);

        // iterate thru the input
        for (Map<String, String> map : input) {

            // expect each Map to have keys for "id", "name", "parent" ... a
            // real implementation would read from a SQL object or resultset
            int id = Integer.parseInt(map.get("id"));
            String name = map.get("name");
            int parent = Integer.parseInt(map.get("parent"));

            Node node = new Node(null, id, name);
            nodeMap.put(id, node);

            childParentMap.put(id, parent);
        }

        // now that each Node is created, setup the child-parent relationships
        for (Map.Entry<Integer, Integer> entry : childParentMap.entrySet()) {
            int nodeId = entry.getKey();
            int parentId = entry.getValue();

            Node child = nodeMap.get(nodeId);
            Node parent = nodeMap.get(parentId);
            parent.addChild(child);
        }

        return root;
    }
}

public class NodePrinter {

    static void printRootNode(Node root) {
        printNodes(root, 0);
    }

    static void printNodes(Node node, int indentLevel) {

        printNode(node, indentLevel);
        // recurse
        for (Node child : node.getChildren()) {
            printNodes(child, indentLevel + 1);
        }
    }

    static void printNode(Node node, int indentLevel) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < indentLevel; i++) {
            sb.append("\t");
        }
        sb.append(node);

        System.out.println(sb.toString());
    }

    public static void main(String[] args) {

        // setup dummy data
        List<Map<String, String>> resultSet = new ArrayList<Map<String, String>>();
        resultSet.add(newMap("1", "Node 1", "0"));
        resultSet.add(newMap("2", "Node 1.1", "1"));
        resultSet.add(newMap("3", "Node 2", "0"));
        resultSet.add(newMap("4", "Node 1.1.1", "2"));
        resultSet.add(newMap("5", "Node 2.1", "3"));
        resultSet.add(newMap("6", "Node 1.2", "1"));

        Node root = NodeBuilder.build(resultSet);
        printRootNode(root);

    }

    //convenience method for creating our dummy data
    private static Map<String, String> newMap(String id, String name, String parentId) {
        Map<String, String> row = new HashMap<String, String>();
        row.put("id", id);
        row.put("name", name);
        row.put("parent", parentId);
        return row;
    }
}

A: Assuming that you know that the root elements are zero, here's the pseudocode to output to text:
function PrintLevel (int curr, int level)
    //print the indents
    for (i=1; i<=level; i++)
        print a tab
    print curr \n;
    for each child in the table with a parent of curr
        PrintLevel (child, level+1)

for each elementID where the parentid is zero
    PrintLevel(elementID, 0)

A: It's a quite old question, but as it's got many views I think it's worth to present an alternative, and in my opinion very elegant, solution.
In order to read a tree structure you can use recursive Common Table Expressions (CTEs). It gives a possibility to fetch whole tree structure at once, have the information about the level of the node, its parent node and order within children of the parent node.
Let me show you how this would work in PostgreSQL 9.1.

*

*Create a structure
CREATE TABLE tree (
    id int  NOT NULL,
    name varchar(32)  NOT NULL,
    parent_id int  NULL,
    node_order int  NOT NULL,
    CONSTRAINT tree_pk PRIMARY KEY (id),
    CONSTRAINT tree_tree_fk FOREIGN KEY (parent_id)
      REFERENCES tree (id) NOT DEFERRABLE
);

insert into tree values
  (0, 'ROOT', NULL, 0),
  (1, 'Node 1', 0, 10),
  (2, 'Node 1.1', 1, 10),
  (3, 'Node 2', 0, 20),
  (4, 'Node 1.1.1', 2, 10),
  (5, 'Node 2.1', 3, 10),
  (6, 'Node 1.2', 1, 20);

*Write a query
WITH RECURSIVE
tree_search (id, name, level, parent_id, node_order) AS (
  SELECT
    id,
    name,
    0,
    parent_id,
    1
  FROM tree
  WHERE parent_id is NULL

  UNION ALL
  SELECT
    t.id,
    t.name,
    ts.level + 1,
    ts.id,
    t.node_order
  FROM tree t, tree_search ts
  WHERE t.parent_id = ts.id
)
SELECT * FROM tree_search
WHERE level > 0
ORDER BY level, parent_id, node_order;

Here are the results:
     id |    name    | level | parent_id | node_order
    ----+------------+-------+-----------+------------
      1 | Node 1     |     1 |         0 |         10
      3 | Node 2     |     1 |         0 |         20
      2 | Node 1.1   |     2 |         1 |         10
      6 | Node 1.2   |     2 |         1 |         20
      5 | Node 2.1   |     2 |         3 |         10
      4 | Node 1.1.1 |     3 |         2 |         10
    (6 rows)

The tree nodes are ordered by a level of depth. In the final output we would present them in the subsequent lines.
For each level, they are ordered by parent_id and node_order within the parent. This tells us how to present them in the output - link node to the parent in this order.
Having such a structure it wouldn't be difficult to make a really nice presentation in HTML.
Recursive CTEs are available in PostgreSQL, IBM DB2, MS SQL Server, Oracle and SQLite.
If you'd like to read more on recursive SQL queries, you can either check the documentation of your favourite DBMS or read my two articles covering this topic:

*

*Do It In SQL: Recursive Tree Traversal

*Get to know the power of SQL recursive queries

A: You can emulate any other data structure with a hashmap, so that's not a terrible limitation.  Scanning from the top to the bottom, you create a hashmap for each row of the database, with an entry for each column. Add each of these hashmaps to a "master" hashmap, keyed on the id. If any node has a "parent" that you haven't seen yet, create an placeholder entry for it in the master hashmap, and fill it in when you see the actual node.
To print it out, do a simple depth-first pass through the data, keeping track of indent level along the way. You can make this easier by keeping a "children" entry for each row, and populating it as you scan the data.
As for whether there's a "better" way to store a tree in a database, that depends on how you're going to use the data. I've seen systems that had a known maximum depth that used a different table for each level in the hierarchy. That makes a lot of sense if the levels in the tree aren't quite equivalent after all (top level categories being different than the leaves).

A: As of Oracle 9i, you can use CONNECT BY.
SELECT LPAD(' ', (LEVEL - 1) * 4) || "Name" AS "Name"
FROM (SELECT * FROM TMP_NODE ORDER BY "Order")
CONNECT BY PRIOR "Id" = "ParentId"
START WITH "Id" IN (SELECT "Id" FROM TMP_NODE WHERE "ParentId" = 0)

As of SQL Server 2005, you can use a recursive common table expression (CTE).
WITH [NodeList] (
  [Id]
  , [ParentId]
  , [Level]
  , [Order]
) AS (
  SELECT [Node].[Id]
    , [Node].[ParentId]
    , 0 AS [Level]
    , CONVERT([varchar](MAX), [Node].[Order]) AS [Order]
  FROM [Node]
  WHERE [Node].[ParentId] = 0
  UNION ALL
  SELECT [Node].[Id]
    , [Node].[ParentId]
    , [NodeList].[Level] + 1 AS [Level]
    , [NodeList].[Order] + '|'
      + CONVERT([varchar](MAX), [Node].[Order]) AS [Order]
  FROM [Node]
    INNER JOIN [NodeList] ON [NodeList].[Id] = [Node].[ParentId]
) SELECT REPLICATE(' ', [NodeList].[Level] * 4) + [Node].[Name] AS [Name]
FROM [Node]
  INNER JOIN [NodeList] ON [NodeList].[Id] = [Node].[Id]
ORDER BY [NodeList].[Order]

Both will output the following results.

Name
'Node 1'
'    Node 1.1'
'        Node 1.1.1'
'    Node 1.2'
'Node 2'
'    Node 2.1'

A: Bill's answer is pretty gosh-darned good, this answer adds some things to it which makes me wish SO supported threaded answers.
Anyway I wanted to support the tree structure and the Order property.  I included a single property in each Node called leftSibling that does the same thing Order is meant to do in the original question (maintain left-to-right order).

mysql> desc nodes ;
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | int(11)      | NO   | PRI | NULL    | auto_increment |
| name        | varchar(255) | YES  |     | NULL    |                |
| leftSibling | int(11)      | NO   |     | 0       |                |
+-------------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

mysql> desc adjacencies;
+------------+---------+------+-----+---------+----------------+
| Field      | Type    | Null | Key | Default | Extra          |
+------------+---------+------+-----+---------+----------------+
| relationId | int(11) | NO   | PRI | NULL    | auto_increment |
| parent     | int(11) | NO   |     | NULL    |                |
| child      | int(11) | NO   |     | NULL    |                |
| pathLen    | int(11) | NO   |     | NULL    |                |
+------------+---------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

More detail and SQL code on my blog.
Thanks Bill your answer was helpful in getting started!

A: If nested hash maps or arrays can be created, then I can simply go down the table from the beginning and add each item to the nested array. I must trace each line to the root node in order to know which level in the nested array to insert into. I can employ memoization so that I do not need to look up the same parent over and over again.
Edit: I would read the entire table into an array first, so it will not query the DB repeatedly. Of course this won't be practical if your table is very large.
After the structure is built, I must do a depth first traverse through it and print out the HTML.
There's no better fundamental way to store this information using one table (I could be wrong though ;), and would love to see a better solution ). However, if you create a scheme to employ dynamically created db tables, then you opened up a whole new world at the sacrifice of simplicity, and the risk of SQL hell ;).

A: To Extend Bill's SQL solution you can basically do the same using a flat array.  Further more if your strings all have the same lenght and your maximum number of children are known (say in a binary tree) you can do it using a single string (character array).  If you have arbitrary number of children this complicates things a bit...  I would have to check my old notes to see what can be done.
Then, sacrificing a bit of memory, especially if your tree is sparse and/or unballanced, you can, with a bit of index math, access all the strings randomly by storing your tree, width first in the array like so (for a binary tree):
String[] nodeArray = [L0root, L1child1, L1child2, L2Child1, L2Child2, L2Child3, L2Child4] ...

yo know your string length, you know it

I'm at work now so cannot spend much time on it but with interest I can fetch a bit of code to do this.
We use to do it to search in binary trees made of DNA codons, a process built the tree, then we flattened it to search text patterns and when found, though index math (revers from above) we get the node back...  very fast and efficient, tough our tree rarely had empty nodes, but we could searh gigabytes of data in a jiffy.

A: Pre-order transversal with on-the-fly path enumeration on adjacency representation
Nested sets from:

*

*Konchog https://stackoverflow.com/a/42781302/895245

*Jonny Buchanan https://stackoverflow.com/a/194031/895245
is the only efficient way I've seen of traversing, at the cost of slower updates. That's likely what most people will want for pre-order.
Closure table from https://stackoverflow.com/a/192462/895245 is interesting, but I don't see how to enforce pre-order there: MySQL Closure Table hierarchical database - How to pull information out in the correct order
Mostly for fun, here's a method that recursively calculates the 1.3.2.5. prefixes on the fly and sorts by them at the end, based only on the parent ID/child index representation.
Upsides:

*

*updates only need to update the indexes of each sibling

Downsides:

*

*n^2 memory usage worst case for a super deep tree. This could be quite serious, which is why I say this method is likely mostly for fun only. But maybe there is some ultra high update case where someone would want to use it? Who knows

*recursive queries, so reads are going to be less efficient than nested sets

Create and populate table:
CREATE TABLE "ParentIndexTree" (
  "id" INTEGER PRIMARY KEY,
  "parentId" INTEGER,
  "childIndex" INTEGER NOT NULL,
  "value" INTEGER NOT NULL,
  "name" TEXT NOT NULL,
  FOREIGN KEY ("parentId") REFERENCES "ParentIndexTree"(id)
)
;
INSERT INTO "ParentIndexTree" VALUES
  (0, NULL, 0, 1, 'one'  ),
  (1, 0,    0, 2, 'two'  ),
  (2, 0,    1, 3, 'three'),
  (3, 1,    0, 4, 'four' ),
  (4, 1,    1, 5, 'five' )
;

Represented tree:
    1
   / \
  2   3
 / \
4   5

Then for a DBMS with arrays like PostgreSQL](https://www.postgresql.org/docs/14/arrays.html):
WITH RECURSIVE "TreeSearch" (
  "id",
  "parentId",
  "childIndex",
  "value",
  "name",
  "prefix"
) AS (
  SELECT
    "id",
    "parentId",
    "childIndex",
    "value",
    "name",
    array[0]
  FROM "ParentIndexTree"
  WHERE "parentId" IS NULL

  UNION ALL

  SELECT
    "child"."id",
    "child"."parentId",
    "child"."childIndex",
    "child"."value",
    "child"."name",
    array_append("parent"."prefix", "child"."childIndex")
  FROM "ParentIndexTree" AS "child"
  JOIN "TreeSearch" AS "parent"
    ON "child"."parentId" = "parent"."id"
)
SELECT * FROM "TreeSearch"
ORDER BY "prefix"
;

This creates on the fly prefixes of form:
1 -> 0
2 -> 0, 0
3 -> 0, 1
4 -> 0, 0, 0
5 -> 0, 0, 1

and then PostgreSQL then sorts by the arrays alphabetically as:
1 -> 0
2 -> 0, 0
4 -> 0, 0, 0
5 -> 0, 0, 1
3 -> 0, 1

which is the pre-order result that we want.
For a DBMS without arrays like SQLite, you can hack by encoding the prefix with a string of fixed width integers. Binary would be ideal, but I couldn't find out how, so hex would work. This of course means you will have to select a maximum depth that will fit in the number of bytes selected, e.g. below I choose 6 allowing for a maximum of 16^6 children per node.
WITH RECURSIVE "TreeSearch" (
  "id",
  "parentId",
  "childIndex",
  "value",
  "name",
  "prefix"
) AS (
  SELECT
    "id",
    "parentId",
    "childIndex",
    "value",
    "name",
    '000000'
  FROM "ParentIndexTree"
  WHERE "parentId" IS NULL

  UNION ALL

  SELECT
    "child"."id",
    "child"."parentId",
    "child"."childIndex",
    "child"."value",
    "child"."name",
    "parent"."prefix" || printf('%06x', "child"."childIndex")
  FROM "ParentIndexTree" AS "child"
  JOIN "TreeSearch" AS "parent"
    ON "child"."parentId" = "parent"."id"
)
SELECT * FROM "TreeSearch"
ORDER BY "prefix"
;

Some nested set notes
Here are a few points which confused me a bit after looking at the other nested set answers.
Jonny Buchanan shows his nested set setup as:
__________________________________________________________________________
|  Root 1                                                                  |
|   ________________________________    ________________________________   |
|  |  Child 1.1                     |  |  Child 1.2                     |  |
|  |   ___________    ___________   |  |   ___________    ___________   |  |
|  |  |  C 1.1.1  |  |  C 1.1.2  |  |  |  |  C 1.2.1  |  |  C 1.2.2  |  |  |
1  2  3___________4  5___________6  7  8  9___________10 11__________12 13 14
|  |________________________________|  |________________________________|  |
|__________________________________________________________________________|

which made me wonder why not just use the simpler looking:
__________________________________________________________________________
|  Root 1                                                                 |
|   ________________________________    _______________________________   |
|  |  Child 1.1                     |  |  Child 1.2                    |  |
|  |   ___________    ___________   |  |   ___________   ___________   |  |
|  |  |  C 1.1.1  |  |  C 1.1.2  |  |  |  |  C 1.2.1  | |  C 1.2.2  |  |  |
1  2  3___________|  4___________|  |  5  6___________| 7___________|  |  |
|  |________________________________|  |_______________________________|  |
|_________________________________________________________________________|

which does not have an extra number for each endpoint.
But then when I actually tried to implement it, I noticed that it was hard/impossible to implement the update queries like that, unless I had parent information as used by Konchog. The problem is that it was hard/impossible to distinguish between a sibling and a parent in one case while the tree was being moved around, and I needed that to decide if I was going to reduce the right hand side or not while closing a gap.
Left/size vs left/right: you could store it either way in the database, but I think left/right can be more efficient as you can index the DB with a multicolumn index (left, right) which can then be used to speed up ancestor queries, which are of type:
left < curLeft AND right > curLeft

Tested on Ubuntu 22.04, PostgreSQL 14.5, SQLite 3.34.0.

A: If elements are in tree order, as shown in your example, you can use something like the following Python example:
delimiter = '.'
stack = []
for item in items:
  while stack and not item.startswith(stack[-1]+delimiter):
    print "</div>"
    stack.pop()
  print "<div>"
  print item
  stack.append(item)

What this does is maintain a stack representing the current position in the tree. For each element in the table, it pops stack elements (closing the matching divs) until it finds the parent of the current item. Then it outputs the start of that node and pushes it to the stack.
If you want to output the tree using indenting rather than nested elements, you can simply skip the print statements to print the divs, and print a number of spaces equal to some multiple of the size of the stack before each item. For example, in Python:
print "  " * len(stack)

You could also easily use this method to construct a set of nested lists or dictionaries.
Edit: I see from your clarification that the names were not intended to be node paths. That suggests an alternate approach:
idx = {}
idx[0] = []
for node in results:
  child_list = []
  idx[node.Id] = child_list
  idx[node.ParentId].append((node, child_list))

This constructs a tree of arrays of tuples(!). idx[0] represents the root(s) of the tree. Each element in an array is a 2-tuple consisting of the node itself and a list of all its children. Once constructed, you can hold on to idx[0] and discard idx, unless you want to access nodes by their ID.

A: Think about using nosql tools like neo4j for hierarchial structures.
e.g a networked application like linkedin uses couchbase (another nosql solution)
But use nosql only for data-mart level queries and not to store / maintain transactions


Q: Can we use dagger only in some parts of an android app? Until now we have not used dagger in our android app. We want to use dagger for whatever new code that we write in our app from now on. Is this possible ? I just started exploring dagger and i have a doubt if this is possible.

A: Yes , It is possible. You can add dagger for ongoing project and use it.


Q: GridGain Error : java.lang.NoClassDefFoundError: org/apache/hadoop/mapreduce/JobContext I have configured gridgain-hadoop-os-6.6.2.zip, and followed steps as mentioned in docs/hadoop_readme.pdf . started gridgain using bin/ggstart.sh command, now am running a simple wordcount code in gridgain with hadoop-2.2.0. using command
hadoop jar $HADOOP_HOME/share/hadoop/mapreduce/*-mapreduce-examples-*.jar wordcount /input /output

Steps I tried:
Step 1:
Extracted hadoop-2.2.0 and gridgain-hadoop-os-6.6.2.zip file in usr/local folder and changed name for gridgain folder as "gridgain".
Step 2:
 Set the path for export GRIDGAIN_HOME=/usr/local/gridgain.. and path for hadoop-2.2.0 with JAVA_HOME as
    # Set Hadoop-related environment variables
export HADOOP_PREFIX=/usr/local/hadoop-2.2.0
export HADOOP_HOME=/usr/local/hadoop-2.2.0
export HADOOP_MAPRED_HOME=/usr/local/hadoop-2.2.0
export HADOOP_COMMON_HOME=/usr/local/hadoop-2.2.0
export HADOOP_HDFS_HOME=/usr/local/hadoop-2.2.0
export YARN_HOME=/usr/local/hadoop-2.2.0
export HADOOP_CONF_DIR=/usr/local/hadoop-2.2.0/etc/hadoop
export GRIDGAIN_HADOOP_CLASSPATH='/usr/local/hadoop-2.2.0/lib/*:/usr/local/hadoop-2.2.0/lib/*:/usr/local/hadoop-2.2.0/lib/*'

Step 3:
now i run command as bin/setup-hadoop.sh ... answer Y to every prompt.
Step 4:
started gridgain using command
bin/ggstart.sh
Step 5:
now i created dir and uploaded file using :
hadoop fs -mkdir /input

hadoop fs -copyFromLocal $HADOOP_HOME/README.txt /input/WORD_COUNT_ME.
txt

Step 6:
Running this command gives me error:
hadoop jar $HADOOP_HOME/share/hadoop/mapreduce/*-mapreduce-examples-*.
jar wordcount /input /output

Getting following error:
15/02/22 12:49:13 INFO Configuration.deprecation: mapred.working.dir is deprecated. Instead, use mapreduce.job.working.dir
15/02/22 12:49:13 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_091ebfbd-2993-475f-a506-28280dbbf891_0002
15/02/22 12:49:13 INFO mapreduce.JobSubmitter: Cleaning up the staging area /tmp/hadoop-yarn/staging/hduser/.staging/job_091ebfbd-2993-475f-a506-28280dbbf891_0002
java.lang.NullPointerException
    at org.gridgain.client.hadoop.GridHadoopClientProtocol.processStatus(GridHadoopClientProtocol.java:329)
    at org.gridgain.client.hadoop.GridHadoopClientProtocol.submitJob(GridHadoopClientProtocol.java:115)
    at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:430)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1268)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1265)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:415)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1491)
    at org.apache.hadoop.mapreduce.Job.submit(Job.java:1265)
    at org.apache.hadoop.mapreduce.Job.waitForCompletion(Job.java:1286)
    at org.apache.hadoop.examples.WordCount.main(WordCount.java:84)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.hadoop.util.ProgramDriver$ProgramDescription.invoke(ProgramDriver.java:72)
    at org.apache.hadoop.util.ProgramDriver.run(ProgramDriver.java:144)
    at org.apache.hadoop.examples.ExampleDriver.main(ExampleDriver.java:74)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:212)

and gridgain console error as:
sLdrId=a0b8610bb41-091ebfbd-2993-475f-a506-28280dbbf891, userVer=0, loc=true, sampleClsName=java.lang.String, pendingUndeploy=false, undeployed=false, usage=0]], taskClsName=o.g.g.kernal.processors.hadoop.proto.GridHadoopProtocolSubmitJobTask, sesId=e129610bb41-091ebfbd-2993-475f-a506-28280dbbf891, startTime=1424589553332, endTime=9223372036854775807, taskNodeId=091ebfbd-2993-475f-a506-28280dbbf891, clsLdr=sun.misc.Launcher$AppClassLoader@1bdcbb2, closed=false, cpSpi=null, failSpi=null, loadSpi=null, usage=1, fullSup=false, subjId=091ebfbd-2993-475f-a506-28280dbbf891], jobId=f129610bb41-091ebfbd-2993-475f-a506-28280dbbf891]]
java.lang.NoClassDefFoundError: org/apache/hadoop/mapreduce/JobContext
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2585)
    at java.lang.Class.getConstructor0(Class.java:2885)
    at java.lang.Class.getConstructor(Class.java:1723)
    at org.gridgain.grid.hadoop.GridHadoopDefaultJobInfo.createJob(GridHadoopDefaultJobInfo.java:107)
    at org.gridgain.grid.kernal.processors.hadoop.jobtracker.GridHadoopJobTracker.job(GridHadoopJobTracker.java:959)
    at org.gridgain.grid.kernal.processors.hadoop.jobtracker.GridHadoopJobTracker.submit(GridHadoopJobTracker.java:222)
    at org.gridgain.grid.kernal.processors.hadoop.GridHadoopProcessor.submit(GridHadoopProcessor.java:188)
    at org.gridgain.grid.kernal.processors.hadoop.GridHadoopImpl.submit(GridHadoopImpl.java:73)
    at org.gridgain.grid.kernal.processors.hadoop.proto.GridHadoopProtocolSubmitJobTask.run(GridHadoopProtocolSubmitJobTask.java:54)
    at org.gridgain.grid.kernal.processors.hadoop.proto.GridHadoopProtocolSubmitJobTask.run(GridHadoopProtocolSubmitJobTask.java:37)
    at org.gridgain.grid.kernal.processors.hadoop.proto.GridHadoopProtocolTaskAdapter$Job.execute(GridHadoopProtocolTaskAdapter.java:95)
    at org.gridgain.grid.kernal.processors.job.GridJobWorker$2.call(GridJobWorker.java:484)
    at org.gridgain.grid.util.GridUtils.wrapThreadLoader(GridUtils.java:6136)
    at org.gridgain.grid.kernal.processors.job.GridJobWorker.execute0(GridJobWorker.java:478)
    at org.gridgain.grid.kernal.processors.job.GridJobWorker.body(GridJobWorker.java:429)
    at org.gridgain.grid.util.worker.GridWorker.run(GridWorker.java:151)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: Failed to load class: org.apache.hadoop.mapreduce.JobContext
    at org.gridgain.grid.kernal.processors.hadoop.GridHadoopClassLoader.loadClass(GridHadoopClassLoader.java:125)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    ... 20 more
Caused by: java.lang.ClassNotFoundException: org.apache.hadoop.mapreduce.JobContext
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at org.gridgain.grid.kernal.processors.hadoop.GridHadoopClassLoader.loadClassExplicitly(GridHadoopClassLoader.java:196)
    at org.gridgain.grid.kernal.processors.hadoop.GridHadoopClassLoader.loadClass(GridHadoopClassLoader.java:106)
    ... 21 more
^[[B

Help here....
Edited Here :
raj@ubuntu:~$ hadoop classpath
/usr/local/hadoop-2.2.0/etc/hadoop:/usr/local/hadoop-2.2.0/share/hadoop/common/lib/*:/usr/local/hadoop-2.2.0/share/hadoop/common/*:/usr/local/hadoop-2.2.0/share/hadoop/hdfs:/usr/local/hadoop-2.2.0/share/hadoop/hdfs/lib/*:/usr/local/hadoop-2.2.0/share/hadoop/hdfs/*:/usr/local/hadoop-2.2.0/share/hadoop/yarn/lib/*:/usr/local/hadoop-2.2.0/share/hadoop/yarn/*:/usr/local/hadoop-2.2.0/share/hadoop/mapreduce/lib/*:/usr/local/hadoop-2.2.0/share/hadoop/mapreduce/*:/usr/local/hadoop-2.2.0/contrib/capacity-scheduler/*.jar
raj@ubuntu:~$ jps
3529 GridCommandLineStartup
3646 Jps
raj@ubuntu:~$ echo $GRIDGAIN_HOME
/usr/local/gridgain
raj@ubuntu:~$ echo $HADOOP_HOME
/usr/local/hadoop-2.2.0
raj@ubuntu:~$ hadoop version
Hadoop 2.2.0
Subversion https://svn.apache.org/repos/asf/hadoop/common -r 1529768
Compiled by hortonmu on 2013-10-07T06:28Z
Compiled with protoc 2.5.0
From source with checksum 79e53ce7994d1628b240f09af91e1af4
This command was run using /usr/local/hadoop-2.2.0/share/hadoop/common/hadoop-common-2.2.0.jar
raj@ubuntu:~$ cd /usr/local/hadoop-2.2.0/share/hadoop/mapreduce
raj@ubuntu:/usr/local/hadoop-2.2.0/share/hadoop/mapreduce$ ls
hadoop-mapreduce-client-app-2.2.0.jar     hadoop-mapreduce-client-hs-2.2.0.jar          hadoop-mapreduce-client-jobclient-2.2.0-tests.jar  lib
hadoop-mapreduce-client-common-2.2.0.jar  hadoop-mapreduce-client-hs-plugins-2.2.0.jar  hadoop-mapreduce-client-shuffle-2.2.0.jar          lib-examples
hadoop-mapreduce-client-core-2.2.0.jar    hadoop-mapreduce-client-jobclient-2.2.0.jar   hadoop-mapreduce-examples-2.2.0.jar                sources
raj@ubuntu:/usr/local/hadoop-2.2.0/share/hadoop/mapreduce$

A: I configured exactly the versions you mentioned (gridgain-hadoop-os-6.6.2.zip + hadoop-2.2.0) -- the "wordcount" sample works fine.

[UPD after question's author log analysis:]
Raju, thanks for the detailed logs.
The cause of the problem are incorrectly set env variables
export HADOOP_MAPRED_HOME=${HADOOP_HOME}
export HADOOP_COMMON_HOME=${HADOOP_HOME}
export HADOOP_HDFS_HOME=${HADOOP_HOME}

You explicitly set all these variables to ${HADOOP_HOME} value, what is wrong. This causes GG to compose incorrect hadoop classpath, as seen from the below GG Node log:
+++ HADOOP_PREFIX=/usr/local/hadoop-2.2.0
+++ [[ -z /usr/local/hadoop-2.2.0 ]]
+++ '[' -z /usr/local/hadoop-2.2.0 ']'
+++ HADOOP_COMMON_HOME=/usr/local/hadoop-2.2.0
+++ HADOOP_HDFS_HOME=/usr/local/hadoop-2.2.0
+++ HADOOP_MAPRED_HOME=/usr/local/hadoop-2.2.0
+++ GRIDGAIN_HADOOP_CLASSPATH='/usr/local/hadoop-2.2.0/lib/*:/usr/local/hadoop-2.2.0/lib/*:/usr/local/hadoop-2.2.0/lib/*'

So, to fix the issue please don't set unnecessary env variables. JAVA_HOME  and HADOOP_HOME is quite enough, nothing else is needed.

A: many thnaks to Ivan, thanks for your help and support, the solution you gave was good to get me out of the problem.
The issue was not to set other hadoop related environment variables. this is enough to set.
JAVA_HOME , HADOOP_HOME and GRIDGAIN_HOME


Q: How to change a predeterminate underline color in an Input with Materialize w/Ruby on Rails I really try so hard to change the underline color but I can't, I don't know where do that, please help me!

          <%= form_for(:session, url: login_path) do |f| %>

          <%= f.label :email %>
          <%= f.email_field :email, class: 'form-control white-text' %>

          <%= f.label :password %>
          <%= f.password_field :password, class: 'form-control white-text' %>

          <%= f.submit "Log in", class: "btn" ,style:"color:white;background-color: #EEB756;" %>
          <% end %>

A: You can change the class .input-field, and add more specific selector, for example:
.input-field input

or to email type of input
.input-field input[type=email]

or to focused field:
.input-field input[type=text]:focus

And set the border style:
.input-field input[type=text]:focus{
     border-bottom: 1px solid #aaa;
}

You can read more in Materialize documentation: http://materializecss.com/forms.html
EDIT: edited as suggested by @Toby1Kenobi

A: According to the docs you can change the underline colour in CSS by modifying the colour of border-bottom and box-shadow of the element containing the input element (that is the one with the class input-field)
so maybe it would be something like this:
.input-field input[type=email] {
   border-bottom: 1px solid red;
   box-shadow: 0 1px 0 0 red;
}


Q: How to delete a pointer belonging to an object stored in a vector? I have a Containing class, a Contained class, and a Data class. That Containing class holds a vector of Contained objects. The Contained class holds a pointer to a data object, allocated on the heap in Contained's constructor. However, I can't deallocate it in the destructor, since the vector will create copies of Contained and then destroy them, thus destroying the data pointer even in the copy we're using.
TL;DR Here's some code to explain:
class Data {
    public:
        Data();
};

class Contained {
    private:
        Data* data;
    public:
        Contained();
        // what should I add ? a copy constructor ? an assignement operator ? and how
};

class Container {
    private:
        vector<Contained> rooms;
    public:
        //some member functions
};

Contained::Contained() {
    data = new Data();
}

Where do I delete data ?

A: Using RAII(Resource Acquisition is Initialization)
Add a destructor to the Contained class:
Contained::~Contained() {
    delete data;
}

This will ensure whenever your contained object goes out of scope, it will automatically delete the data pointer it has. So if you do
//delete first element
rooms.erase(rooms.begin());

data ptr of that object will automatically be deleted.
Using smart pointers
Use std::unique_ptr<T>.
class Contained {
    private:
        std::unique_ptr<Data> data;
    public:
        Contained();
        // what should I add ? a copy constructor ? an assignement operator ? and how
};

and in the constructor:
Contained::Contained() {
    data = std::make_unique<Data>();
}

Using smart pointers i.e., (unique_ptr, shared_ptr) ensures your pointer will automatically delete when no one is owning it. Since you can not copy unique_ptr but only move it, you should define a move constructor and move assignment operator on the Contained class.
Contained::Contained(Contained&& other)
    : data(std::move(other.data))
{}

Contained& operator=(Contained&& rhs) {
    if (this != &other) {
        data = std::move(rhs.data);
    }
    return *this;
}


Q: Finding if file exists ANYWHERE c# For starters, I'm quite new to C#.
How would I go about checking if a (.exe) file exists anywhere on a pc's memory?
I tried to google an answer, but only ones I came across required you to specify a directory where to look from.
I'm building an application that launches certain apps which the user selects, hence why I can't know the directory where the file is in. Is there a way of checking it without a directory, aka check if the file exists anywhere on the pc?
Alternatively, is there a way to handle an error where the selected file is not found?


Q: apt-get fails on i386/debian docker image I have a 32-bit Ubuntu server, running 17.10 Artful & with docker.io installed (my understanding is this is the only version available for 32-bit)
jonny@grizzly ~ $ lsb_release -cs
artful
jonny@grizzly ~ $ apt list | grep docker.io

WARNING: apt does not have a stable CLI interface. Use with caution in scripts.

4384:docker.io/artful,now 1.13.1-0ubuntu6 i386 [installed]

I am attempting to use i386/debian image (I have also tried 32bit/Ubuntu with similar results), and having issues with apt-get. Sources appear to be configured sensibly, but apt-get update gets 404 errors. Hitting the same URLs (with .gz appended) from browser works fine. ping works within Docker image, wget & curl aren't available so haven't been able to further diagnose possible network issues.
jonny@grizzly ~ $ docker run -it i386/debian /bin/bash
root@1023ad95222c:/# more /etc/apt/sources.list
deb http://deb.debian.org/debian stretch main
deb http://security.debian.org/debian-security stretch/updates main
deb http://deb.debian.org/debian stretch-updates main
root@1023ad95222c:/# apt-get update
Ign:1 http://security.debian.org/debian-security stretch/updates InRelease
Ign:2 http://security.debian.org/debian-security stretch/updates Release
Ign:3 http://deb.debian.org/debian stretch InRelease
Ign:4 http://deb.debian.org/debian stretch-updates InRelease
Ign:5 http://deb.debian.org/debian stretch Release
Ign:6 http://security.debian.org/debian-security stretch/updates/main all Packages
Ign:7 http://security.debian.org/debian-security stretch/updates/main i386 Packages
Ign:6 http://security.debian.org/debian-security stretch/updates/main all Packages
Ign:7 http://security.debian.org/debian-security stretch/updates/main i386 Packages
Ign:8 http://deb.debian.org/debian stretch-updates Release
Ign:6 http://security.debian.org/debian-security stretch/updates/main all Packages
Ign:7 http://security.debian.org/debian-security stretch/updates/main i386 Packages
Ign:9 http://deb.debian.org/debian stretch/main all Packages
Ign:6 http://security.debian.org/debian-security stretch/updates/main all Packages
Ign:10 http://deb.debian.org/debian stretch/main i386 Packages
Ign:11 http://deb.debian.org/debian stretch-updates/main i386 Packages
Ign:12 http://deb.debian.org/debian stretch-updates/main all Packages
Ign:7 http://security.debian.org/debian-security stretch/updates/main i386 Packages
Ign:9 http://deb.debian.org/debian stretch/main all Packages
Ign:6 http://security.debian.org/debian-security stretch/updates/main all Packages
Ign:10 http://deb.debian.org/debian stretch/main i386 Packages
Ign:7 http://security.debian.org/debian-security stretch/updates/main i386 Packages
Ign:11 http://deb.debian.org/debian stretch-updates/main i386 Packages
Ign:6 http://security.debian.org/debian-security stretch/updates/main all Packages
Ign:12 http://deb.debian.org/debian stretch-updates/main all Packages
Err:7 http://security.debian.org/debian-security stretch/updates/main i386 Packages
  404   [IP: 212.211.132.250 80]
Ign:9 http://deb.debian.org/debian stretch/main all Packages
Ign:10 http://deb.debian.org/debian stretch/main i386 Packages
Ign:11 http://deb.debian.org/debian stretch-updates/main i386 Packages
Ign:12 http://deb.debian.org/debian stretch-updates/main all Packages
Ign:9 http://deb.debian.org/debian stretch/main all Packages
Ign:10 http://deb.debian.org/debian stretch/main i386 Packages
Ign:11 http://deb.debian.org/debian stretch-updates/main i386 Packages
Ign:12 http://deb.debian.org/debian stretch-updates/main all Packages
Ign:9 http://deb.debian.org/debian stretch/main all Packages
Ign:10 http://deb.debian.org/debian stretch/main i386 Packages
Ign:11 http://deb.debian.org/debian stretch-updates/main i386 Packages
Ign:12 http://deb.debian.org/debian stretch-updates/main all Packages
Ign:9 http://deb.debian.org/debian stretch/main all Packages
Err:10 http://deb.debian.org/debian stretch/main i386 Packages
  404   [IP: 130.89.148.14 80]
Err:11 http://deb.debian.org/debian stretch-updates/main i386 Packages
  404   [IP: 130.89.148.14 80]
Ign:12 http://deb.debian.org/debian stretch-updates/main all Packages
Reading package lists... Done
W: The repository 'http://security.debian.org/debian-security stretch/updates Release' does not have a Release file.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.
W: The repository 'http://deb.debian.org/debian stretch Release' does not have a Release file.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.
W: The repository 'http://deb.debian.org/debian stretch-updates Release' does not have a Release file.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: Failed to fetch http://security.debian.org/debian-security/dists/stretch/updates/main/binary-i386/Packages  404   [IP: 212.211.132.250 80]
E: Failed to fetch http://deb.debian.org/debian/dists/stretch/main/binary-i386/Packages  404   [IP: 130.89.148.14 80]
E: Failed to fetch http://deb.debian.org/debian/dists/stretch-updates/main/binary-i386/Packages  404   [IP: 130.89.148.14 80]
E: Some index files failed to download. They have been ignored, or old ones used instead.

I've tried various different mirrors I've found online with no difference. I've also tried a few different versions/tags of the i386/debian docker image. No proxy used to access internet on this server. Are there any other steps I may be missing here?


Q: Why is my User Group Information Do as not passing my keytab token to my HDFS access method When I attempt to list the files in a HDFS directory I am receiving the following error:
main] ERROR com.pr.hdfs.common.hadooputils.HdfsUtil - Failed to connect to hdfs directory /HDFS/Datastore/DB
org.apache.hadoop.security.AccessControlException: SIMPLE authentication is not enabled.  Available:[TOKEN, KERBEROS]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.apache.hadoop.ipc.RemoteException.instantiateException(RemoteException.java:106)
at org.apache.hadoop.ipc.RemoteException.unwrapRemoteException(RemoteException.java:73)

The code I am using although being accessed as scala is the following Java:
public static List<Path> listHdfsFilePaths(final FileSystem hdfs, final String directory) throws IOException
 {
  final List<Path> result = new ArrayList<>();
  final FileStatus[] fileStatuses;
  try
  {
     fileStatuses = hdfs.listStatus(new Path(directory));
     for (final FileStatus fileStatus : fileStatuses)
     {
        result.add(fileStatus.getPath());
     }
  }
  catch (final IOException e)
  {
     LOGGER.error("Failed to connect to hdfs directory " + directory, e);
     throw e;
  }
  return result;
}

The scala code wraps a User Group Information doas to access the folder:
val auctions = ugiDoAs(ugi){
  val hdfs = FileSystem.get(hadoopConf)
  HdfsUtils.listHdfsFilePaths(hdfs, "/HDFS/Datastore/DB/")
}

The ugiDoAs method is specified as:
def ugiDoAs[T](ugi: Option[UserGroupInformation])(code: => T) = ugi match {
   case None => code
   case Some(u) => u.doAs(new PrivilegedExceptionAction[T] {
     override def run(): T = code
   })
 }

The ugiDoAs wrapper works for reading from Zookeeper, reading from Hbase but just not accessing HDFS in this case.
Also, my ugi variable contains the keytab and the principal needed.


Q: Unable to resolve dependency tree after upgrading node, failing on node-sass After upgrading Node to the latest version, I start getting these error messages when I tried npm audit fix --force. It seems like I'm unable to fix my dependency tree issues. I've tried to search for solutions to this error extensively and tried many different solutions but none worked. Should the only solution be downgrading back to an older Node version?
npm ERR! path /Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-sass
npm ERR! command failed
npm ERR! command sh -c node scripts/build.js
npm ERR! Building: /usr/local/bin/node /Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-gyp/bin/node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp verb cli [
npm ERR! gyp verb cli   '/usr/local/bin/node',
npm ERR! gyp verb cli   '/Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-gyp/bin/node-gyp.js',
npm ERR! gyp verb cli   'rebuild',
npm ERR! gyp verb cli   '--verbose',
npm ERR! gyp verb cli   '--libsass_ext=',
npm ERR! gyp verb cli   '--libsass_cflags=',
npm ERR! gyp verb cli   '--libsass_ldflags=',
npm ERR! gyp verb cli   '--libsass_library='
npm ERR! gyp verb cli ]
npm ERR! gyp info using node-gyp@3.7.0
npm ERR! gyp info using node@16.13.0 | darwin | x64
npm ERR! gyp verb command rebuild []
npm ERR! gyp verb command clean []
npm ERR! gyp verb clean removing "build" directory
npm ERR! gyp verb command configure []
npm ERR! gyp verb check python checking for Python executable "python2" in the PATH
npm ERR! gyp verb `which` succeeded python2 /usr/bin/python2
npm ERR! gyp verb check python version `/usr/bin/python2 -c "import platform; print(platform.python_version());"` returned: "2.7.16\n"
npm ERR! gyp verb get node dir no --target version specified, falling back to host node version: 16.13.0
npm ERR! gyp verb command install [ '16.13.0' ]
npm ERR! gyp verb install input version string "16.13.0"
npm ERR! gyp verb install installing version: 16.13.0
npm ERR! gyp verb install --ensure was passed, so won't reinstall if already installed
npm ERR! gyp verb install version is already installed, need to check "installVersion"
npm ERR! gyp verb got "installVersion" 9
npm ERR! gyp verb needs "installVersion" 9
npm ERR! gyp verb install version is good
npm ERR! gyp verb get node dir target node version installed: 16.13.0
npm ERR! gyp verb build dir attempting to create "build" dir: /Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-sass/build
npm ERR! gyp verb build dir "build" dir needed to be created? /Users/Mac/Desktop/Projects/folder/Website/filder/node_modules/node-sass/build
npm ERR! gyp verb build/config.gypi creating config file
npm ERR! gyp verb build/config.gypi writing out config file: /Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-sass/build/config.gypi
npm ERR! (node:19391) [DEP0150] DeprecationWarning: Setting process.config is deprecated. In the future the property will be read-only.
npm ERR! (Use `node --trace-deprecation ...` to show where the warning was created)
npm ERR! gyp verb config.gypi checking for gypi file: /Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-sass/config.gypi
npm ERR! gyp verb common.gypi checking for gypi file: /Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-sass/common.gypi
npm ERR! gyp verb gyp gyp format was not specified; forcing "make"
npm ERR! gyp info spawn /usr/bin/python2
npm ERR! gyp info spawn args [
npm ERR! gyp info spawn args   '/Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-gyp/gyp/gyp_main.py',
npm ERR! gyp info spawn args   'binding.gyp',
npm ERR! gyp info spawn args   '-f',
npm ERR! gyp info spawn args   'make',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-sass/build/config.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-gyp/addon.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/Users/Mac/.node-gyp/16.13.0/include/node/common.gypi',
npm ERR! gyp info spawn args   '-Dlibrary=shared_library',
npm ERR! gyp info spawn args   '-Dvisibility=default',
npm ERR! gyp info spawn args   '-Dnode_root_dir=/Users/Mac/.node-gyp/16.13.0',
npm ERR! gyp info spawn args   '-Dnode_gyp_dir=/Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-gyp',
npm ERR! gyp info spawn args   '-Dnode_lib_file=/Users/Mac/.node-gyp/16.13.0/<(target_arch)/node.lib',
npm ERR! gyp info spawn args   '-Dmodule_root_dir=/Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-sass',
npm ERR! gyp info spawn args   '-Dnode_engine=v8',
npm ERR! gyp info spawn args   '--depth=.',
npm ERR! gyp info spawn args   '--no-parallel',
npm ERR! gyp info spawn args   '--generator-output',
npm ERR! gyp info spawn args   'build',
npm ERR! gyp info spawn args   '-Goutput_dir=.'
npm ERR! gyp info spawn args ]
npm ERR! No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.
npm ERR!
npm ERR! No receipt for 'com.apple.pkg.DeveloperToolsCLILeo' found at '/'.
npm ERR!
npm ERR! No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'.
npm ERR!
npm ERR! gyp: No Xcode or CLT version detected!
npm ERR! gyp ERR! configure error
npm ERR! gyp ERR! stack Error: `gyp` failed with exit code: 1
npm ERR! gyp ERR! stack     at ChildProcess.onCpExit (/Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-gyp/lib/configure.js:345:16)
npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:390:28)
npm ERR! gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:290:12)
npm ERR! gyp ERR! System Darwin 19.6.0
npm ERR! gyp ERR! command "/usr/local/bin/node" "/Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
npm ERR! gyp ERR! cwd /Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-sass
npm ERR! gyp ERR! node -v v16.13.0
npm ERR! gyp ERR! node-gyp -v v3.7.0
npm ERR! gyp ERR! not ok
npm ERR! Build failed with error code: 1

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/Mac/.npm/_logs/2021-11-24T18_21_54_491Z-debug.log

A: First solution
Make sure your nodejs version is not superior than the latest stable one. For that you can use n package from npm:
npm install -g n
n stable
# if one of the commands does not pass, you may need to use sudo
sudo npm install -g n
sudo n stable

Then you would wanna use sass package instead of node-sass, as it's deprecated. And for that run those commands:
npm uninstall node-sass --save
npm install sass --save

Second solution
If you need or want node-sass for some reasons, you should downgrade your nodejs version to like v14. For that you can use n package from npm:
npm install -g n
n 14
# if one of the commands does not pass, you may need to use sudo
sudo npm install -g n
sudo n 14

A: I got rid of everything and re-installed Xcode, Node and node-sass again, and the issue is resolved.


Q: Uninstall a Component in vue.js I installed this component in my application. I would like to uninstall it now. How can I do that ?


Q: Angular Material unit tests - Failed to find MatHarness element I am writing unit tests for my app which uses Angular Material.
I wanna make sure that there's a material card in the page. For this, I use the following code:
  let loader: HarnessLoader;
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;
  let authService: jasmine.SpyObj<AuthService>;

  beforeEach(async () => {
    authService = jasmine.createSpyObj<AuthService>(['authenticate', 'logout']);
    await TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [LoginComponent],
      providers: [{ provide: AuthService, useValue: authService }]
    })
      .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    loader = TestbedHarnessEnvironment.loader(fixture);
    fixture.detectChanges();
  });

   it('should display a material card', async () => {
    const card = await loader.getHarness(MatCardHarness);
    expect(card).toBeTruthy();
  });

But, this returns the error:
Error: Failed to find element matching one of the following queries:
        (MatCardHarness with host element matching selector: ".mat-card")

Here's my HTML:
<mat-card class="custom-class">

Sign In

</mat-card>

I'll be able to solve this by adding mat-card class to the <mat-card> element. But isn't it supposed to work without manually adding the class? Is there anything wrong with the way I set up my tests?

A: Try importing MatCardModule into you TestBed configuration.
import { MatCardModule } from '@angular/material/card';

beforeEach(async () => {
  await TestBed.configureTestingModule({
    imports: [
      RouterTestingModule,
      MatCardModule,
    ],
    declarations: [LoginComponent],
    providers: [{ provide: AuthService, useValue: authService }]
  }).compileComponents();
});


Q: What is the technology most commonly used for iPhone - iPad communications? What is the most commonly used technology for communicating between an application running on an iPad and one on an iPhone?  For example, the famous Scrabble application uses device-to-device communication to host the game board on the iPad and the letters on the iPhone.

A: Bluetooth P2P connection.
Check that


Q: How to open/run YML compose file? How can I open/run a YML compose file on my computer? I've installed Docker for Windows and Docker tools but couldn't figure out how.

A: If you are asking how to open YAML files, then you can use some common editors like NotePad++ in windows or vim in linux.
If your question is about running the compose yaml file, then run this command from the directory where compose file is residing:
docker-compose -f {compose file name} up

You can avoid -f if your filename is docker-compose.yml

A: To manage .yml files you have to install and use Docker Compose.
Installation instructions can be found here: https://docs.docker.com/compose/install/
After the installation, go to your docker-compose.yml directory and then execute docker-compose up to create and start services in your docker-compose.yml file.
If you need more information, take a look to Docker Compose docs: https://docs.docker.com/compose


Q: How can my Spring integration tests create their own schema based on the model in a HSQL database? Writting some integration tests in Spring (Like in this question) I will like to avoid the work of a big script to create all tables in HSQL:

<jdbc:script location="classpath:createSchema.sql" />

As Spring is creating and updating my development tables from the model automagically. How could I tell Spring to do the same things for my integration tests?
My datasource file is
<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns=          "http://www.springframework.org/schema/beans"
    xmlns:xsi=      "http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context=  "http://www.springframework.org/schema/context"
    xmlns:jee=      "http://www.springframework.org/schema/jee"
    xmlns:p=        "http://www.springframework.org/schema/p"
    xmlns:jdbc=     "http://www.springframework.org/schema/jdbc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context               http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee                   http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/jdbc                  http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd">

    <!-- Usamos HSQLDB para hacer las pruebas con in-memory db -->
    <jdbc:embedded-database id="dataSource" type="HSQL">
        <jdbc:script location="classpath:create_schema.sql"/>
        <jdbc:script location="classpath:import.sql"/>
    </jdbc:embedded-database>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="com.myProject.model" />
        <property name="hibernateProperties">
        <props>
            <prop key="hibernate.default_schema">TESTING</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
            <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
</beans>

Update: After NimChimpsky answer I had included the schema name in hibernate properties and created a script with just:
CREATE SCHEMA TESTING

After trying the first insert int the import.sql script I see:
org.hsqldb.hsqlexception user lacks privilege or object not found [MyTable]

A: You still need to create schema manually - but literally only the create schema my-schema-name statement, let hibernate create the tables
<jdbc:embedded-database id="dataSource" type="HSQL">
  <jdbc:script location="classpath:create_schema.sql"/>
</jdbc:embedded-database>

If populating the database with values is a problem, yeah it is. No shortcuts really.
And the import script will have to run after the tables are created, in a postconstruct method probably.

A: I solved the issue with the help of geoand comment. (Thanks, you should have posted it as an answer). But let me share more information to make future reader's life easier.
First. It seems that telling that you have an script to initializa database makes hibernate to avoid the creation proccess. I changed the code embedded elemento to:
<jdbc:embedded-database id="dataSource" type="HSQL"/>

Hibernate will automatically execute import.sql from the classpath (at least in Create or Create-Drop mode) so there was no need to indicate further scripts.  As Spring test framework does rollback the transaction you do no need to restore the database after each test.
Second, I had some problems with my context configuration that needed to be solved if I wanted Spring to create my schema. The best way to do it was to set the ignore failures attribute to "ALL" and look and the logs.
Third. Using HSQL for a few things MySQL for others has its own issues. Syntax is sometimes different and I had to fix my import.sql to become compatible with both databases.
Appart from that, it works:
@ContextConfiguration(locations={"file:src/test/resources/beans-datasource.xml",
                     "file:src/main/webapp/WEB-INF/applicationContext.xml",
                                 "file:src/main/webapp/WEB-INF/my-servlet.xml"})
        @Configuration
        @RunWith(SpringJUnit4ClassRunner.class)
        public static class fooTest{

            @Inject BeanInterface myBean;

            @Test
            @Transactional
            public void fooGetListTest(){

                assertTrue("Expected a non-empty list", myBean.getList().size() > 0 );
            }
        }
    }


Q: Ajax call include not works in Wordpress I have a PHP file that I call with Cron Job and I need it separately from the rest of code. So, I have a button that call AJAX request from my dashboard. The Ajax function in my Wordpress plugin includes the file (process.php), this in turn, includes another file (snippets.php).
If I call process.php directly, it works perfectly, but not from Ajax call.
Folder structure
plugin.php
plugin.js
snippets.php
processes/process.php

plugin.js
jQuery.ajax({
type: 'GET',
url: ajaxurl,
data : {
action : 'process',
}
})

plugin.php
function process(){
include_once( 'processes/process.php' );
}
add_action( 'wp_ajax_process', 'process' );

process.php
include_once('../snippets.php')
//here not includes 'snippets.php'

A: You should use relative includes from their own file, otherwise, it will run from the current path. To force this you can use __DIR__  and start with a slash
plugin.php
function process(){
include_once(__DIR__.'/processes/process.php' );
}
add_action('wp_ajax_process', 'process' );

process.php
include_once(__DIR__.'/../snippets.php');
//here not includes 'snippets.php'

Also, you forgot the semicolumn ; in process.php


Q: Unit tests for a custom Date Serializer I have recently started writing tests in Java and I am having some problem with the tests for the following class. How to write correctly tests for TestDateTimeSerializer class in such a form.
public class TestDateTimeSerializer extends JsonSerializer<LocalDateTime> {
    public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

    @Override
    public void serialize(LocalDateTime dt, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException {
        if (dt == null) {
            gen.writeNull();
        } else {
            gen.writeString(dt.format(FORMATTER));
        }
    }
}

this class is used here
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonFormat(with = JsonFormat.Feature.ACCEPT_CASE_INSENSITIVE_PROPERTIES)
public class TestRequest implements ITestResponse {
    @JsonProperty("TestID")
    private Long testID;
    @JsonSerialize(using = TestDateTimeSerializer.class)
    private LocalDateTime lastUpdateDate;
}

A: Make JsonGenerator as mock object, then verify its method call.
@ExtendWith(MockitoExtension.class)
class TestDateTimeSerializerTest {
    @Mock
    JsonGenerator generator;       // JsonGenerator is mock
    @Mock
    SerializerProvider provider;

    @Test
    void test() throws IOException {
        TestDateTimeSerializer serializer = new TestDateTimeSerializer();
        LocalDateTime now = LocalDateTime.now();

        // run your method
        serializer.serialize(now, generator, provider);

        // assert mocked generator's method call
        verify(generator).writeString(ArgumentMatchers.anyString());
    }
}

Mockito API doc : https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#1
you can find more example and usage.

A: Please try this:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.junit.Before;
import org.junit.Test;

import java.time.LocalDateTime;

import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE_TIME;
import static org.junit.Assert.*;

public class TestDateTimeSerializerSerializerTest {

        private ObjectMapper mapper;
        protected TestDateTimeSerializer serializer;

        @Before
        public void setup() {
            mapper = new ObjectMapper();
            serializer = new TestDateTimeSerializer();

            SimpleModule module = new SimpleModule();
            module.addSerializer(LocalDateTime.class, serializer);
            mapper.registerModule(module);
        }

        @Test
        public void testSerializeNonNull() throws JsonProcessingException {
            LocalDateTime ldt = LocalDateTime.parse("2016-10-06T10:40:21.124", ISO_LOCAL_DATE_TIME);

            String serialized = mapper.writeValueAsString(ldt);

            assertEquals("equal strings", "\"2016-10-06T10:40:21.124Z\"", serialized);
        }

        @Test
        public void testSerializeNull() throws JsonProcessingException {
            LocalDateTime ldt = null;

            String serialized = mapper.writeValueAsString(ldt);

            assertEquals("equal strings", "null", serialized);
        }

    }


Q: Access nested model attributes I have following setup:
class EmpsController < ApplicationController
  def new
    @emp = Emp.new
    @unit_options = Unit.all.collect{|unit| [unit.name, unit.id] }
  end

  def create
    @emp = Emp.new(emp_params)
    @emp.save!
    redirect_to :action => :list
  end

  def destroy
    @emp = Emp.find([:id])
    @emp.destroy
    redirect_to :action => :list
  end

  def list
    @emps = Emp.all
  end

  def emp_params
    params.require(:emp).permit(:name, :unit_id)
  end

 end

Model:
class Emp < ApplicationRecord
    has_one :units
    accepts_nested_attributes_for :units
end

Form:

 List of Employees:

<% @emps.each do |u| %>

<%= u.id %>	 <%= u.name %>	  <%= u.unit_id %>	   <%= link_to "Delete", u, :method => :delete %>

<% end %>

All I want to do is to print (in table above) unit attribute called :name related with Emp printed Emp object.
Found various related solution but they do not apply to my case.

A: First, don't use :units as the association name, it "has one unit" no "units", Rails convention over configuration expects the association to be singular.
Then you should be able to do some_emp.unit.name.
Or you can use method delegation:
class Emp < ApplicationRecord
  has_one :unit

  delegate :name, to: :unit
end

And now you can do some_emp.name.


Q: What is the Java equivalent of Objective-C's NSDictionary? What is the closest implementation of Objective-C's NSDictionary in Java?  To me, it looks like HashMap<String, Object>, but I'm very new to Objective-C.
Thanks

A: NSDictionary is a class cluster (see the "Class Cluster" section in The Cocoa Fundamentals Guide), meaning that the actual implementation is hidden from you, the API user. In fact, the Foundation framework will choose the appropriate implementation at run time based on amount of data etc. In addition, NSDictionary can take any id as a key, not just NSString (of course, the -hash of the key object must be constant).
Thus, closest analog is probably Map<Object,Object>.

A: For practical usage:
HashMap<String, Object> would be the way to go for a simple, non-parallel dictionary.
However, if you need something that is thread-safe (atomic), you'd have to use
HashTable<String, Object>
which is thread safe, but - notably - does not accept null as a valid value or key.

A: I'm admittedly an Android newbie, but to me ContentValues seems to be the closest thing to NSDictionary.


Q: Indexing lists of list/vectors Data
lst <- list(1, 1:3, 2:4)
ind <- c(1, 2, 2)

Problem
I can guarantee that length(ind) == length(lst) and now I want to get the 1st element of the the first element of lst, then the second element of the second element and finally the second element of the third element.
With a loop I could do something like
sapply(seq_along(ind), function(i) lst[[i]][[ind[i]]])

So my question is whether I need the loop or is there any smart indexing technique which I am not aware of? Background of the question is that I have the impression that I do not make best use of R's  capability to do incredible stuff with smart indexing (like indexing a matrix with another matrix).

A: We can use mapply to get the corresponding element of 'lst' based on the index in 'ind'.
mapply(`[`, lst, ind)
#[1] 1 2 3


Q: $elemMatch projection in node.js dbo.collection("users")
            .findOne({email: emailGiven, "friends.email": element.email},
                     { friends: { $elemMatch: { email: element.email } } },
                     function(errT, resultT) {})

I have the query above in node.js but for some reason the query's elemMatch part doesn't work on node.js but when I execute  the same query in mongo terminal it works, so I'm thinking maybe node.js doesn't support $elemMatch? If this is the case, could anyone tell me what would be the equivalent of this query in node.js?
Sample data from my DB:
/* 4 */
{
    "_id" : ObjectId("5ad20cef8248544860ce3dc1"),
    "username" : "test",
    "email": "",
    "fullName" : "",
    "friends" : [{email: "",
                 status :""}],
    "alarms": [ {"id":111,
        "title": "TITLE",
        "location": "",
        "startTime": "10-10-1996 10:18:00",
        "endTime": "10-10-1996 10:18:00" }, {},{}

    ],
     "pnumber" : ""
}

A: The node.js driver findOne has a different call signature than the findOne in the MongoDB shell. You pass the field selection object as the projection element of the options parameter:
dbo.collection("users")
    .findOne({"friends.email": email},
             {projection: { friends: { $elemMatch: { email: email } } } },
             function(errT, resultT) {...});

A: If you want to find for any values which is stored in some variable, you use regex for that. Your query should look like
dbo.collection("users").findOne({
    email: new RegExp(emailGiven, 'i'),
    "friends.email": new RegExp(element.email, 'i')
}, {
    friends: {
        $elemMatch: {
            email: new RegExp(element.email, 'i')
        }
    }
}, function(errT, resultT) {})

i is for case insensitive comparison here


Q: Nested list with TAL I'm using Chameleon in the Pyramids Framework and want to repeat nested list while rendering the template.
My minimized HTML-Code is:
1. <ul>
2.  <li tal:repeat="item items">
3.      <input tal:attributes="id item.id; onclick item.url">
4.      <label tal:repeat="premise item.values" tal:attributes="for item.id; id premise.id">
5.          <label tal:replace="premise.title"/>
6.      </label>
7.      <label tal:attributes="for item.id" tal:content="item.title"/>
8.  </li>
9. </ul>

Whereby I got the following json-Data
[{
    'url': 'location.href="http://..."',
    'values':
    [{
        'id': '70',
        'title': 'some title 1'
    }],
    'attitude': 'justify',
    'id': '68',
    'title': 'some title 2'
}, {
    'url': 'null',
    'values':
    [{
        'id': '0',
        'title': 'some title 3!
    }],
    'attitude': 'justify',
    'id': '0',
    'title':
    'some title 4'
}]

If I kill HTML-lines 4.-6., everything is fine, otherwise Pyramid/Chameleon throws:
  File "/usr/local/lib/python3.4/dist-packages/chameleon/tal.py", line 471, in __call__
    iterable = list(iterable) if iterable is not None else ()
TypeError: 'builtin_function_or_method' object is not iterable

Anyone some idea?

A: Thanks to #pyramid in the IRC i got the first hint, which is mentioned in the comment. But..never ever name a key 'value' or 'values'!


Q: Angular JS - Date changes when submitting to $http - Timezone issue I am having a strange problem where a Date changes when it is passed to API through $http.put, I suspect a timezone issue:
Datepicker triggers ng-change event - console.log:
Tue Jun 10 2014 00:00:00 GMT+0100 (GMT Summer Time)
Passed to API using Angular $http.put...
When it hits Fiddler:
StartDate=2014-06-09T23:00:00.000Z
As you can see the date changes from 10th June to 9th June.
How can I stop this change of date? Is it the timezone causing the change? Both the API and client side are running on Localhost.
Further to this:
When the field is clicked a second time and the datepicker launched / date selected, this second time the problem does not appear:
Console.log:
Wed Aug 06 2014 22:00:00 GMT+0100 (GMT Summer Time)
Fiddler data received:
StartDate=2014-08-06T21:00:00.000Z

A: I think it is a TZ issue, b/c the difference between your GMT+0100 and your StartDate=2014-06-09T23:00:00.000Z is 5 hours.
.
The issue:
Your local time is currently BST (British Summer Time) equivalent to GMT +1
This is going to be the default time when you make your API call.
However, the API was written by Google in California, and they are rather egocentric.  Therefore, they're automatically converting the time since you're not providing any date formatting "instructions".
In other words, Chrome does the conversion for you nicely when you print to the console.log(), but when you make your $http.put, Angular, without explicit formatting for you, makes the call using it's default TZ (which is PST)
.
Resolution
You need to force the date formatting to your locale.

*

*Angular template
{{ date_expression | date : 'yyyy-MM-dd HH:mm:ss'}}

*In JavaScript
$filter('date')(date, 'yyyy-MM-dd HH:mm:ss')

*using localization
<html>
  <head>
    <title>My Angular page</title>
    <script src="angular-locale_en-uk.js"></script>
    ...
  </head>
  <body>
    ...
  </body>
</html>


Q: Lotus Notes - Column view as Totals: Total showing not 0.00 even if there aren't no docs saved I have a view which contains a column ( as Total ) . Even, there aren't any docs created, the column shows:
165.65 ( as total ) and not 0.00 ( as it should be )
Any suggestions?

A: Does the view show documents in a response hierarchy? Probably there is an "orphaned" response (Replication conflict or other reason) that is not shown in the view as the parent document is missing, but still is counted in the total- column. Try disable response- hierarchy in the View- Properties and check if there is such a document.
An additional reason for the total not being 0 could also be a document that is protected by a readers- field. Server will add this document to the totals (as View- Index is created by the server) whereas the Designer / User does not see the document.
If you know, what is in the Readers- Field (Role, GroupName, etc.) then make yourself member of that field (by assigning the Role to yourself or add yourself to the group).
If you don't know, what's in there (or something went wrong filling the readers field, e.g. forgot to tick the "multi value"- property), then you need somebody with "Full Access Administration"- right to the server. This Admin- function ovverrides all Reader- fields and makes the document visible to you.


Q: Adding another variable information or adding weight into stat_density_2d Below is a simple code to produce stat_density_2d plot of X~Y.
plot_data <-
  data.frame(X = c(rnorm(300, 3, 2.5), rnorm(150, 7, 2)),
             Y = c(rnorm(300, 6, 2.5), rnorm(150, 2, 2)),
             Z = c(rnorm(300, 60, 5), rnorm(150, 40, 5)),
             Label = c(rep('A', 300), rep('B', 150)))
ggplot(plot_data, aes(x=X, y=Y)) +
  stat_density_2d(geom = "polygon", aes(alpha = stat(level), fill = Label))

As I understand, the density is based on the count of X~Y. My question is can I use Z as the density? Or perhaps, add Z as weight to the density? I'm not sure I'm making sense here. As it is the density of X~Y is useful for me. But I'm just wondering if I can add the information in Z into the density of X~Y.
Perhaps you have alternative idea? Both the density of X~Y and Z are information that I want to convey. Currently I'm separating them into separate density X~Y, X~Z, Y~Z, and they're all useful to me (using my data of course).
Edit2, Manual Calculation Plan:
I'm still working on this as I go. This is a general idea of what I'm planning to do.

*

*Instead of using stat_density_2d, I plan to calculate the density itself using the method used in stat_density_2d, which is MASS::kde2d().

*I would then use interpolation such as akima::interp, to interpolate the Z into X~Y grid.

*I would then multiply Z unto the density of X~Y (from 1) as a form of weightage.

*Plot them again using ggplot.

Edit 3: Update with code of applying Z as weightage towards density of X~Y.
library(ggplot2)
library(data.table)
library(ggnewscale)
library(akima)
library(MASS)

plot_data <-
  data.frame(X = c(rnorm(300, 3, 2.5), rnorm(150, 7, 2)),
             Y = c(rnorm(300, 6, 2.5), rnorm(150, 2, 2)),
             Z = c(rnorm(300, 60, 5), rnorm(150, 60, 5)),
             Label = c(rep('A', 300), rep('B', 150)))
setDT(plot_data)

#Interpolation of Z into X~Y grid for Label A
int_plot_data_A=with(plot_data[Label=="A"],interp(x=X,y=Y,z=Z,nx=100,ny=100))
rownames(int_plot_data_A$z)=int_plot_data_A$x
colnames(int_plot_data_A$z)=int_plot_data_A$y
plot_data_Z_A <- melt(int_plot_data_A$z)
names(plot_data_Z_A) <- c("X", "Y", "Z")

#Calculation of kde2d for Label A
plot_data_A=plot_data[Label=="A"]
kde2d_A=kde2d(plot_data_A$X,plot_data_A$Y,n=100)
rownames(kde2d_A$z)=kde2d_A$x
colnames(kde2d_A$z)=kde2d_A$y
plot_kde_A <- melt(kde2d_A$z, na.rm = TRUE)
names(plot_kde_A) <- c("X", "Y", "Z")

#Interpolation of Z into X~Y grid for Label B
int_plot_data_B=with(plot_data[Label=="B"],interp(x=X,y=Y,z=Z,nx=100,ny=100))
rownames(int_plot_data_B$z)=int_plot_data_B$x
colnames(int_plot_data_B$z)=int_plot_data_B$y
plot_data_Z_B <- melt(int_plot_data_B$z)
names(plot_data_Z_B) <- c("X", "Y", "Z")

#Calculation of kde2d for Label B
plot_data_B=plot_data[Label=="B"]
kde2d_B=kde2d(plot_data_B$X,plot_data_B$Y,n=100)
rownames(kde2d_B$z)=kde2d_B$x
colnames(kde2d_B$z)=kde2d_B$y
plot_kde_B <- melt(kde2d_B$z, na.rm = TRUE)
names(plot_kde_B) <- c("X", "Y", "Z")

#Filtering out values under 0.01. It makes the plot better. This is subjective
setDT(plot_kde_A)
plot_kde_A[Z<0.01]=NA
setDT(plot_kde_B)
plot_kde_B[Z<0.01]=NA

#Calculate for A weighted with Z
plot_kde_A_Weight_Z=plot_kde_A
plot_kde_A_Weight_Z$Z=plot_kde_A_Weight_Z$Z*plot_data_Z_A$Z

#Calculate for B weighted with Z
plot_kde_B_Weight_Z=plot_kde_B
plot_kde_B_Weight_Z$Z=plot_kde_B_Weight_Z$Z*plot_data_Z_B$Z

ggplot() +
  geom_contour_fill(data=plot_kde_A,aes(x=X,y=Y,z=Z),alpha=0.8,bins=10) +
  scale_fill_continuous(low = "white", high = "blue") +
  geom_contour(data=plot_kde_A_Weight_Z,aes(x=X,y=Y,z=Z),bins=10) +
  new_scale_fill() +
  geom_contour_fill(data=plot_kde_B,aes(x=X,y=Y,z=Z),alpha=0.8,bins=10) +
  scale_fill_continuous(low = "white", high = "red") +
  geom_contour(data=plot_kde_B_Weight_Z,aes(x=X,y=Y,z=Z),color="red",bins=10)

Edit 1: After searching around while dropping keyword ggplot, I found something called kernel density estimation And this post, Plot contours of distribution on all three axes in 3D plot, feels like this is what I'm looking for to visualise my data. Unfortunately, I found out that ggplot does not have 3D functionality. There's a 4 years package called gg3D? plotly seems to be the best candidate for this? The final figure in the post looks like what I'm trying to achieve.


Q: How to target specific Cucumber runner classes or feature files within Jenkins? Is it possible to target specific runner classes or feature files within Jenkins?
Let's say for example I have the following files.
Runner classes:
RunnerClass1.java
RunnerClass1.java

Feature Files:
Login.feature
SignUp.feature

Is there a way to trigger specific runner classes or feature files within the Jenkins UI, I know you can use specific plugins such as: 'Parameterised / String Parameters', has anyone else found a solution to target specific tests from Jenkins?
thanks for your help

A: You can tag your test cases and maven will be able to run them by these tags.
For example, When I have Login cases with @Login tags and I want to run them with Maven, I am using the following terminal script :
mvn clean test -Dcucumber.options="--tags @Login"


Q: How to revoke Users Access On Schema in Azure SQL? I have a requirement where I need to revoke users access on a particular schema as we will be purging that schema and its table in future.
Currently, the process followed to create Schema and grant access is like below,

*

*Create Schema

*Create DB Role

*Create Azure AD Group on azure portal

*Create DB User with the same name as AD group

*Then, we run EXEC sp_addrolemember command to add DB user to DB role in database.

*Finally, we run the Grant command to give permission (Select, Insert etc) on Schema to DB Role.

Now, whenever any new user need access to that schema we simply add him in the Azure AD group and he is able to see and access that schema.
However, when I Revoke the access of user by removing him from Azure AD group he is still able to see that Schema.
As I am not an expert in SQL so I am not sure what am I missing in order to revoke his access.
I also tried Revoke command like below but still the user is able to see the schema.
REVOKE SELECT ON SCHEMA :: Schema_Name TO [DB Role]
Am I missing anything, can anyone please let me know the right steps to revoke user access so that they should not be able to see that schema anymore or should not be able to run any command on that schema not even select command?

A: Then, in addition to remove it from the AD group, try to deny permissions on the schema:
DENY SELECT,VIEW DEFINITION On SCHEMA::Schema_Name To [user_name]


Q: PopBackStack previous last fragment and check which fragment it is I got a few fragments in MainActivity which can be selected from Navigation Drawer. Now, whenever users press a profile button, it will jumps to UserProfile Fragment. If home button is pressed, it will pop back the last fragment. Since I've assigned each of the fragments a specific backstack name i.e .addToBackStack("abc"), how can I check what is the last fragment by using popBackStack() method ?

A: To get the last fragment:
FragmentManager fm = getSupportFragmentManager();
int lastFragEntry = fm.getBackStackEntryCount()-1;
String lastFragTag = fm.getBackStackEntryAt(lastFragEntry).getName();

Log.i("Last Fragment Tag->", lastFragTag);

NB: If you want to get the name/tag of last fragment, you also have to use the same Tag during fragment transaction:
ft.replace(android.R.id.container, fragment, "abc");
ft.addToBackStack("abc");

Hope this helps.


Q: How to convert mathematical expressions into C statement? How to convert each of the following mathematical expressions to its equivalent statement in C?

*

*1 / (x^2 + y^2)

*square root of (b^2 - 4ac)

A: *

*1.0 / (pow(x,2) + pow(y,2))

*sqrt(pow(b,2) - 4*a*c)
See pow() and sqrt() functions manual.
You can also write x*x instead of pow(x, 2). Both will have the exact same result and performance (the compiler knows what the pow function does and how to optimize it).

(For commenters)
GCC outputs the exact same assembler code for both of these functions:
double pow2_a(double x) {
    return pow(x, 2);
}

double pow2_b(double x) {
    return x * X;
}

Assembler:
    fldl    4(%esp)
    fmul    %st(0), %st
    ret