Tuesday, February 10, 2015

Not In Clause in LINQ



Consider following code sample where we want to exclude all the Videos which are in dataset from List of videos we have.
For illustration we will create class as follows

public class Video
{
    private int _id;
    public int Id
    {
        get { return _id; }
        set { _id = value; }
    }

    private string _name;
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    private string _url;
    public string Url
    {
        get { return _url; }
        set { _url = value; }
    }
}
 
Now we will write two methods first one “GetVideos” which will emulate fetching video list from certain repository.

    public List<Video> GetVideos()
    {
        Video v1 = new Video { Id = 1, Name = "Video1", Url = "http://www.google.co.in" };
        Video v2 = new Video { Id = 2, Name = "Video2", Url = "http://www.google.co.in" };
        Video v3 = new Video { Id = 3, Name = "Video3", Url = "http://www.google.co.in" };
        Video v4 = new Video { Id = 4, Name = "Video4", Url = "http://www.google.co.in" };
        Video v5 = new Video { Id = 5, Name = "Video5", Url = "http://www.google.co.in" };
        Video v6 = new Video { Id = 6, Name = "Video6", Url = "http://www.google.co.in" };
        Video v7 = new Video { Id = 7, Name = "Video7", Url = "http://www.google.co.in" };
        Video v8 = new Video { Id = 8, Name = "Video8", Url = "http://www.google.co.in" };
        Video v9 = new Video { Id = 9, Name = "Video9", Url = "http://www.google.co.in" };
        Video v10 = new Video { Id = 10, Name = "Video10", Url = "http://www.google.co.in" };

        List<Video> Videos = new List<Video>();
        Videos.Add(v1);
        Videos.Add(v2);
        Videos.Add(v3);
        Videos.Add(v4);
        Videos.Add(v5);
        Videos.Add(v6);
        Videos.Add(v7);
        Videos.Add(v8);
        Videos.Add(v9);
        Videos.Add(v10);


        return Videos;
    }

 While second function “GetDataset” is having list of videos that need exclusion.

    public DataTable GetDataset()
    {
        DataTable dt = new DataTable();

        DataColumn VideoId = new DataColumn("VideoId", typeof(System.Int64));
        DataColumn VideoName = new DataColumn("Name", typeof(System.String));
        DataColumn Url = new DataColumn("Url", typeof(System.String));

        dt.Columns.Add(VideoId);
        dt.Columns.Add(VideoName);
        dt.Columns.Add(Url);

        DataRow dr1 = dt.NewRow();
        dr1["VideoId"] = 1;
        dr1["Name"] = "Video1";
        dr1["Url"] = "http://www.google.co.in";
        dt.Rows.Add(dr1);

        DataRow dr2 = dt.NewRow();
        dr2["VideoId"] = 2;
        dr2["Name"] = "Video2";
        dr2["Url"] = "http://www.google.co.in";
        dt.Rows.Add(dr2);

        DataRow dr3 = dt.NewRow();
        dr3["VideoId"] = 7;
        dr3["Name"] = "Video7";
        dr3["Url"] = "http://www.google.co.in";
        dt.Rows.Add(dr3);

        DataRow dr4 = dt.NewRow();
        dr4["VideoId"] = 8;
        dr4["Name"] = "Video8";
        dr4["Url"] = "http://www.google.co.in";
        dt.Rows.Add(dr4);

        DataRow dr5 = dt.NewRow();
        dr5["VideoId"] = 9;
        dr5["Name"] = "Video9";
        dr5["Url"] = "http://www.google.co.in";
        dt.Rows.Add(dr5);

        DataRow dr6 = dt.NewRow();
        dr6["VideoId"] = 10;
        dr6["Name"] = "Video10";
        dr6["Url"] = "http://www.google.co.in";
        dt.Rows.Add(dr6);

        return dt;
    }

Really LINQ Stuff is here:

In our your page load (say)  we will write linq query to read video list but after exclusion
 var v3 = from m in vids
                 where (
                     from d in dt.AsEnumerable()
                     select d["VideoId"].ToString()
                 ).Contains(m.Id.ToString()) ==false
                 select m;
 
where inner query below
                     from d in dt.AsEnumerable()
                     select d["VideoId"].ToString()

is selecting only Video id’s as string from DataTable that need to be excluded

one can see final result by binding linq output to  gridview.

steps through which we can go to result:Usually we are more concerned in final result than process that derives the solution,here how i made my way to solution,
Here is Complete Code of my page load event:
   if you want to use below code then make sure that in your aspx page there are required three grid views,I first make sure that my inner query give desired result then simply  merged two queries.

        DataTable dt = GetDataset();
        List<Video> vids = GetVideos();

        var v2 = from d in dt.AsEnumerable()
                 select d["VideoId"].ToString();
        GridView1.DataSource = v2;
        GridView1.DataBind();

        //intermediate query
        var v1 = from m in vids
                 select m;
        GridView2.DataSource = v1;
        GridView2.DataBind();

        //final merged query
        var v3 = from m in vids
                 where (
                     from d in dt.AsEnumerable()
                     select d["VideoId"].ToString()
                 ).Contains(m.Id.ToString()) ==false
                 select m;
        GridView3.DataSource = v3;
        GridView3.DataBind();


Sunday, February 8, 2015

Find Your Lucky Number using Your Name

Here is python code that calculate lucky number from your name

Code:

from __builtin__ import str
print "*** Welcome to Forcast by Name ***"
Name = raw_input("What is your first name ? ").strip()

Meaning_Dict ={
               '1':
               "Attractive personality. Magnetic charm. Superman/superwoman like vitality and physical energy. Incredibly active and gregarious. Enjoys outdoor activities and sports. Has friends and individuals in powerful positions. Good government connections. Intelligent, spectacular, flashy and successful. A loyal number for love and relationships.",
              
               '2':
               "Feminine and soft, emotional temperament. Fluctuating moods but intuitive, and possibly even clairvoyant abilities. Ingenious nature and kind-hearted expression of feelings. Loves family, mother and home life. Night owl who probably needs more sleep. Success with the public and/or women generally. ",
              
               '3':
               "Sociable, optimistic number with fortunate destiny. Attracts opportunities without too much effort. Great sense of timing. Religious or spiritual inclinations. Naturally drawn to investigate the meaning of life. Philosophical insight. Enjoys travel and explore the world and different cultures. ",
              
               "4":
               "Volatile character with many peculiar aspects. Likes to experiment and test novel experiences. Forward thinking, with many extraordinary friends. Gets bored easily so needs plenty of inspiring activities. Pioneering, technological and creative. Wilful and obstinate at times. Unforeseen events in life may be positive or negative. ",
              
               "5":
               "Sharp-wit, quick thinking with great powers of speech. Extremely active life; always on the go and lives on nervous energy. Youthful outlook and never grows old. Looks younger than actual age. Young friends and humorous disposition. Loves reading and writing. Great communicator. ",
              
               "6":
               "Delightful and charming personality. Graceful and eye-catching personality who cherishes and nourishes friends. Very active social life. Musical or creative interests. Great money making opportunities as well as numerous love affairs are indicated. Career in the public eye is quite likely. Loves family but is often troubled other divided loyalties with friends. ",
              
               "7":
               "Intuitive, spiritual and self sacrificing nature. Easily duped by those who need help. Loves to dream of life's possibilities. Has healing powers. Dreams are revealing and prophetic. Loves the water and will have many journeys in life.  Spiritual aspirations dominate worldly desires. ",
              
               "8":
               "Hard-working, ambitious person with slow yet certain achievements. Remarkable concentration and self-sacrifice for a chosen or objective. Financially focused but generous when a person's trust is gained. Proficient in one's chosen field but is a hard taskmaster. Demands perfection and needs to relax and enjoy life more. ",
              
               "9":
               "Extraordinary physical drive, desires and ambition. Sports and outdoor activities are major keys to health.  Confrontational but likes to work and play really hard. Protects and defends family, friends and territory. Individual tastes in life but is also self absorbed. Needs to listen to others' advice to gain greater success in life. "
            }


Ruling_Planet = {
                 '1':'Sun',
                 '2':'Moon',
                 '3':'Jupiter',
                
                 '4':'Uranus',
                 '5':'Mercury',
                 '6':'Venus',
                
                 '7':'Neptune',
                 '8':'Saturn',
                 '9':'Mars',
                }

Lucky_Dict = {
        'A': '1',
        'I': '1',
        'Q': '1' ,
        'J': '1',
        'Y':'1',
       
        'B':'2',
        'K':'2',
        'R':'2',
       
        'C':'3',
        'G':'3',
        'L':'3',
        'S':'3',
       
        'D':'4',
        'M':'4',
        'T':'4',
       
        'E':'5',
        'H':'5',
        'N':'5',
        'X':'5',
       
        'U':'6',
        'V':'6',
        'W':'6',
       
        'O':'7',
        'Z':'7',
       
        'F':'8',
        'P':'8'       
    }
luckyNo = 0
for c in Name.upper():
    luckyNo = luckyNo +  int(Lucky_Dict[c])
   
while len(str(luckyNo)) !=1:
    #print str(luckyNo)
    num =0  
    for x in str(luckyNo):
        num = num + int(x)
        luckyNo = str(num)  
   
   


print "Your Lucky No is:" + str(luckyNo)
print "**************FORCAST**********************"
print "What Astrologer Say About You:" + Meaning_Dict[luckyNo]
print "Ruling Planet:" + Ruling_Planet[luckyNo]

year_num = int(luckyNo) +  8//for calender year 2015

while len(str(year_num)) !=1:
    #print str(luckyNo)
    num =0  
    for x in str(year_num):
        num = num + int(x)
        year_num = str(num) 
       
print "Your Year No:" + str(year_num)


Output:


*** Welcome to Forcast by Name ***
What is your first name ? sangram desai
Your Lucky No is:6

**************FORCAST**********************

What Astrologer Say About You:Delightful and charming personality. Graceful and eye-catching personality who cherishes and nourishes friends. Very active social life. Musical or creative interests. Great money making opportunities as well as numerous love affairs are indicated. Career in the public eye is quite likely. Loves family but is often troubled other divided loyalties with friends.

Ruling Planet:Venus

Your Year No:5

Note:This forecast just fun and nothing more to take it seriously