Thursday, February 26, 2015

Blast from the past: C++ revisited

Ok, I'll admit that C++ doesn't appear to be as popular as some other current languages and may not draw the interest of many new developers but it was one of the first handful of languages I learned - right after CoCo Basic, 6809E assembler, Microsoft QuickC 1.0 and then Turbo C++.  I used C/C++ extensively throughout college and C++ was the primary language I used for roughly half of my career.  I have a number of fond memories from those times - fortunately the memories of corrupted memory and segfaults faded.

Anyways, I decided to check and see what has changed over the last 10 years or so.  I figured that there likely have been a number of improvements and I am pleasantly surprised.  I picked up a copy of "Effective Modern C++ by Scott Meyers; published by O'Reilly" and working my way through it. This book covers newer stuff from the C++11 and C++14 standards.  In the process, I am trying out Eclipse (initially setup for Java EE and Reports developers) with CDT installed. I had Cygwin installed already with many of the GNU tools installed (including G++ 4.8.2).

The CDK tooling doesn't seem quite as refined as the Turbo C++ or old Visual Studio tools I used years ago but it is workable.  I may just need time to adapt a bit to something new.

A quick note on accessing the most current C++ features in Eclipse; you should set the language standard to C++1y which appears to map to C++14.  If you are just working from a command line and make files; pass '-std=c++1y' on the g++ command line. 



 Here is a short example using 'auto' and 'lambda' functionality.



The output from the above is:
My Name is scott
4 + 1 =5
lambda call result:120
'auto' lambda called; result=720


Here is an extended example passing lambda defined functions to a function.



Output:
This examples produces 12.28

I do want to note that the CDK tooling indicates a problem/confusion with the return type of function "fn" in this case but the g++ compiler produces a working executable. If you simply declare the return type of "fn" as double instead of auto the error indication goes away.  Hard to say what should happen here without digging into the standards doc I am thinking.

Overall, I'm happy to see the changes made to the language so far.  Other interesting changes appear to include threading/concurrency support and "move/perfect forwarding".  I'll have to work on some examples at some point.  I have always enjoyed C++ templates and want to revisit those when time permits.



Sunday, February 22, 2015

The funny things children do - our daughter

Ok, so you find a piece of paper sitting in the kitchen which looks like it was supposed to be the start of a "to get" list.  You take a quick look and laugh because it says "Gerbowl wiper" and we just naturally expected that she was being funny and was reminding us to get both a real bowl for the gerbils that they could use for a sand bath and something it clean it out with. 

What we didn't realize until a wee bit later is that the note was sitting on a kitchen washcloth and she was saying that she had used it to clean up a makeshift sand bath container we had been using. 

We now question the meaning of any notes and don't grab washcloths which are laying around..

The little things we can tease the kids with later in life are quite funny.. Hope to never forget any of these little things.

Enjoy and God bless!
Scott


Tuesday, February 17, 2015

Java 8 lambda Example 2

Here is a slightly more interesting Java 8 example.  The larger problem being solved involves several smaller needs.
  1. Finding a users active directory group memberships that match an application specific pattern
  2. Extracting an organizational "short name" from the group definitions
  3. Returning a list of official organizational ID's associated with the short names. 
Described in a little more detail; if you had a user that belonged to the AD groups like:
    CN=HapBu-WidgetMaint-App-Employee-Role,OU=Security,OU=Groups.DC=TESTORG,DC=ORG
    CN=ChkSk-WidgetMgr-App-Employee-Role,OU=Security,OU=Groups.DC=TESTORG,DC=ORG

    CN=Other-App-Role,OU=Security,OU=Groups.DC=TESTORG,DC=ORG
You want to select the first 2 roles because they contain: 
     App-Employee-Role,OU=Security,OU=Groups
which would be the first 2 items.  From those, you want to take the "friendly org name" which would be the values "HapBu" and "ChkSk" and map those to an organization # by using an enum of valid organizations which maintains the mapping.
In the past this would probably require some fairly specific dedicated classes/methods.  I found that I am able to do this in a simpl fashion in Java 8.  I won't say that it was especially fast for me to develop this but I think over time it will become easier and more natural.

This enumeration, OrganizationInfo, is simply showing the use of a lambda if defining an a method which uses alternative key type info to search/select an enum value.
 package test2;  
 import java.util.Arrays;  
 import java.util.function.Predicate;  
 public     enum OrganizationInfo  
 {  
      HAPPYBURGER("O123", "HapBu"),  
      TONYTORTILLA("O543", "TonTo"),  
      CHICKENSHACK("O443", "ChkSk");  
      OrganizationInfo(final String orgCode,  
                final String displayableName)  
      {  
           this.orgCode = orgCode;  
           this.displayableName = displayableName;  
      }  
      String getOrgCode()  
      {  
           return orgCode;  
      }  
      /* This is a pretty generic method to select an enum  
       * value based on some attribute. For this example,  
       * it is a bit overkill but in a more realistic context this  
       * allows a good amount of code reuse.  
      */  
      private static OrganizationInfo search(  
                final Predicate<OrganizationInfo> predicate)  
      {  
           // This filters the enum list by the provided predicate and  
           // returns the first match.  
           return Arrays.asList(  
                     OrganizationInfo.values()).  
                     stream().  
                     filter(predicate).  
                     findFirst().  
                     get();  
      }  
      public static OrganizationInfo displayableNameToEnum(  
                final String displayableName)  
      {  
           // This is example client code to the previous private method and  
           // demonstrates using a lambda to specify the filter predicate  
           return search(p -> p.displayableName.equals(displayableName));  
      }  
      private String orgCode;  
      private String displayableName;  
 }  

The getMultValAttrib method is a good example of what code looks like which receives the lambda.
 package test2;  
 import java.util.Arrays;  
 import java.util.Collections;  
 import java.util.List;  
 import java.util.function.Function;  
 import java.util.function.Predicate;  
 import java.util.stream.Collectors;  
 public class User  
 {  
      /**  
           Responsible for querying multi-valued attribute data from  
           Active Directory for attribute "attribName", only process  
           items matching the predicate and then return values  
           as processed by the provided mapper function.  
      */  
      public List<String> getMultValAttrib(final String attribName,  
        final Predicate<String> predicate,  
           final Function<String, String> mapper)  
      {  
        List<String> data = Collections.emptyList();  
        // Get the data from active directory; skipping  
        // the real details here. Using some dummy data.  
        final String [] attributeData =  
             {  
                  "CN=HapBu-WidgetMaint-App-Employee-Role,OU=Security,OU=Groups.DC=TESTORG,DC=ORG",  
                  "CN=ChkSk-WidgetMgr-App-Employee-Role,OU=Security,OU=Groups.DC=TESTORG,DC=ORG"  
             };  
                  //adctx.getStringAttributes(attribName);  
        if (attributeData != null)  
        {  
                // This is where all the processing is actually done but  
                // note that the processing functions are passed in so this  
                // method is pretty generic.  
          data = Arrays.asList(attributeData). // stream uses a list  
            stream().  
            filter(predicate).  // Filter out only what we want to keep  
            map(mapper). // Perform some caller specific mapping  
            collect(Collectors.toList()); // Produce a list of results  
        }  
        return data;  
      }  
 }  


Below is an example of the above in use.
 package test2;  
 import java.util.List;  
 public class Test2  
 {  
      public static void main(String args[])  
      {  
           User aUser = new User();  
           //....  
           //...  
           List<String> orgCodes =  
                aUser.getMultValAttrib(  
                     "memberOf",  
                     p -> p.matches("(.*App-Employee-Role,OU=Security,OU=Groups.*)"),  
                     g -> OrganizationInfo.displayableNameToEnum(  
                               g.substring(3, g.indexOf('-'))).  
                               getOrgCode());  
           for(String org: orgCodes)  
           {  
                System.out.println(org);  
           }  
      }  
 }  


The above code produces the following output:
O123
O443

Wednesday, February 11, 2015

Java 8 lambda example 1

I started some new development work today and decided it is time to start moving to JDK 8.  Looks like existing code compiled as JDK 7 source tends to run ok under JDK 8 already. With some of the new functionality I needed though, it seemed reasonable to start working with actual JDK 8 specifics though.

This is a sample demonstrating some JDK 8 features I am using.


Here is the test class demonstrating some JDK 8 functionality.  

and here is the resulting output:
The regular expression from SampleEnum.flatList() is: (Item1|Item2|Item3|Item4).*
[Item1] matches
[Item3] matches
[Item4 with extra] matches

I am far from an expert on functional programming but I do like to dabble in them.  I do think there are times where the new JDK 8 functionality will promote smaller (and hopefully more maintainable) code.  A famous quote seems appropriate here - "With great power comes great responsibility".  I also foresee some real ugly code being spawned into existence.  I will try to take the good with the bad and try to use the tools at hand to make things better rather than worse. 

Monday, February 9, 2015

Amazing attitudes

I really need to learn from moments like this.  I find I need reminders every so often on how God wants us to respond to adversity. 

In this case, a coworker of mine has been going through cancer issues.  She had to endure surgery and various other unpleasant treatments.  During this process, she has always exhibited a wonderful attitude - smiling and more worried about others than herself.  This was even true after encountering several other very uncomfortable issues around Christmas. 

The topper to this though is her telling me about an encounter a family member (I think?) had.  They had been doing some banking and just loved the attitude of the women they were working with.  They mentioned to the women that they planned to ask only for her for the next 10 years but the women indicated that that would not  be possible.  When asked why, she let them know that her doctor estimated she only had 3 months to live.  She told them she wanted to make the most of the time she had left and didn't want to just sit at home and wait.

These types of encounters remind me that I should think harder about my responses to adversity.  I only wish I didn't need regular reminders.  I am very thankful for the folks that leave a positive mark on my life and I hope I do the same for others.

Thanks for reading and God bless!
Scott

Sunday, February 8, 2015

Son and cotiliion

Phew.  My sons last cotillion was last night and we survived.  He was never very thrilled about it from the beginning but since he didn't find an agreeable activity providing either exercise or social value we found one for him.  We called it an "Opportunity".  As much as he dislikes it, he was still pretty good at picking up the dances.  We did not know about about the cotillion until last year so he was only able to go for final year offered.  I know that starting on the last year didn't help things - knowing almost no one and doing activities you don't really like.  I still think it was worthwhile and hope that someday we will find that it made a positive change in him.  I am proud of him for putting some effort into it even if it wasn't always with a happy heart.

We did get one funny bit of his dry humor out of it.  I had looked over the railing at the the start of their intermission and yelled down "Smiling is contagious" which is one of the statements from the folks that run the cotillion.  My sons response was "Glad I was vaccinated"!  I sighed a bit but had to laugh a while too.



Friday, February 6, 2015

Thumper - The jumping gerbil

Ok, we are still working out how to keep the gerbils in a safe contained area while letting them roam a bit.  One of our gerbils, Thumper, just has the need to roam outside of any "contained area".  He is pretty smart to start with and is getting better at escaping contained areas and now has found that he can jump pretty high.  I think we will have to work on a way to contain him in our hallway by blocking off a few doors and such with towels - that will give some room to roam but prevent the need to empty out the "treasure" that my daughter tends to collect under her bed while trying to convince Thumper to come out.  Actually Thumper does tend to come out and I think he may actually like being chased a little - it is quite funny to see how easily he evades us. 

Here is a quick video showing how high he can jump.  I do fear that he will hurt himself if he keeps this up though.


Thursday, February 5, 2015

The family addition - pets

So our kids have been wanting a pet for some time.  Our son would like a cat and our daughter wants a horse but would "make do" with a dog.  yeah, right..

I'm not a cat person.  My wife has never really had indoor pets.  I had dogs as a kid and really enjoy them but for a couple of reasons they just are not a good fit for our family (right now).  Part of me would really like a dog but I just can't justify it.  I even researched them and picked out around 4 breeds which I really like that would make nice pets for us.

Eventually, I came back to reality and started looking into other possible pets.  No cats. Can't be big.  No fish or birds.  No lizards, snakes or similar.  Kids don't want a goat (ok, too big too for indoors).  Finally looked at rodents of various sorts.  I didn't want something that was mainly up during the night.  Prefer something that is pretty easy to care for.  Something that doesn't tend to smell too bad.  Something that can be held/handled/played with to a decent extent.

After some research and a good number of youtube videos it was pretty clear that gerbils would fit the requirements pretty well.  They do chew *a lot* and it sounded like it would be best to get a pair of them (same sex though).  I didn't really want multiple critters but because they otherwise sounded like a good idea I decided to pursue this further.

I decided to test the waters with the kids though but in a non-obvious fashion to gauge whether they would be interested.  Ok, more like whether my daughter was interested - I know my son would enjoy watching them but would never want to take care of them.  Anyway, one Saturday morning I took us all over to a nearby pet store to just "look around".  I don't think I thought this through well enough first.  Anyways, we get there and they have a number of dogs there needing adoption.  My daughter makes a bee line for them and decides that "cupcake" is what we need.  I very briefly got the kids down the rodent section but they had no interest.  I thought the whole pet idea was done at that point.

A week or 2 later, we were having dinner and pets came up again and I told them I had considered letting them have gerbils.  At that point my daughter finally expressed some excitement and interest.

So the pet idea was back on track now.  Previous stops at the pet store didn't leave me very optimistic because they only ever had one lonely gerbil.  I made another quick stop one night to the pet store and they had 3 young male gerbils that had just come in.  They were still in their quarantine waiting period but they were there!  A couple more trips to the pet store and the kids in tow - they still seemed interested so we loaded our arms up with all the necessities and head home with 2 new family members.

As an aside, my wonderful wife that is pet tolerant but not excited about pets generally looked at me at one point as we were heading to get the little guys and says "they have 3 of them.  hm.".  Anyways, we started laughing and commenting on feeling bad about leaving one behind.  In the end, we had to get only 2 of the 3 but it was close.

We didn't initially have the full size tank/setup we were working on so it would have been really cramped.  I have a larger tank on order but it has yet to be delivered after 2 weeks - supposed to be here tomorrow but we'll see.  The 2 story tank topper arrived pretty quick and even though it wasn't optimum, we are able to put it on top of the smaller tank we have.  The little guys do seem much happier with the extra space of the topper.

It took us a day or so to commit to names for the gerbils.  One is a honey/white mix (Thumper) and the other is black with white around the front ankles (Shadow).  We did have to laugh at a few earlier name ideas which were girl names.  I know the gerbils don't care but hey, it just seemed too wrong :)

It has been a couple weeks now and the little guys have grown a lot.  We have learned a lot as well.  They are now pretty tame; they are ok being held but are so active that it doesn't last too long.  They both have very distinct personalities.  Thumper is a full throttle adventurer/explorer and a bit of an escape artist.  He now scales the outside of the topper and has learned that he can jump pretty high which he uses to get loose for quick explorations of his surroundings while we try to "convince" him to go back to the "safe area".  He is a bit larger than Shadow and that may be because he really likes to eat and seems to try and steal his brothers food at times.  Thumper isn't really scared most of the time.  Shadow on the other hand is smaller and a little shy and skittish.  He is not quite as wild overall but is an impressive sprinter if startled. Shadow is much easier to just let wander on our folded arms and chest.

We are still sorting out their environment.  I need a nice bowl for their dust bath instead of a plastic ice cream bucket.  They are supervised with it but they still try to give it a quick nibble here and there which I know isn't good.  We are still working out food/treats a bit.  We are using plain dry gerbil food as the primary food but am trying to use a seed/nut food as the source for "treats".  I have some hay which they seem to both nibble and use in the normal bedding.  For bedding, I am using aspen shavings and white Carefresh which they seem to like.  It does support some tunneling.  For the aspen shavings, it can be somewhat expensive at the pet store but I did get our next batch from Tractor Supply - much larger quantity and very good price.  Not ready to use it yet but am prepared.  Only downside seems to be the larger storage requirement.  They really enjoy chewing up toilet paper rolls, paper towel rolls, toilet paper and store-bought willow sticks.

Here are a couple quick videos of our furry friends.





Our entire family is enjoying the gerbils.  My daughter is learning how to be responsible and take care of them.  Her and I really enjoy playing with them.  My wife and son enjoy watching them and watching me and the daughter play with them.  I think we get laughed at quite a bit but we love every minute of it.