Friday, March 8, 2013

Recursive Yield Return

Was writing a recursive routine the other day and wondering what an implementation of this would look like should I convert it to use yield return.

Much to my consternation this was not as easy as I thought it would be.  It took me almost a week to get it working.  Not of constant time, of course, but elapsed time.  In my initial implementation I could not get my head wrapped around whether each yield return was going to bypass all the calls on the stack and return a result to the caller OR whether it was going to just pop one call context.  Turns out it is the latter, which greatly complicates the implementation.  Given that the implementation of this particular implementation was escaping me.

I was downstairs meditating last week, not thinking about anything in particular and it hit me.  Like a flash...I could see the implementation.  I ran upstairs and quickly wrote down the rough implementation.  I felt kind of like a musician when a riff for a song hits them in their sleep and they need to quickly write it down before they forget it.

I came back to the code after dinner and put the finishing touches on it.

The first method is the seed method implemented as an extension method on IEnumerable.  It in turn calls the the recursive method.

The implementation below is function that given a collection it will return you a collection of all the permutations (a collection of collections). 

For instance if you pass
[
    [ 1, 2, 3],
    [4, 5,  6],
    [7, 8,  9]
]

This routine will return you 3x3x3 (27) collections, each of which will contain 3 items.  Using the data above here are the first few collections returned...
[
   [1, 4, 7],
   [1, 4, 8],
   [1, 4, 9],
   [1, 5, 7],
...
]


  
public static IEnumerable> GetPerm(this IEnumerable> domain)
{
return GetPermRecur(domain);
}
public static IEnumerable> GetPermRecur(IEnumerable> domain)
{
var c = domain.Count();
var firstFromDomain = domain.First();
if (c == 1)
{
foreach (var item in firstFromDomain)
{
yield return new[] {item};
}
}
else
{
var domainWithoutFirst = domain.Skip(1);
var permSoFar = GetPermRecur(domainWithoutFirst);
foreach (var item in firstFromDomain)
{
foreach (var curCol in permSoFar)
{
var curPerm = new List() { item };
curPerm.AddRange(curCol);
yield return curPerm;
}
}
}
}

Code Formatter for Blogger

I bowed down at the alter of the all knowing oracle (aka search engine) and asked what I could use to format the code in my previous post.


The answer was this.



Copy the code into first text box.  Press a button.  Out comes the HTML.  Nice.



I turned off the last option (Alternate Background) to get ride of the alternating highlights.  Yuck.

Google Contacts Importer

Could not get a bunch of contacts to import into Google Contacts the way I wanted.  I had a CSV that I exported from Outlook but no matter what I did to the CSV header names, I did not get the phone numbers spiked out for the contact correctly.  Instead the phone numbers would all be put as text into the Notes of the contact.  Useless.


So I rolled up my sleeves and wrote the following code to import the CSV file.  I made some assumptions (because I could) about the order fields appear in the file and their format.  For instance, the name I have is in the "Last, First M." format; so the code breaks this up.  Also, all the phone numbers are formatted correctly so no fixing required.

Another assumption is that all the contacts are added to the same group (see the constant at the top) which does not have to be the same as the company name in the CSV file.  Probably could have cleaned this up a bit, but it worked for what I needed.  



Hope this helps someone...



CSV Format
 UserName,Company,Department,Cell Phone,Home Phone,Work Phone,Mobile Phone 2  
"Adams, Gomez",My Co,Accounting,,(212) 555-4805,(212) 555-6748,


C# Code

 using System;  
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Diagnostics;
using Google.Contacts;
using Google.GData.Contacts;
using Google.GData.Client;
using Google.GData.Extensions;
using LumenWorks.Framework.IO.Csv; // http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader
namespace UploadContacts
{
class MyContact
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Company{ get; set; }
public string Department{ get; set; }
public string CellPhone{ get; set; }
public string HomePhone{ get; set; }
public string WorkPhone{ get; set; }
public string CellPhone2{ get; set; }
}
internal static class Program
{
private const string CompanyNameForGroup = "My Co";
private const string AppName = "Test";
private const string Username = "Me";
private const string Password = "blah";
private static ContactsService _cs;
private static void Main()
{
var himcoGroupId = LookupGroup(CompanyNameForGroup).Id;
var data = ReadCsv();
foreach (var contact in data)
{
var newEntry = CopyData(contact, himcoGroupId);
AddContact(newEntry);
}
}
private static void AddContact(ContactEntry newEntry)
{
if (_cs == null)
{
_cs = new ContactsService(AppName);
_cs.setUserCredentials(Username, Password);
}
var displayName = string.Format("{0} {1}", newEntry.Name.GivenName, newEntry.Name.FamilyName);
var feedUri = new Uri(ContactsQuery.CreateContactsUri("default"));
try
{
_cs.Insert(feedUri, newEntry);
Console.WriteLine("Added {0}", displayName);
}
catch (Exception ex)
{
Console.WriteLine("Error {0} while adding {1}", ex.Message, displayName);
}
}
private static ContactEntry CopyData(MyContact contact, string himcoGroupId)
{
var fullName = string.Format("{0} {1}", contact.FirstName, contact.LastName);
var newEntry = new ContactEntry
{
Title = {Text = fullName},
Name = new Name {GivenName = contact.FirstName, FamilyName = contact.LastName}
};
newEntry.Categories.Add(new AtomCategory(CompanyName));
newEntry.Organizations.Add(new Organization
{
Department = contact.Department,
Name = contact.Company,
Primary = true,
Rel = ContactsRelationships.IsWork
});
if (!string.IsNullOrEmpty(contact.CellPhone))
newEntry.Phonenumbers.Add(new PhoneNumber(contact.CellPhone)
{
Primary = true,
Rel = ContactsRelationships.IsMobile
});
if (!string.IsNullOrEmpty(contact.CellPhone2))
newEntry.Phonenumbers.Add(new PhoneNumber(contact.CellPhone2)
{
Primary = false,
Rel = ContactsRelationships.IsOther
});
if (!string.IsNullOrEmpty(contact.HomePhone))
newEntry.Phonenumbers.Add(new PhoneNumber(contact.HomePhone)
{
Primary = false,
Rel = ContactsRelationships.IsHome
});
if (!string.IsNullOrEmpty(contact.WorkPhone))
newEntry.Phonenumbers.Add(new PhoneNumber(contact.WorkPhone)
{
Primary = false,
Rel = ContactsRelationships.IsWork
});
newEntry.GroupMembership.Add(new GroupMembership {HRef = himcoGroupId});
return newEntry;
}
public static Group LookupGroup(string name)
{
var rs = new RequestSettings(AppName, Username, Password);
var cr = new ContactsRequest(rs);
var feed = cr.GetGroups();
var retVal = feed.Entries.Where(i => i.Title == name);
return retVal.First();
}
public static IEnumerable ReadCsv()
{
var retList = new List();
using (var csv = new CsvReader(new StreamReader(@"C:\Users\Curtis1\Dropbox\Code\UploadContacts\UploadContacts\PhoneNumbers.csv"), true))
{
while (csv.ReadNextRecord())
{
string fname;
string lname;
var wholeName = csv[0];
var nameParts = wholeName.Split(new [] { ',' });
if (nameParts.Length >= 2)
{
fname = nameParts[1];
lname = nameParts[0];
}
else
{
nameParts = wholeName.Split(new [] {' '});
fname = nameParts[0];
lname = nameParts[1];
}
if (fname.Length == 0 || lname.Length == 0)
Debug.Assert(false);
var newContact = new MyContact
{
FirstName = fname,
LastName = lname,
Company = csv[1],
Department = csv[2],
CellPhone = csv[3],
HomePhone = csv[4],
WorkPhone = csv[5],
CellPhone2 = csv[6]
};
retList.Add(newContact);
}
}
return retList;
}
}
}

Tuesday, January 3, 2012

Social Media

Today I found myself pontificating on Facebook, Google+, LinkedIn, Twitter and other more real time social media sites.  I think they differ from blogging which can be more informational or narrative.  Not that I am against any of them and find uses (even if just pure entertainment) for each.  On occasion.  As a content creator though, I suck.  I know that I have lots of content, just that I also have two big restrictions.

  1. Time

  2. Firewall

When it comes to time I am not saying that I don't have enough; just that these things just don't rate high enough for me to spend time doing them.  When I have a few minutes or when something is sticking with me such that I know that writing about it will help me move forward - well then I make time.  But I am not in content creation business.  Nor does my business directly benefit from any of these.  Which brings me to the second restriction - the firewall.

The firewall is not the physical firewall here at work.  In fact I am currently at work and have 10 mins before my next meeting and decided to spend it quickly writing this post.  No the firewall is the policy that we have here at work to not write anything about work.  I understand the policy and certainly abide by it.   But it is restrictive. 

I wonder what a world without this restriction would be like?  Certainly those who believe in the virtues of social networking think that it would be better.  Me I am not so sure.  I see both sides.  I certainly see how me writing about the cool stuff we are doing would help the image of the company and possibly help attract talent.  On the other hand it does not take but one bad apple (or post) to be taken out of context and watch the fireworks.  Bad image.  Litigation.  All thing that I believe scare the company and cause it have a blackout policy.

Not to mention that I work for an investment firm and there is the whole insider trading kinds of issues.

Restrictions aside, time is really the bigger reason I don't do more.  Nuff said.  3 mins left before my meeting; think of the possibilities.

Thursday, December 29, 2011

Humility and Confidence

Humility and Confidence are two words that have been rolling around in my head lately. In this post I am going to let these two play out here and see what I end up with; I have no idea where this is going.

This was inspired by my closing comment in my previous post - that I still have so much to learn. This was not meant to be a statement of self judgment but one of humility; especially as it pertains to leadership. The day that I believe that this statement is less true is the day that my ego is in control and I will be a less effective leader. Not to be confused with confidence. Confidence is knowing that things are going to be OK. Unfortunately confidence is mistaken by many as something more than just know that things are going to work out and it is used to boost/elevate the Self.

Confidence is experiential - Humility is constant. Confidence that is not based on experience is not solid and will not be trusted. The people around you will know this and their tentativeness will be palpable; that is if you are paying attention. But someone in this state will not be paying close enough attention; rather this person will be expending a lot of energy trying to show or justify the position that they will miss signals. The way to combat this is by being honest with people when you are not confident. That is not to say that you freak out and run out the room screaming. But rather you turn to people and say something to the extent – “I have never encountered something like this before – what would you do?” In other words show some humility.

This is where it gets tricky. First off, being a good leader means that you are doing this quite a bit already. You should be allowing people to contribute by being part of the decision making process and then empowering them to act. Good leaders do not do everything themselves. Every time I get to this point in my thinking of remember one of the tenants from “What Got You Here…” – Don’t add too much value. Secondly, statements like this need to couched in some sort of decision making “process” (I am using the work process lightly). Be very clear in your own thinking that statements like this can lead to a sense of anarchy or distributed decision making; this is not about abdicating or stealing the decision making process. Someone still needs to own the decision or you can end up on an endless discussion or debate. Also you need be very clear when the decision has been made; believe it or not this can be hard. I can’t tell you how many times I have seen a decision made and people don’t realize it and bad things happen from there (maybe something to address a subsequent post).

So back to our my statement and the key aspect of it that shows humility is the prefix – that you are being humble by acknowledging you don’t “know” the answer. But you are not faking that you do. Take the same statement without the prefix – “What would you do?” Depending upon the person this statement can be taken a bunch of ways. Every day I deal with people in different states and to a “paranoid” lonely statement could mean something different than it does to someone who is “competitive”. I believe that peoples states mostly boil down to trust – trust in me and trust in themselves (how are they different ). When I exhibit humility it helps reinforce trust. Is there a guarantee? Nope. Some people have some core trust issues and this is a drop in the ocean to helping that. But hey, before there where oceans there had to be that first drop.

Humility goes so much further than what I have mentioned here. In fact I believe that humility instills confidence. Have you ever been around a humble person and felt a difference? Are you more relaxed? I believe so. I believe that I am more likely to value humility in a leader than just pure confidence. I have worked with some way smarter people over the years and nothing was more of a turnoff than confidence with no humility. When working with someone like this I did not feel that there was anything in it for me; they just “knew” what the right thing to do was and made the call. Often times they were right or close; but how invested was I in that decision? How likely would I be to work hard to see it through the challenges? How much did I learn from the experience?

See the difference?

Lastly, humility has another aspect worth mentioning. I find that there is another aspect of humility that characterizes good leaders – they give a lot of credit to those around them. They take (or assign) responsibility and ownership for the decision but give clear credit to those who contributed to the decision. This is easy to recognize and gets my attention very quickly; regardless of whether I am the person being acknowledged or now.

So how good am I at this? I can certainly do better. I know that

PS. I feel like there are aspects to these two words that I want to address in the future that I in some way touched on above; but will wait for a future post to explore.

  • Confidence is situational – Humility is not.

  • Confidence is shakable - Humility is solid.

  • Something about Humility being timeless.

  • Attributes of healthy confidence vs less healthy?

Tuesday, December 27, 2011

What a year!

Was just reviewing my last post (which began similarly) and it ended with reference to changes in leadership in my department. Those changes continued to snowball and culminated with me landing a new position on the leadership team. The last year has consisted of me figuring out what this new job is and how I can do it. I just finished my self appraisal so it can say that it has been a difficult year. The transition has not been easy for me or my extended team. We changed many things in the organization this year and it has had some significant impacts. Every day I get up and keep my eye on the big vision of what we are trying to do and figure out how to make course corrections to get us there. Unfortunately it feels like I am using a spoon to do it sometimes. Yes, I am the one picking up the spoon thinking it will help and realizing that it is just the wrong "tool". Rookie mistakes abound. Last week I was reading an article from the Harvard Biz Review called "Why Should Anyone Be Led By You?" and it was pretty intimidating. Geez, I have a lot to learn.

For what it's worth here are some new books "on the shelf"...
1. What Got You Here Won't Get You There
2. The Leadership Moment
3. Crucial Conversations
4. True North
5. The Zen of Listening
6. Nice Teams Finish Last
7. The World Is Flat

Monday, October 4, 2010

Dry Spell

I took a long break from blogging. Looking Back it has been 7 months! I felt like I was on a role at the beginning of the year. No resolution, just had the time to put down what I was thinking.

I also can't help but notice it has been raining here in New England off and on for over a week. I believe I heard some weather man announce that the drought is officially over. So what better reason to end my blogging drought. They lasted almost the same length of time.

Then everything changed. On the personal side I proposed to a great woman and her two girls. Blink - instant family. Trying to sell a house. Get someone off to college. Plan a wedding. Buy a house. Oh yeah, then the other half of my life changed - work.

At work I suddenly found myself taking on the roles of at least three people. I had my old responsibilities as the Lead Application Architect. Then suddenly I owned every server in the organization. More on that later. Lastly we let the person go who as going to build out our SharePoint environment and move the organization to better collaboration (whatever that means). Yes you guessed it...I inherited that as well. At least SharePoint is not a far cry from the application space. But I not only owned the implementation but also the infrastructure. I don't know if anyone has peeked under the covers at SharePoint 2007, but it's huge.

As near as I can tell this product is made up of at least 3 other products that were glued together to make a single product. Which means they loosely fit together; they are unified but not really. Wow, what a pain to keep this thing running. I am sure that part of the complexity of our configuration is that they guy who put it together knew SharePoint really well and I don't. So he build out something that will fully support the organization for many years and growth; but only if he was here to keep in running. This is not a job for someone who does this part time!

Today it was announced that the CTO/CIO of our organization "is leaving to pursue other interests". This always sounds to me like it was clear that he was not longer welcome at the party. Whatever the reason, it won't mean more blogging. Guess that means that the one or two of you that actually read this will have to continue to live with disappointment.

;-)

Can You Feel the Vibe?