Tuesday, December 30, 2014

It's Hard to Eat Right as an Engineer

These are my favorite info graphs, I'll be printing them off and hanging them on my fridge soon in hopes I'll eat more vegetables:

Things you should be looking to buy:


How to buy them fresh:



How you can enjoy them:



How long you can store the left overs/ingredients:


The best place to store them:



The best ways to preserve them:


Monday, July 14, 2014

NULL in T-SQL

Friday before I left I had the need to find all entries of configurations that we are using in one of our tables. I wanted to list all of them in nicely formatted SQL result so that I could later use that query to build a tool to make our configurations easier and faster to put together. I was joining two tables, one we'll call Cars, the other we'll call Attributes. Here's a sample query to clarify:

SELECT c.AttributeId, c.Name, a.[Description]
FROM Cars c 
JOIN Attributes a ON a.AttributeId = c.AttributeId
WHERE c.AttributeId IS NOT NULL 

The results looked something like this:

AttributeId   |  Name   | Description
-----------------------------
1             | Ford    | Cool Car
1             | Chevy   | Cool Car
2             | Honda   | Yellow Car
2             | Mazda   | Yellow Car

See how the id is repeated twice? This was ok because I knew we had more Attributes than Cars. The tool was intended to expose the attributes, the Cars were only there to clarify how the Attributes were being used. No word yet on how I'll display it in the UI.

I knew that my Attributes had 36 results, but when I joined them with the cars, I counted 12. This means we had a lot of orphaned Attributes. Interestingly, I had a hard time finding all of the attributes that weren't being used. I thought I could simply do this:

SELECT *
FROM Attributes 
WHERE AttributeId NOT IN (
 SELECT AttributeId
 FROM Cars
)

The problem with this approach was that some of the Cars have NO Attributes. Meaning they have NULL entries. When you try to use NULL's in conjunction with the IN operator in T-SQL, it's roughly equivalent to doing this:

SELECT 'Not being used.'
FROM 1 (NotEqual) 2 AND
     1 (NotEqual) NULL

What I found is that when you're working with NULL's in SQL you have to be very careful of three value logic. NULL's don't have a value so they don't evaluate to anything. When this happens SQL will just omit the results that don't equal either true or false. Since an IN operator is roughly equivalent to a AND operator, this will evaluate to unknown and won't be included in the results. See this awesome table to make a little more sense out of this, the portion is green is our specific scenario:

p q p OR q p AND q p = q
true true true true true
true false true false false
true unknown true unknown unknown
false true true false false
false false false false true
false unknown unknown false unknown
unknown true true unknown unknown
unknown false unknown false unknown
known unknown unknown unknown unknown

Thursday, June 20, 2013

Nullabe Guid?

I saw this today:
    if (myObject.ResourceValue != null)
    {
        otherData.Value = myObject.ResourceValue.ToString();
    }

and wondered if it is possible to get to this situation. So I tried it out myself and found that you will never have a null, non-nullable guid. See below:
namespace ScratchConsole
{
    public class Haha
    {
        private Guid _value;

        public Guid Null { get { return _value; } }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            Guid? test = null;
            //Guid data = test.Value; // throws an exception.
            //Guid data2 = null; // won't compile
            Guid data3;
            //Console.WriteLine(data3.ToString()); // won't compile, unassigned variable.

            Haha ha = new Haha();

            Console.WriteLine(ha.Null.ToString()); // outputs "00000000-0000-0000-0000-000000000000"
        }
    }
}

It seems that instead you should always check for an empty guid. Like so:
    if (myObject.ResourceValue != Guid.Empty)
    {
        otherData.Value = myObject.ResourceValue.ToString();
    }

Sunday, April 28, 2013

Generating TinyUrl Like Id's

I was looking into generating id's for a personal site that I'm doing for fun. The first thing I did was Google around a bit to see what other people are doing. There were some pretty good ideas out there, most of them taking a url and hashing it to a Base64 representation.

That was fine and dandy, but the methods they were using were long and hideous. I'm a huge fan of short and simple approaches because odds are, it's already been done by Microsoft. Since everyone was talking about hashing I figured I would see what this was about in my search result. How to Hash Passswords

It was still a little too complicated. I knew there had to be something simpler. Then I realized that on the Path object you can generate a temporary file name. It's pretty short. I tried it out and it was exactly what I was looking for! I just had to chop off the portion I wanted, since I wanted to restrict it to 7-8 characters.


Friday, April 19, 2013

Small Code

Here's a snippet from a post I took offline.

Small Code
"Functions should do one thing. They should do it well. They should do it only."

I feel like this is an overused term. It doesn't help that I also feel cursed by what my professor has taught me, "Try to keep your methods down to three to five lines." No matter how many times a fellow developer will compliment how nice my code is, they will argue to the death that you can't possibly have those kind of restrictions.

Sunday, October 21, 2012

Fresh Ideas

At first I was really pissed off, but now I'm finding it amusing. It kind of makes me feel like the world is sane and I'm the crazy one. So now I cackle in hysteria! Not really but you get the point.

What I would like to talk about is what happens when people see an innovative idea. Annoyingly, no matter how good of an idea it is, they can't seem to handle it. So their first instinct is to say, "it's JUST xyz." Let me tell you, I hate that phrase with fiery passion.

Thursday, August 23, 2012

Dictionaries and Hashtables

I see Hashtable being used everywhere it seems. Hashtable is a early data structure in c#, this was pre-.net 2.0.

Ideally we should avoid using Hashtable where possible because thanks to generics, Dictionary, is more efficient. This is because Dictionary does not have to box and unbox the values. If you're not familiar with this you can reference this article. http://msdn.microsoft.com/en-us/libr...=vs.80%29.aspx Dictionary is also a type safe way of storing and retrieving data and therefore should be preferred so as to avoid experiencing run time errors.

There are actually multiple types of dictionaries available:
  1. ConcurrentDictionary - thread safe (can be safely accessed from several threads concurrently)
  2. HybridDictionary - optimized performance (for few items and also for many items)
  3. OrderedDictionary - values can be accessed via int index (by order in which items were added)
  4. SortedDictionary - items automatically sorted by key
  5. StringDictionary - strongly typed and optimized for strings

There are other data structures out there in c# that can be really effective. I highly recommend you read this article multiple times when you get the chance. It's a little dated (.Net 2.0) http://msdn.microsoft.com/en-us/libr...1%28v=vs.80%29 But it's really good and dives deep into how each of the core data structures work.

One of the engineers I work with pointed out something else that's pretty awesome. KeyedCollection, here's what he had to say:

The KeyedCollection uses a Dictionary internally. It is another nice way of managing keyed data.

http://msdn.microsoft.com/en-us/library/ms132438.aspx

http://stackoverflow.com/questions/7...eyedcollection

Monday, June 4, 2012

Meta-Syntax

Over the few years that I've been learning to write software, I find myself often struggling to think in terms of metadata. More accurately, meta-metadata. So it's no surprise that I have found myself struggling to understand Backus-Narf Form (BNF) syntax. I finally decided to sit down and take a closer look at it and I found it surprisingly easier to understand than I initially thought. Read on to see my findings.

Sunday, April 29, 2012

Padding Wrong for Ordered Lists

As I'm making some modifications to my blog, I couldn't help but noticed that ordered lists.
  1. example
  2. example
  3. example
Are messed up with most templates I picked. So I wrote some simple css to fix that issue, under the advanced section of the template manager. I put this in the "Add CSS" text box.

ol {
    padding-left: 40px;
    padding-top: 10px;
}

Just throwing this out there in case someone else was just as confused as me.

Wednesday, April 25, 2012

Serialization Helper Methods

I keep forgetting the classes/methods I need to Serialize/Deserialize objects to and from XML. So I decided to make a couple of helper methods.


/// <summary>
/// Writes the serialized form of the object, in xml format, to the file
/// location specified.
/// </summary>
/// <typeparam name="T">type to serialize from</typeparam>
/// <param name="toSerialize">data to serialize</param>
/// <param name="fileLocation">to serialize the data too</param>
public static void Serialize<T>(T toSerialize, string fileLocation)
{
    if (toSerialize == null)
        throw new ArgumentException("The data to serialize cannot be null.");

    if (string.IsNullOrEmpty(fileLocation))
        throw new ArgumentException("You must provide a file location to output the data to.");

    using (var textWriter = new StreamWriter(fileLocation))
    {
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
        ns.Add("", ""); //turn off namespaces
        serializer.Serialize(textWriter, toSerialize, ns);
    }
}

/// <summary>
/// Reads the data from the file location specified and creates an instance
/// of the object type. The object must be serializable.
/// </summary>
/// <typeparam name="T">type to deserialize the data too</typeparam>
/// <param name="fileLocation">data to deserialize from</param>
/// <returns>new object of type T with properties filled out</returns>
public static T Deserialize<T>(string fileLocation)
{
    if (string.IsNullOrEmpty(fileLocation))
        throw new ArgumentException("You must provide a file location to read the data from.");

    using (var reader = XmlReader.Create(fileLocation))
    {
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        return (T)serializer.Deserialize(reader);
    }
}

They're pretty straight forward to use, but just for clarification.


public static void Main(string[] args)
{
    MyObject obj = Program.Deserialize<MyObject>(@"Files\SerializedData.xml");
    obj.AdjustValues();
    Console.WriteLine("Done!!!: {0} test: {1}", obj.Property1, obj.Property2);
    obj.AuditDirectoryName = "Test";
    Program.Serialize(obj, @"Files\SerializedData.xml");
    Console.ReadLine();
}

Short and Sweet

So today at work I had to come up with a method that would give me a listing of something from a collection. If the listing didn't exist, I wanted the listing to be initialized and automatically added to the list.

Let's look at my pathetic first attempt.


private Listing GetListing(List<Listing> cars, string name)
{
    Listing listing = null;
    IEnumerable<Listing> results = cars.Where(i => i.Name == name);

    //if map doesn't exist create it
    if (results.Count() == 0)
    {
        listing = new Listing()
        {
            Name = name,
            AdditionalData = new List<Data>()
        };

        cars.Add(listing);
     }
     else
     {
         //If we originally did this, it would throw an 
         //exception when there are no matches found. 
         //That's why this part is in the else block.
         listing = results.First();
     }

     return listing;
}

As you can see, I tried to get fancy and use Linq. I found, through testing, that the method .First() would throw an exception if there were no results. There were other methods, but for some reason I just couldn't think of the right method.

So then I threw my hands in the air and figured it'd be shorter to just write a method without Linq and that I was just over complicating it.

Thursday, September 23, 2010

Input

Here is a helper class that I created for getting input from the console in java. Created a java class named InputHelper and paste the content below and press ctrl+shift+f to format it.

Friday, August 13, 2010

Creating and Generating Java Doc

To generate java docs in code simply type "/**" and press enter. The first sentence you write is the summary and the rest in put in the details section.
Here is an example: (Unfortunately I couldn't format the code on here, sorry)
/**
* Get's the input from the user as a short. The input must be between the lower and
* upper bounds specified inclusive. If not between the values the user will be prompted
* with the error "Please input a number between (lower) and (upper) inclusive." The user
* will continue to be prompted with the message to display until valid input is given.
*
* @param lower bound
* @param upper bound
* @param display what to prompt the user before accepting input
* @return input from the user as a short
*/
public static short getShort(short lower, short upper, String display){
boolean valid = false; short result = 0;

while(!valid){ System.out.print(display);
String input = getString();
if(isWholeNumber(input)){
result = Short.parseShort(input);
valid = withinBounds(lower, upper, result);
}
}

return result;
}
To generate the html for the javadoc, right click on the project and select export. Type javadoc in the window as shown below and select javadoc.

Once your done specify the location of the javadoc tool. For me the path is "C:/Program Files/Java/jdk1.6.0_20/bin/javadoc.exe " As shown below.


Press finish and voila, your done generating javadocs.