I have an Entity which in turn refers to same table which is its parent. Below is the table which describes it more better.
| ID | Source_ID |
+----+----------+
| 1 | null |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 4 |
Now, when I am at ID = 5, I need to fetch its ultimate parent, which is ID = 1.
I tried writing a function which is as below:
<entity> ultimateparententity;
internal <entity> FetchParentComponentRecursive(<entity> entity)
{
if (component.ParentEntity!= null)
{
FetchParentComponentRecursive(entity.ParentEntity);
}
else
{
ultimateparententity = entity;
return component;
}
return entity;
}
I am using variable declared at class level to know the ultimate parent. I am returning variable "Entity" which is never used later, but ultimateparententity is what is used. This approach works, but I am not too happy with this. Any directions will be helpful.
I'm not too familiar with C#, but the general structure of your recursive function looks off.
Try something along the lines of:
internal <entity> FetchParentComponentRecursive(<entity> entity)
{
if (component.ParentEntity == null)
{
return component;
}
else
{
return FetchParentComponentRecursive(entity.ParentEntity);
}
}
By the way, this very much depends on there being no circular references in your data set.
Related
I am new to Cucumber. I have a requirement to use variables instead of actual values in a feature file example. Actual values are to be populated in a separate property file.
Sample feature file:
#tag
Feature: Add an element to stack
The user pushes an element. It gets added to stack
#tag1
Scenario: Push element to empty stack
Given Stack is empty
When User pushes an element
Then stack should have only one element
#tag2
Scenario Outline: Push element to stack
Given Stack has {initial} elements
When User adds {new} element
Then Length of stack increases to {new_size}
| initial | new | new_size |
| 1 | 2 | 2|
| 5 | 9 | 6|
| 0 | 3 | 1|
The output example should be like:
| initial | new | new_size |
| {val1_1} |{val1_2} | {val1_3}|
| {val2_1} |{val2_2} | {val2_3}|
I have used "{}" instead of "<>" as am not able to print elements inside <> in pre-formatted code
Use scenario outlines with examples. Its will solve you data input based queries. For example,
#tag2
Scenario Outline: Push element to stack
Given Stack has <initial> elements
When User adds <new> element
Then Length of stack increases to <new_size>
Examples:
| initial | new | new_size |
| 1 | 2 | 2 |
| 5 | 9 | 6 |
| 0 | 3 | 1 |
And your step definition would be like this,
Given("^Stack has (.*) elements$", (String initial) -> {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
});
Similarly do for the other query parameters like (name, new_size).
I have this grammar with common prefixes (<id>) and I want to transform it to avoid them.
void Components() : {}
{
(Read() | Write())* (<id>Assignment())* <id>Declaration() (Read() | Write() | <id>(Assignment() | Declaration()))*
}
The problem is (<id>Assignment())* <id>Declaration(). The grammar can have 0 or more Assignments/Read/Write statments but at least 1 Declaration and then any statment/declaration in any order.
Refactoring this is easy, but I probably wouldn't do it. I'd probably look ahead a little further. Here are two solutions
Factor out the <id>
void Components() : {}
{
(Read() | Write())*
<id>
(Assignment() <id>)*
Declaration()
( Read()
| Write()
| <id> (Assignment() | Declaration())
)*
}
Use longer lookahead
void Components() : {}
{
(Read() | Write())*
(LOOKAHEAD( 2 ) <id> Assignment())*
<id> Declaration()
( Read()
| Write()
| LOOKAHEAD( 2 ) <id> Assignment()
| <id> Declaration())
)*
}
Flow defines so called "Maybe types". I.e. ?string is similar to string | null | void (void is a type of value undefined).
Is there something like general type that can be of any value but null and undefined? Basically something like $Diff<$Diff<any, null>, void> if $Diff operator was able to operate on non-object types.
There is no some "magic" type for this, but something like this should work: string | number | boolean | {} | []
It is possible using the NonMaybeType Flow utility type: see $NonMaybeType
$NonMaybeType<T> converts a type T to a non-maybe type. In other words, the values of $NonMaybeType<T> are the values of T except for null and undefined.
// #flow
type MaybeName = ?string;
type Name = $NonMaybeType<MaybeName>;
('Gabriel': MaybeName); // Ok
(null: MaybeName); // Ok
('Gabriel': Name); // Ok
(null: Name); // Error! null can't be annotated as Name because Name is not a maybe type
If you need only a "shallow" type that does not allow null or undefined:
export type NotNullOrUndefined =
| string
| number
| bigint
| []
| {}
Now, in case you want to propagate the not null and not undefined requirement in values nested under objects and arrays you will need the following:
export type NotNullOrUndefined =
| string
| number
| bigint
| NotNullOrUndefined[]
| { [k: string]: NotNullOrUndefined }
Suppose we had a table of vendors in a SQL database that we want to load into F#:
+----+--------+--------+
| ID | Name | Parent |
+----+--------+--------+
| 1 | Nest | 2 |
| 2 | Google | NULL |
| 3 | Apple | NULL |
+----+--------+--------+
Using type providers it is easy enough to get the table into F#, but suppose we wanted to then convert the data into a sequence of Vendors, where Vendor is a type like this:
Vendor = {ID: int; Name: String; Parent: Vendor option}
How would one go about doing that? The issue is that when creating the sequence of Vendors we can't map to each row a particular Vendor, since we don't have the sequence of Vendors yet. It would be good to also assume that the application allows for cycles (A could have B as a parent and B could have A as a parent), although in the case of vendors that doesn't really make sense.
You could instead define the Vendor type as:
Vendor = {ID: int; Name: String; ParentID: int option}
But this seems much less elegant, since every time you would want to reference the parent vendor you'd have to do some sort of lookup. Is there a known solution to this? It seems like a situation that could occur often (especially when dealing with graphs or trees).
It also seems like a solution could involve some sort of lazy evaluation, but it's not clear to me how the Lazy<'T> type in F# could be applied here.
It's not a particularly elegant solution, but the one that uses lazy evaluation for the parent would look something like this: you would have two types, one that matches the schema of your table and one recursive:
type Flat = { ID: int; Name: string; ParentID : int option}
type Recursive = { ID: int; Name: string; Parent: Lazy<Recursive> option}
Then let's set up something that looks like your table:
let records =
[
{ ID = 1; Name = "Nest"; ParentID = Some 2 }
{ ID = 2; Name = "Google"; ParentID = None }
{ ID = 3; Name = "Apple"; ParentID = None }
{ ID = 4; Name = "Yin"; ParentID = Some 5 }
{ ID = 5; Name = "Yang"; ParentID = Some 4 }
]
|> List.map (fun x -> x.ID, x)
|> Map.ofList
let getRecord recID = records |> Map.find recID
And you can put it together like this:
let rec getRecordRecursive recID =
let record = getRecord recID
{
ID = record.ID
Name = record.Name
Parent =
record.ParentID
|> Option.map (fun pid ->
Lazy.Create <| fun () ->
getRecordRecursive pid)
}
So in a sense you're using the lazy type to delay the next step of recursion until you need it. Otherwise getRecordRecursive 4 would give you a stack overflow.
But there are tradeoffs - you no longer get nice behaved equality on such records, for instance. I'm not convinced you're not better off with Flat records in the long run.
Consider the following program (http://play.golang.org/p/IbAstvudtE):
package main
import (
"fmt"
)
func changeStringValueNotOK(dest *string, src string) {
dest = &src
}
func changeStringValueOK(dest *string, src string) {
*dest = src
}
func main() {
a := "Hello"
b := "World"
changeStringValueNotOK(&a, b)
fmt.Println(a) // still "Hello"
changeStringValueOK(&a, b)
fmt.Println(a) // now "World"
}
My goal is to call a function and change the value of string. Works fine with the second function, but not with the first.
Question: what is the meaning of *dest = src compared to dest = &src? I guess the former is "the contents of dest is now src" and the latter is "change the dest variable so that it now points to the address of src" which discards the previous value, but not the contents of a. But even if I am right, I don't understand how the *dest = src works.
I hope my question isn't too fuzzy.
*dest = src
is: Set the value pointed at by dest to the value in src. So it's effective.
dest = &src
is: Set the value of dest to the address of src. As dest is a formal parameter of changeStringValueNotOK the change (to the pointer only, not to the pointee) is visible only locally. As the changed value is not really used, it's total effect is a no operation.
Just to help visualize it graphically, in your main function you have this:
Data Variables
| ... |
-------
| Hello |<----- <a string>
-------
| World |<----- <b string>
-------
| ... |
When you provide the parameters to either of these functions, it becomes:
Data Parameters
| ... |
-------
| Hello |<----- <a string> <----- <dest *string>
-------
| World |<----------------------- <src string>
-------
| ... |
With that scenario, when you do *dest = src, you get:
Data Parameters
| ... |
-------
| Hello | ,- <a string> <---- <dest *string>
------- |
| World |<--/
| |<---------------------- <src string>
-------
| ... |
Note that this effectively changes a itself, so when you return to the prior scope, you'll observe the change.
On the other hand, if you do dest = &src, you'd instead get:
Data Parameters
| ... |
-------
| Hello | <dest *string> ----,
------- |
| World |<---------------------- <src string> <---/
-------
| ... |
Which doesn't solve your problem, because both dest and src are local to the functions they're in.
As a side note, this kind of parameter passing is a common C idiom, but in Go you'd generally change such a string by returning the new value instead.