Class which shows relationship of members in a family [closed] - data-structures

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I want to create a class which can dynamically add the family members and his/her relationship with that member.
For Example:
In a family Father is one of the member and his wife is another member and they have children. But the number of children in each family are different(eg only one son/only one daughter/one son one daughter and so on). Therefore number of children decided at run time.
I have one tables:
Members tables: In which details of all the members such as member_reference_number, name, address, phone number etc. are to be store. member_reference_number is a primary key which identifies the unique member from database. This table is for any member(father, mother,son, daughter etc).
I want to use that member_reference_number to show the relationship.

Object oriented + Inheritence can help you. I think you mean this structure:
class Person
{};
class Father : public Person
{};
class Mother : public Person
{};
class Child : public Father, public Mother
{};
class Son : public Child
{};
class Daughter: public Child
{};
class Family
{
Father father;
Mother mother;
std::vector<Child> children;
};
+------------------+
| Person |
+------------------+
^ ^
| |
| |
\ \
+------------------+ +------------------+
| Father | | Mother |
+------------------+ +------------------+
^ ^
| |
| |
| |
\ \
+------------------+
| Child |
+------------------+
^ ^
| |
| |
\ \
+------------------+ +------------------+
| Son | | Daughter |
+------------------+ +------------------+

I Think you can have tree with FamilyTreeNode.
where FamilyTreeNode (structure) can have
-> Male -- String
-> Female -- String
-> NumberOfChildern -- int
-> Children -- array of FamilyTreeNodes (dynamic array).
Here if anyone is not married then make the opp sex to null.

Related

Eloquent model relationship for final table

I've the following tables
Cities (City model)
+----+-------+
| id | name |
+----+-------+
| 1 | tokyo |
+----+-------+
events (Event model)
+----+--------------------+---------+
| id | title | city_id |
+----+--------------------+---------+
| 1 | Biggest event ever | 1 |
+----+--------------------+---------+
event_user_applications (EventUserApplication model)
+----+----------+---------+
| id | event_id | user_id |
+----+----------+---------+
| 1 | 1 | 1 |
+----+----------+---------+
How do I get the city on EventUserApplication model.
I tried both of this in the EventUserApplication
public function city()
{
// return $this->belongsTo('App\Model\City', 'city_id')->using('App\Model\Event', 'event_id');
// return $this->hasOneThrough('App\Model\City', 'App\Model\Event', 'city_id', 'id');
}
Can't get any of this to work. Already spent hours. Please help. Thank you in advance.
I solved it with the help of my friend. This is what I did to get the city.
$applications = EventUserApplication::with(
'user:id,name,phone,email,date_of_birth',
'event:id,title,area_id,area_city_id',
'event.city' // nester eager loading
)->latest()->get();
In the Event model, I already had this
public function city()
{
return $this->belongsTo('App\Model\City', 'area_city_id');
}
It's the Nester Eager Loading which was needed.
In that case you can use hasOnThrough relationship EventUserApplication has One city Through Event.
Edit:The 5th parameter should be event_id and there should be another parameter which is id (foreign key of event table)

Spark: How to create a sessionId based on userId and timestamp

Sorry for a newbie question.
Currently I have log files which contains fields such as: userId, event, and timestamp, while lacking of the sessionId. My aim is to create a sessionId for each record based on the timestamp and a pre-defined value TIMEOUT.
If the TIMEOUT value is 10, and sample DataFrame is:
scala> eventSequence.show(false)
+----------+------------+----------+
|uerId |event |timestamp |
+----------+------------+----------+
|U1 |A |1 |
|U2 |B |2 |
|U1 |C |5 |
|U3 |A |8 |
|U1 |D |20 |
|U2 |B |23 |
+----------+------------+----------+
The goal is:
+----------+------------+----------+----------+
|uerId |event |timestamp |sessionId |
+----------+------------+----------+----------+
|U1 |A |1 |S1 |
|U2 |B |2 |S2 |
|U1 |C |5 |S1 |
|U3 |A |8 |S3 |
|U1 |D |20 |S4 |
|U2 |B |23 |S5 |
+----------+------------+----------+----------+
I find one solution in R (Create a "sessionID" based on "userID" and differences in "timeStamp"), while I am not able to figure it out in Spark.
Thanks for any suggestions on this problem.
Shawn's answer regards on "How to create a new column", while my aim is to "How to create an sessionId column based on timestamp". After days of struggling, the Window function is applied in this scenario as a simple solution.
Window is introduced since Spark 1.4, it provides functions when such operations is needed:
both operate on a group of rows while still returning a single value for every input row
In order to create a sessionId based on timestamp, first I need to get the difference between user A's two immediate operations. The windowDef defines the Window will be partition by "userId" and ordered by timestamp, then diff is a column which will return a value for each row, whose value will be 1 row after the current row in the partition(group), or null if the current row is the last row in this partition
def handleDiff(timeOut: Int) = {
udf {(timeDiff: Int, timestamp: Int) => if(timeDiff > timeOut) timestamp + ";" else timestamp + ""}
}
val windowDef = Window.partitionBy("userId").orderBy("timestamp")
val diff: Column = lead(eventSequence("timestamp"), 1).over(windowDef)
val dfTSDiff = eventSequence.
withColumn("time_diff", diff - eventSequence("timestamp")).
withColumn("event_seq", handleDiff(TIME_OUT)(col("time_diff"), col("timestamp"))).
groupBy("userId").agg(GroupConcat(col("event_seq")).alias("event_seqs"))
Updated:
Then exploit the Window function to apply the "cumsum"-like operation (provided in Pandas):
// Define a Window, partitioned by userId (partitionBy), ordered by timestamp (orderBy), and delivers all rows before current row in this partition as frame (rowsBetween)
val windowSpec = Window.partitionBy("userId").orderBy("timestamp").rowsBetween(Long.MinValue, 0)
val sessionDf = dfTSDiff.
withColumn("ts_diff_flag", genTSFlag(TIME_OUT)(col("time_diff"))).
select(col("userId"), col("eventSeq"), col("timestamp"), sum("ts_diff_flag").over(windowSpec).alias("sessionInteger")).
withColumn("sessionId", genSessionId(col("userId"), col("sessionInteger")))
Previously:
Then split by ";" and get each session, create a sessionId; afterwards split by "," and explodes to final result. Thus sessionId is created with the help of string operations.
(This part should be replaced by cumulative sum operation instead, however I did not find a good solution)
Any idea or thought about this question is welcomed.
GroupConcat could be found here: SPARK SQL replacement for mysql GROUP_CONCAT aggregate function
Reference: databricks introduction
dt.withColumn('sessionId', expression for the new column sessionId)
for example:
dt.timestamp + pre-defined value TIMEOUT

Laravel Categories Map Relationship

I have the following three tables but I don't know how to build a relation between the category and the other data type, in this case 'Page':
posts:
post_id | title | slug
1 | Test | test
2 | Another test | another test
catgory_map:
id | category_id | referrer_id | category_map_type
1 | 2 | 1 | Post
2 | 3 | 2 | Post
3 | 2 | 9 | Page
category
id | name
1 | Laravel
2 | Zend2
3 | Phalcon
So whenever I read a Category I like to be able to do something like this
foreach($category->destinations) ...
I have tried until now with hasManyThrough but it didn't work.
What you have is a many-to-many relation with some additional filtering on the relationship (for the category_map_type). Try this:
Post model
public function categories(){
return $this->belongsToMany('Category', 'category_map', 'referrer_id')
->where('category_map_type', 'Post');
}
Category model
public function posts(){
return $this->belongsToMany('Post', 'category_map', 'category_id', 'referrer_id')
->where('category_map_type', 'Post');
}
Usage
$category = Category::find(1);
foreach($category->posts as $post){
// ...
}
(And the same goes for Post)
You might also want to look into polymorphic many-to-many relations

Laravel multiple whereHas criteria for relationship

I have two tables - contacts and visits:
Contacts Table
id | name
----- | -------
1 | Joe
2 | Sally
Visits Table
id | contact_id | pathname | referrer
----- | ------- | ------- | -------
1 | 1 | about | google
2 | 1 | pricing | null
3 | 1 | signup | null
4 | 2 | about | null
5 | 2 | signup | null
Using eloquent, I would like to retrieve all contacts that have a both a pathname = 'signup' AND a referrer = 'google'.
What I've got so far is:
Contact::whereHas('visits', function($query) {
$query->where('pathname','=','signup');
})
->orWhereHas('visits', function($query) {
$query->where('referrer','=','google');
})
->get();
Which properly retrieves all contacts that have visited either the pricing OR signup page.
However, this example would also retrieve Sally (from the example table above), since she visited signup, but was not referred by google. I need a way to only retrieve Joe, who was both referred by google and visited pricing.
Any ideas? Thanks in advance!
You can use:
Contact::whereHas('visits', function($query) {
$query->where('pathname','=','signup');
})
->whereHas('visits', function($query) {
$query->where('referrer','=','google');
})
->get();
A refined version of the code above:
Contact::whereHas('visits', function($query) {
$query->where('pathname','signup')->where('referrer','google');
})->get();
Several noteworthy points:
You can chain where() clauses within a closure.
The default operator for a where clause is =, so you can omit it.
Use multiple whereHas() clauses, when accessing multiple related models.

Bitwise operations in Postgres

I have the following tables:
types | id | name
------+----+----------
1 | A
2 | B
4 | C
8 | D
16| E
32| F
and
vendors | id | name | type
--------+----+----------+-----
1 | Alex | 2 //type B only
2 | Bob | 5 //A,C
3 | Cheryl | 32 //F
4 | David | 43 //F,D,A,B
5 | Ed | 15 //A,B,C,D
6 | Felix | 8 //D
7 | Gopal | 4 //C
8 | Herry | 9 //A,D
9 | Iris | 7 //A,B,C
10| Jack | 23 //A,B,C,E
I would like to query now:
select id, name from vendors where type & 16 >0 //should return Jack as he is type E
select id, name from vendors where type & 7 >0 //should return Ed, Iris, Jack
select id, name from vendors where type & 8 >0 //should return David, Ed, Felix, Herry
What is the best possible index for tables types and vendors in postgres? I may have millions of rows in vendors. Moreover, what are the tradeoffs of using this bitwise method compared with Many To Many relation using a 3rd table? Which is better?
Use can use partial indices to work around the fact that "&" isn't an indexable operator (afaik):
CREATE INDEX vendors_typeA ON vendors(id) WHERE (type & 2) > 0;
CREATE INDEX vendors_typeB ON vendors(id) WHERE (type & 4) > 0;
Of course, you'll need to add a new index every time you add a new type. Which is one of the reasons for expanding the data into an association table which can then be indexed properly. You can always write triggers to maintain a bitmask table additionally, but use the many-to-many table to actually maintain the data normally, as it will be much clearer.
If your entire evaluation of scaling and performance is to say "I may have millions of rows", you haven't done enough to start going for this sort of optimisation. Create a properly-structured clear model first, optimise it later on the basis of real statistics about how it performs.

Resources