tag:blogger.com,1999:blog-55683281460326646262024-03-05T20:49:22.095+02:00Programming for COWARDSCode, Design, Tests, Refactoring, Success, Failure, and all-things ProgrammingUnknownnoreply@blogger.comBlogger30125tag:blogger.com,1999:blog-5568328146032664626.post-49958431514740883232012-02-05T17:46:00.000+02:002012-02-05T17:46:29.737+02:00Converting String to Number in Javascript: A Gotcha<div dir="ltr" style="text-align: left;" trbidi="on">
If you are used to program in C, Java, or any similar language, you might get surprised by the way Javascript's <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt">parseInt </a>and <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseFloat">parseFloat </a>functions work. By their names, parseInt will convert a string into an integer, it does so by reading thorough the string and converts the characters to integer until it meets an invalid character, it then stops and returns the read characters (the valid part) as an integer, so <pre class="csharp" name="code">parseInt("123ax4");</pre> will return 123.<div>
This is a very different behavior than how Java, or C would work. So, if you see this dangerous, then there is a better way to do it. </div>
<div>
<br /></div>
<div>
<b>The Unary + Operator:</b></div>
<div>
Using the unary <a href="https://developer.mozilla.org/en/JavaScript/Reference/Operators/Arithmetic_Operators#.2B_(Unary_Plus)">+ </a>operator to convert strings to numbers guarantees you that either the entire string is a valid number, in such case the converted number value is returned as a result of the expression, or if there is any invalid number in the string, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/NaN">NaN </a>is returned. So the output of the statement <pre class="csharp" name="code">+ "123";</pre> results in the integer value 123. The output of the statement <pre class="csharp" name="code">+ "123a";</pre> is NaN.</div>
</div>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5568328146032664626.post-47503694442345464232010-07-12T21:55:00.000+03:002010-07-25T14:49:38.638+03:00You Can Actually Cast To Anonymous TypesJust a quick note, one can really cast to anonymous types! <br />
<br />
There's a very interesting quote in the C# specifications regarding anonymous types: <br />
<i><br />
"Within the same program, two anonymous object initializers that specify a sequence of properties of the same names and types in the same order will produce instances of the same anonymous type"<br />
</i><br />
<br />
This means this:<br />
<pre name="code" class="csharp">var x = new { Name = "Jon Doe", Position = "Manager" };
</pre><br />
and this: <br />
<pre name="code" class="csharp">var y = new { Name = "Chuck Norris", Position = "The One" };
</pre><br />
will produce instances of the same type, hence x.GetType() and y.GetType() will yield the same result. <br />
Now how to cast? For example, if you have a method like the following: <br />
<br />
<pre name="code" class="csharp">object Test() {
return new { Name = "XYZ", Position = "ABC" };
}
</pre><br />
One way to cast the return of this method is as follows: <br />
<pre name="code" class="csharp">var ret = Test();
var retCasted = Cast(ret, new { Name = "", Position=""});
Console.WriteLine("Name: {0} -- Position: {1}"retCasted.Name, retCasted.Id);
</pre><br />
Here's my Cast method: <br />
<pre name="code" class="csharp">T Cast<T>(object o, T type)
{
return (T)o;
}
</pre><br />
OK, just that quick tip!Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5568328146032664626.post-58298566479799987802010-07-06T12:26:00.000+03:002010-07-06T20:21:04.819+03:00List.Find(Predicate <T>) Considered HarmfulHold on, it's not goto! <br />
<br />
I dare to say that every program have ever written on this entire planet needed some sort of searh functionality, and if it didn't, it's probably because it's too lame and frickin' uslelss. <br />
<br />
Today I was working on a piece of code that part of it is concerned about finding items in a generic List<T>. The code I wrote was some like this: <br />
<br />
<pre name="code" class="csharp">var products = ProductsCollection.Find(p => p.Price > 500);
</pre><br />
Doesn't that look concise and elegant. For me it does, the problem is, however, this code is not <i><b>SAFE</b></i> (yeah, i was surprised too). <br />
<br />
When I run this code I got a <a href="http://msdn.microsoft.com/en-us/library/system.nullreferenceexception.aspx">System.NullReferenceException</a>. WTF is that? ProductsCollection is totally a valid reference, however, it was empty.<br />
<br />
OK, wait a second why should searching an empty list throw an exception? The expected result should be null or something but not an exception. After thinking about it a little, I thought, Oh, what if the list contains value types? In such case null is not a valid return type, so an exception makes sense to me now. <br />
<br />
Here I thought I really got it and understood that List.Find will throw a null reference exception if called on an empty list. I was totally wrong if you must know. The call would simply return default(T) which is null for reference types. The exception was actually thrown when I used the return of the find! <br />
<br />
Now I wondered "OK, now what if i'm searching a list that only contains value types and the item i'm searching for doesn't exist in that list? What would be the result in this case? Well, let's try it out":<br />
<br />
<pre name="code" class="csharp">List<int> evens = new List<int> { 0, 2, 4, 6, 8, 10};
var evenGreaterThan10 = evens.Find(e => e > 10);
Console.WriteLine(evenGreaterThan10);
</pre><br />
What the search returned in this case is the value 0, yes zero! because nothing in the list is greater than 10 so Find will just give you default(T). This can lead to some really nasty bugs. Don't curse, this is frickin' documented you lazy sloths.<br />
<i><br />
<b>Important Note:</b><br />
When searching a list containing value types, make sure the default value for the type does not satisfy the search predicate. Otherwise, there is no way to distinguish between a default value indicating that no match was found and a list element that happens to have the default value <br />
for the type. If the default value satisfies the search predicate, use the FindIndex method instead.<br />
</i><br />
<br />
Trying to be safe in this case you could simply check after finding to see if the returned value is what you actually asked for, something like that: <br />
<br />
<pre class="csharp" name="code">List<int> evens = new List<int> { 0, 2, 4, 6, 8, 10};
var evenGreaterThan10 = evens.Find(e => e > 10);
if(evenGreaterThan10 > 10)
{
// valid value
}
else
{
// none found
}
</pre><br />
I'm not sure how do you feel about that, but for me, I really hate it! So what I ended up doing is something similar to the well known TryParse style, I overloaded the Find method with an extension method that would allow the usage to be something like this:<br />
<br />
<pre class="csharp" name="code">List<int> evens = new List<int> { 0, 2, 4, 6, 8, 10};
int i;
if(evens.Find(e => e > 6, out i))
Console.WriteLine(i);
else
Console.WriteLine("None found");
</pre><br />
The extension method is as simple as: <br />
<br />
<pre class="csharp" name="code">public static bool Find<T>(this List<T> list, Predicate<T> predicate, out T output)
{
output = list.Find(predicate);
return predicate(output);
}
</pre><i><br />
<b>EDIT:</b><br />
As reported by Kevin Hall in the comment, this method has a serious bug. Consider the following code segment: <br />
<pre class="csharp" name="code">List<int> x = new List<int> { -10, -8, -6, -4 };
int myResult = -9999;
bool resultFound = x.Find(e => e > -3, out myResult);
</pre><br />
In this case result found would be true and myResult would be zero! A yet better way to do this is by making use of the FindIndex method like so: <br />
<br />
<pre class="csharp" name="code">public static bool Find<T>(this List<T> list, Predicate<T> predicate, out T output)
{
int index = list.FindIndex(predicate);
if (index != -1)
{
output = list[index];
return true;
}
output = default(T);
return false;
}
</pre><br />
Thanks Kevin for pointing that out.<br />
</i><br />
I'm much happier now, I can drop the suicide thought for a while! What do you think dear reader?Unknownnoreply@blogger.com13tag:blogger.com,1999:blog-5568328146032664626.post-67900090869684120792010-03-23T13:14:00.000+02:002010-06-02T12:13:03.229+03:00Usage Of The "is" Operator Should Be Handled With CareC# provides means to explicitly cast from a type to another type. If you want to cast from float to int you can use the (int) cast operator to acheive that. This operator simply says to the compiler, I know you don't like this, but, please let the runtime try to do the cast. This operation can either succed or result in an System.InvalidCastException to be thrown. <br />
<br />
In addition to this, you can overload the explicit cast operator in case you wanted the cast to happen by your own defined rules. Ok let's see an example of this. Suppose that we have two types, Human and Employee, and in our very unfair world, an Employee is not a Human! The layout of these two classes might look like this: <br />
<br />
<pre name="code" class="csharp">public class Human
{
public string Name { get; set; }
}
public class Employee
{
public string Name { get; set; }
public string Job { get; set; }
public override string ToString()
{
return string.Format("Employee: {0} is {1}", Name, Job);
}
}
</pre><br />
Now let's say that you want to support an explicit custome conversion from Humans to Employees -for a fictious rule, let's say that every human is unemployed employee. The human class after adding the conversion operator should look like this: <br />
<pre class="csharp" name="code">public class Human
{
public string Name { get; set; }
public static explicit operator Employee(Human h)
{
return new Employee()
{
Name = h.Name,
Job = "Happily Unemployeed"
};
}
}
</pre><br />
You can now try to cast your Humans to Employees, and see if the cast is really applying your rules, here's how I might attempt to cast one of humans to employee: <br />
<pre class="csharp" name="code">Human h = new Human {Name = "John"};
Employee s = (Employee) h;
Console.WriteLine(s);
</pre><br />
If you run this code you should see the output on the console screen saying: <br />
<br />
<i>Employee: John is Happily Unemployeed. </i><br />
<br />
Now let's see how this plays with the famous "is" operator. The is operator is binary operator with a return type of boolean. What it does, is that it checks to see if the left hand operand is actually of the same type of the right hand operand -By the same type here, I mean, the same as an instance of the same class, or an instance of a derived class, or an instance of a class the implements the right hand operand in case the right hand operand is an interface. <br />
<br />
Here's a simple example to see this operator in action: <br />
<br />
<pre class="csharp" name="code">bool shouldBeTrue = "Hello" is string; // true
bool shouldBeTrueToo = "Hello" is object; // true
bool shouldBeFalse = "Hello" is ICollection; // false
</pre><br />
Now, the interesting part: <br />
<pre class="csharp" name="code">bool shouldBeWhat = new Employee() is Human; // ?? guess guess
</pre><br />
Pause a minute and think of the above statement. What should the value of "shouldBeWhat" be? True of False? ... <br />
<br />
OK, the value of the boolean variable "shouldBeWhat" will actually be false. Yes, Employees are not Humans! Even though you have provided an explicit cast rule that , by the virtue of its existence, states that humans can be employees. "can be" doesn't equal to "is", does it? So, yeah the is operator doesn't take in account your explicit casting operators. So this is the first gottcha! <br />
<br />
The second point I wanna mention is that, the "is" operator works by actually performing a cast. Yes it casts and checks if the cast succedes it returns true otherwise, it returns false. A typical usage of the is operator is probably as follows: <br />
<br />
<pre class="csharp" name="code">if(h is Employee)
{
var x = ((Employee) s).Job;
}
</pre><br />
This should look familiar to you, a typical pattern when using the is operator is by checking first if a variable is of a given type, then if it is, cast it to that given type and use it. How many casts does the above code segment contain? 2 is the answer! Yes two, one is obvious in the statment <br />
<pre class="csharp" name="code">var x = ((Employee) s).Job;
</pre>and the other one is, yeah you guessed it, the cast performed by the is operator. This is not very ideal, as it simply, adds an overhead of a second cast which should is not necessary. So, what should you do to avoid that second cast?<br />
<br />
<b>Use "as" instead of "is"</b>:<br />
<br />
The "as" operator allows you to do safe casts and aslo avoid the probability of throwing any InvalidCastException, by assigning null to the variable if the cast failed. The following segment is semantically equivalent to the previous segment, but is considered faster and safer:<br />
<pre class="csharp" name="code">var x = h as Employee;
if(x != null)
string job = x.Job;
</pre><br />
The above segment is faster because it includes only one cast. <br />
<br />
Conclusion: <br />
There's not much to say here, just deal with the is operator carefully, and if possible avoid it and use the better alternative "as" operator.Unknownnoreply@blogger.com3tag:blogger.com,1999:blog-5568328146032664626.post-38612169878292685002010-03-14T14:42:00.000+02:002010-03-14T21:16:39.598+02:00New, But Not So Obvious, Features in .NET 4.0.NET 4.0 came out lately with a lot of new, cool, and somewhat game-changing features. These features include language features like the famous dynamic keyword in C# and this whole dynamic dispatching thing that made possible by the DLR (Dynamic Language Runtime).There are also some additions on the library level, the parallel extensions is an obvious example of that.<br />
<br />
In this post I will mention some of the new additions that are not so well propagated.<br />
<br />
<b>First The additions to the string class:</b><br />
The BCL guys are still working on the core. Apparently they are trying to lessen the number of extension methods that you need to write as a complement to some of the very core, and widely used in any application, classes -Pretty much everyone has a StringExtensions, and DateTimeExtensions dlls.<br />
<br />
<b>string.IsNullOrWhiteSpace()</b><br />
The old string.IsNullOrEmpty() was used to check if the string variable is null or if it's equal to the empty string ("", or string.empty)In many cases a string that contains only white spaces is considered to be an empty string. People used to do the following check over and over again:<br />
<pre name="code" class="csharp">if(string.IsNullOrEmpty(s) && s.Trim() != string.Empty)
{
// do my job;
}
</pre>Now string.IsNullOrWhiteSpace() is designed to save you that extra Trim call.<br />
<br />
<b>string.Join()</b><br />
Prior to .NET 4.0 string.Join was designed to accept two parameters a separator and an array of string, and it was expected to output one single string that contains the strings in the array separated by the separator. The problem with this is, if you have two separate strings and you want to join them together you would have to create an array and insert those two strings inside the array, then call string.Join passing in your separator of choice and the array. A call should look like this: <br />
<pre name="code" class="csharp">string first = "first";
string second = "second";
string[] sequence = { first, second };
string joined = string.Join(" - ", sequence);
</pre><br />
New overloads had been added to the string.Join method, one of them accepts a params of objects and it automatically calls ToString, so that you don't have to do that extra step of creating an array that holds your string values. Now the call to the method is simplified: <br />
<pre name="code" class="csharp">string joined = string.Join(" - ", first, second);
</pre><br />
<b>Modern collections support with string methods</b><br />
If you examine the old overloads of string methods that accept a collection, you shall find that the only collection these methods accept, is array. With .NET 4.0 things are different, now these methods support IList<T>, ICollection<T>, and IEnumerable<T> (yeah, I know, this should have been possible since .NET 2.0). With this support statments like this are possible:<br />
<pre name="code" class="csharp">string joined = string.Join(" - ", stringList.Where(s => s.Length > 3).Select(s=> s));
</pre><br />
<b>Second, Lazy<T><br />
</b><br />
Lazy Loading, is a technique that implies, creating and initializing expensive objects on demand. Most nowadays ORMs follow this technique when fetching data from the database. The Lazy<T> is a new type introduced in .NET 4.0 that enables you to lazily create your instances and validate whether an instance has been created or not without accidently creating it.For example if I have an object named ExpensiveObject like so: <br />
<br />
<pre class="csharp" name="code">class ExpensiveObject
{
public ExpensiveObject() { }
public ExpensiveObject(string connection)
{
Console.WriteLine("Constructing expensive object");
Connection = connection;
}
public string Connection { get; set; }
}
</pre>Here's how I would Lazily create an instance of this object:<br />
<pre class="csharp" name="code">Lazy<expensiveobject> a = new Lazy<expensiveobject>();
</pre><br />
To check if the object has been already created or not, you can use IsValueCreated boolean propery on the Lazy<T> object:<br />
<pre class="csharp" name="code">Console.WriteLine(a.IsValueCreated);
</pre>This should print false. If I tried to access the underlying expensive object (through the Value propery on Lazy<T>) and then check to see IsValueCreated, the result should be true: <br />
<pre class="csharp" name="code">string dummy = a.Value.Connection;
Console.WriteLine(a.IsValueCreated);
</pre><br />
This statement should print True on the console window. <br />
<br />
Note: In the above example we created an instance of ExpensiveObject using the default constructor. You can create it using a custom consructor by passing in a Func<expensiveobject> (i.e. any method that returns an expensive object)<br />
<pre class="csharp" name="code">Lazy<expensiveobject> custom = new Lazy<expensiveobject>(() => new ExpensiveObject("My Connection"));
</pre><br />
Hope this helps!Unknownnoreply@blogger.com3tag:blogger.com,1999:blog-5568328146032664626.post-13221703612686800122010-03-08T14:11:00.000+02:002010-03-10T16:55:13.557+02:00Programmers And The Value Of Hard FocusThere was a very <a href="http://www.reddit.com/r/programming/comments/b8qho/how_many_hours_of_pure_work_do_you_put_in_a_day/">interesting </a>discussion on <a href="http://reddit.com/">reddit </a>a few days ago. Some fresh programmer asked how many pure work hours do programmers work per day?<br />
<br />
<br />
By pure work he meant, the number of hours spent on (coding/designing/testing, etc.) a task that is probably assigned to him by one of his superiors. Other activities like personal researching, blogging, etc. are not counted.<br />
<br />
The question sound pretty interesting to me and the answers came much more interesting.<br />
<br />
Most of the answers implied that programmers put less that four hours of pure work per day. This is half the assumed time (8 hours for most companies).<br />
<div><br />
</div><div><div>So, why do programmers work less than most of other carriers' professionals? An immediate answer that might came to my mind "well, that's normal because they are sloths lazy." </div><div><br />
</div><div class="separator" style="clear: both; text-align: center;"><a href="http://www.supercoloring.com/wp-content/thumbnail/2009_04/lazy-programmer-coloring-page.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="304" src="http://www.supercoloring.com/wp-content/thumbnail/2009_04/lazy-programmer-coloring-page.jpg" width="320" /></a></div><div><br />
</div><div><b>False Assumption:</b></div><div> If I don't work HARD I will eventually fail to finish my work, and will certainly feel incompetent.</div><div><br />
</div><div><div><b>There's a lot to programming than HARD work:</b> </div><div>For me, it doesn't matter how many hours I work during the day. What matters most, however, is the number of tasks I manage to finish. This is ths only productivity metric to me, and it's not related to the number of working hours, it's related to the number of hours (or minutes) I managed to keep my focus hard. </div><div><br />
</div><div><div><b>The value of Hard Focus: </b></div><div>Haruki Murakami in his excellent memori (<a href="http://www.amazon.com/What-Talk-About-When-Running/dp/0307269191">What I Talk About When I Talk About Running</a>) noted: </div><div><i>If I’m asked what the next most important quality is for a novelist, that’s easy too: focus the ability to concentrate all your limited talents on whatever’s critical at the moment. Without that you can’t accomplish anything of value</i>.</div><div><br />
</div><div><div>The key is to concentrate all your mental abilities on one specific task and foreget about anything else as long as you're working on this one task. This is very important -actually a lot of programming techniques and tools are proven usefeul and highly adopted because it lets you forget about other details and foucs on your specific task.</div><div><br />
</div><div>Luckily enough, Marukami pointed that: "<b><i>Fortunately [sustaining focus for a long period of time] can be acquired and sharpened through training</i></b>."</div><div><br />
</div><div><div><b>Pomodoro</b>: </div><div>The <a href="http://www.pomodorotechnique.com/">pomodoro technique</a> is designed to address this very problem. It's mainly focused on helping you stay focused by working for shorter periods of time, named pomodoros, each is 25 minutes long and during each you're focused on only one task. And while working on this one task you are not allowed to think or worry about anything else. This really helps you cultivate all your energy on attacking one problem. </div><div><br />
</div></div></div></div></div><div><div><b>Conclusion: </b></div><div>The number of working hours is not that crucial in CS-related carriers or any other carrier that requires a non-trivial amout on creativity. What matters most is to keep your mind clear, break your problem into smaller problems, and focus on these smaller problems one at a time.</div><div><br />
</div><div>Now I see (and hopefully you dear reader) what every GTD book meant when they loudly screamed in readers' faces "<b>WORK SMART NOT HARD</b>"!</div><div><br />
</div><div>What do you think dear reader? </div></div></div>Unknownnoreply@blogger.com2tag:blogger.com,1999:blog-5568328146032664626.post-12388008866588458642010-03-02T13:44:00.000+02:002010-03-02T13:44:30.836+02:00Routing in ASP.NET 4.0 : A Sneak Peak<div class="separator" style="clear: both; text-align: center;"><a href="http://www.ciscorouting.com/routing_engine.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="217" src="http://www.ciscorouting.com/routing_engine.jpg" width="320" alt="Routing" /></a></div><br />
One of the cool features of ASP.NET MVC is the ability to provide clean, extension less, and SEO/user friendly urls. This is accomplished by using the new routing system in ASP.NET.<br />
<br />
Before ASP.NET 4.0, people used to get these clean urls using a technique called <a href="http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx">UrlRewriting or UrlRewiring.</a> The technique did get the job done, but unfortunately was somewhat complicated and involved the use of third party components.<br />
<br />
Now with ASP.NET 4.0, and with the addition of the new Routing System, we can get clean urls, like those we get with MVC, in Web Forms. <br />
<br />
To do this we need to first define our routes, seconde register them in the current RouteTable when the application starts.<br />
<br />
For example let's assume that we have a page that should display the details of a certain product given its Id.<br />
The url for this action should look something like "MySite.Com/Products/1". Routes have to be registered in your Application_Start in Global.asax. The code should look something like the following:<br />
<br />
<pre class="csharp" name="code">void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute(
"ProductDetails",
"Products/{id}",
"~/ProductDetails.aspx");
}
</pre><br />
I'm leveraging the new <a href="http://msdn.microsoft.com/en-us/library/system.web.routing.routecollection.mappageroute(VS.100).aspx">MapPageRoute</a> method on the <a href="http://msdn.microsoft.com/en-us/library/system.web.routing.routecollection.aspx">RouteCollection </a>class inside System.Web.Routing.<br />
The first argument of the method is the name of the route, in our case "ProductDetails".<br />
The second parameter is the Url pattern for this route which in this case is the string "Products" followed by<br />
the Id of the product.<br />
The {Id} parameter is the name of the actual parameter added to the RouteData collection. This parameter can then be accessed by the page RouteData property like so:<br />
<pre class="csharp" name="code">int id = Convert.ToInt32(RouteData.Values["Id"]);
</pre><br />
RouteData is a shortcut property of RequestContext.RouteData. The above statment is equivalent to this one:<br />
<pre class="csharp" name="code">int id = Convert.ToInt32(HttpContext.Current.Request.RequestContext.RouteData.Values["Id"]);
</pre><br />
<br />
Note:<br />
This is a very trivial example. The routing system is pretty powerfull. It can enable you to do a lot of neat stuff with it for example, you can generate urls out of the routing values, you can also add regular expression constraints on your route parameters to differentiate what route matches which request.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5568328146032664626.post-47919890534117805612010-02-03T19:39:00.000+02:002010-05-07T21:38:12.126+03:00Why this is not possible in C# Generics?<span class="Apple-style-span" style="border-collapse: collapse; font-family: Arial, 'Liberation Sans', 'DejaVu Sans', sans-serif; font-size: 14px; line-height: 18px;"></span><br />
<div style="background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-size: 14px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline;">A colleague pointed me to a strange case in C# (not so sure if this actually strange though).<br />
Suppose you have a class Employee. If you want to create a Generic List<> of type Employee, you can simply do:<br />
<pre class="csharp" name="code">List<Employee> x = new List<Employee>;
</pre>I understand that I need to pass the Employee type to the Generic list so that it knows the required type information about Employee and generates methods that return and accept parameters that are compatible with Employee. </div><div style="background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-size: 14px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline;"></div><div style="background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-size: 14px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline;">Now my question is, why isn't it possible to do the following?<br />
<pre class="csharp" name="code">Employee x = new Employee();
List<typeof(x)> list = new List<typeof(x)>();
</pre></div><div style="background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-size: 14px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline;">Shouldn't this suffice the information required for List<> to know, in order to create a list? In other words, the type of x which is the type of Employee is now passed as a generic type parameter to List<>, which (as I used to believe) is the same as passing list the type name (in this case Employee). </div><div style="background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-size: 14px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline;">I wondered so, I posted a <a href="http://stackoverflow.com/questions/2192876/why-this-is-not-possible-in-c-generics">question </a>on <a href="http://stackoverflow.com/">Stackoverflow</a>.</div><div style="background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-size: 14px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline;">If you're lazy enough to check the question, here's my selected answer, and boy it was submitted by Jon Skeet himself: </div><div style="background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-size: 14px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline;"><code style="background-attachment: initial; background-clip: initial; background-color: #eeeeee; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; font-family: Consolas, Monaco, 'Lucida Console', 'Liberation Mono', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Courier New'; font-size: 14px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 1px; padding-left: 5px; padding-right: 5px; padding-top: 1px; vertical-align: baseline;">typeof(x)</code> doesn't work in C# either to get the type of a variable - it returns a <code style="background-attachment: initial; background-clip: initial; background-color: #eeeeee; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; font-family: Consolas, Monaco, 'Lucida Console', 'Liberation Mono', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Courier New'; font-size: 14px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 1px; padding-left: 5px; padding-right: 5px; padding-top: 1px; vertical-align: baseline;">Type</code>reference for the <em style="background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; font-size: 14px; font-style: italic; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline;">type</em> name, e.g. <code style="background-attachment: initial; background-clip: initial; background-color: #eeeeee; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; font-family: Consolas, Monaco, 'Lucida Console', 'Liberation Mono', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Courier New'; font-size: 14px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 1px; padding-left: 5px; padding-right: 5px; padding-top: 1px; vertical-align: baseline;">typeof(string)</code> will return a reference to the <code style="background-attachment: initial; background-clip: initial; background-color: #eeeeee; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; font-family: Consolas, Monaco, 'Lucida Console', 'Liberation Mono', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Courier New'; font-size: 14px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 1px; padding-left: 5px; padding-right: 5px; padding-top: 1px; vertical-align: baseline;">Type</code> object associated with the <code style="background-attachment: initial; background-clip: initial; background-color: #eeeeee; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; font-family: Consolas, Monaco, 'Lucida Console', 'Liberation Mono', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Courier New'; font-size: 14px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 1px; padding-left: 5px; padding-right: 5px; padding-top: 1px; vertical-align: baseline;">System.String</code> type. That's equivalent to using <code style="background-attachment: initial; background-clip: initial; background-color: #eeeeee; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; font-family: Consolas, Monaco, 'Lucida Console', 'Liberation Mono', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Courier New'; font-size: 14px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 1px; padding-left: 5px; padding-right: 5px; padding-top: 1px; vertical-align: baseline;">String.class</code> in Java. (Note that again, that's applying <code style="background-attachment: initial; background-clip: initial; background-color: #eeeeee; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; font-family: Consolas, Monaco, 'Lucida Console', 'Liberation Mono', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Courier New'; font-size: 14px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 1px; padding-left: 5px; padding-right: 5px; padding-top: 1px; vertical-align: baseline;">.class</code> to a type name, <em style="background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; font-size: 14px; font-style: italic; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline;">not</em> a variable name.)</div><div style="background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-size: 14px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline;"></div><div style="background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-size: 14px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline;">Java generics don't support anything like your final statement either. If you believe they do, please give a sample :)</div><div style="background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-size: 14px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline;">What you <em style="background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; font-size: 14px; font-style: italic; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline;">can</em> do in C# is use type inference to do what you want:<br />
<pre class="csharp" name="code">public static List<T> CreateListForSampleType<T>(T sample)
{
return new List<T>();
}
...
Employee x = new Employee();
var list = CreateListForSampleType(x);
</pre></div><div style="background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-size: 14px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline;">Note that there's no reason why C# <em style="background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; font-size: 14px; font-style: italic; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline;">couldn't</em> be extended to allow something like<code style="background-attachment: initial; background-clip: initial; background-color: #eeeeee; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; font-family: Consolas, Monaco, 'Lucida Console', 'Liberation Mono', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Courier New'; font-size: 14px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 1px; padding-left: 5px; padding-right: 5px; padding-top: 1px; vertical-align: baseline;">typeof(variablename)</code> or <code style="background-attachment: initial; background-clip: initial; background-color: #eeeeee; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; font-family: Consolas, Monaco, 'Lucida Console', 'Liberation Mono', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Courier New'; font-size: 14px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 1px; padding-left: 5px; padding-right: 5px; padding-top: 1px; vertical-align: baseline;">List<typeof(variablename)></typeof(variablename)></code> - it's all compile-time type information, after all. However, I can't see that it would meet the team's requirements for usefulness... there are other far more useful features I'd like to see first :)</div><br />
<div style="background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial initial; background-repeat: initial initial; border-bottom-width: 0px; border-color: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; clear: both; font-size: 14px; margin-bottom: 1em; margin-left: 0px; margin-right: 0px; margin-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline;"><br />
</div>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5568328146032664626.post-77698929052233912172010-01-21T15:22:00.000+02:002010-02-01T13:09:00.084+02:00A Misleading Name of Computer Science Concept: Dynamic ProgrammingHave you heard of these words before?<br />
Probably yes!<br />
First let's make a clear (well, not so clear) difference, clearer. Dynamic Programming is not about Dynamic Typing. Dynamic typing is a property of a particular programming language. Languages like Lisp, Python, and Ruby are all dynamically typed languages. Unlike those, languages like C/C++, Java, and C# are statically typed language. The difference relies on whether the compiler checks certain things (types, overload resolution, etc.) before running the program or not.<br />
Dynamic Programming on the other hand is something very different. It's an ancient method for solving problems by basically dividing these problems into smaller, and easier to solve problems.<br />
<br />
It's mainly focused on addressing these two issues:<br />
<br />
<ol><li>Overlapping subproblems </li>
<li>Optimal Substructures</li>
</ol><div>I think the best way to explain these two fuzzy concepts is by using examples. To start let's see an example of using a famous dynamic programming technique called Memorization. Assume that we need to implement a function that calculates a <a href="http://en.wikipedia.org/wiki/Fibonacci_number">Fibonacci </a>sequence. I know this is easy, but let's look at this first implementation:</div><pre class="csharp" name="code">static int FibClassic(int n, ref int numberOfStepsTaken)
{
numberOfStepsTaken += 1;
if (n <= 1)
return 1;
Console.WriteLine("FibClassic called with: {0}", n);
return FibClassic(n - 1, ref numberOfStepsTaken) + FibClassic(n - 2, ref numberOfStepsTaken);
}
</pre>Note: on the above code I used two counter variables to count the number of times the method executed. I also printed the input on which the method is called every time, just to give you a hint of how dividing a problem can cause the same subproblem to be computed more than once --Subproblem Overlapping, remember! Now let's run the code given the number 6 as input and see what happens: <br />
<pre class="csharp" name="code">int z = 0;
int x = FibClassic(6, ref z);
Console.WriteLine("{0}: {1}", x, z);</pre><div class="separator" style="clear: both; text-align: center;"><br />
</div>And here's the result of this call:<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhddK00Mr_AAoR1wrxzYsqdOOXxXHfT4VfaZ96HL8GWFdDTidwoR8-gKKB6br-a2ruFiP2MGK2__8-XOsAHxT7wVEmpgeWLy-gzFilwr2aMp_N1wutnWUTMZc6PSmBd7vFAipkOU7n8Bgo/s1600-h/output.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhddK00Mr_AAoR1wrxzYsqdOOXxXHfT4VfaZ96HL8GWFdDTidwoR8-gKKB6br-a2ruFiP2MGK2__8-XOsAHxT7wVEmpgeWLy-gzFilwr2aMp_N1wutnWUTMZc6PSmBd7vFAipkOU7n8Bgo/s640/output.png" width="640" /></a></div><br />
As you can see the method has been called first with input 6 which is the initial input we passed in, then 5, 4, 3, 2, 2, ... oops!! Can you spot it? the method is being called on the same input more than once! Think about this for a while, pretty logical, yeah!? Our strategy is based on dividing the problem into simpler subproblems. For example to get the 6th item in the Fibonacci sequence we divide the problem into two smaller problems, getting the 5th item, and 4th item and adding them together, then to get the 5th, you should get the 4th and 3rd, etc. The next figure shows how is this working.<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg-3DowJe06twbivkV9_fZEVn_1reSHISKGbDGvqcyyjS0QpTzIL7o9OlJL5y24O2wzMaq-yLkRzAW9lzarwnz2vDXkc_BtpjxdRde71XLa6mMl2Yyy3yA9eBjiyBGnXG45Do1qyZslPvY/s1600-h/tree.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="196" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg-3DowJe06twbivkV9_fZEVn_1reSHISKGbDGvqcyyjS0QpTzIL7o9OlJL5y24O2wzMaq-yLkRzAW9lzarwnz2vDXkc_BtpjxdRde71XLa6mMl2Yyy3yA9eBjiyBGnXG45Do1qyZslPvY/s400/tree.png" width="400" /></a></div><br />
<div class="separator" style="clear: both; text-align: center;"><br />
</div>As you notice the overlapping happens when solving one part of the problem includes solving another part of the problem, in such a case we can take advantage of this and simply memorize the solution for the overlapped problem and each time we need that result, we don't have to compute it again, we just supply it from wherever we stored it. Here's the modified method to do it: <br />
<pre class="csharp" name="code">static int FibFast(int n, ref int numberOfStepsTaken, Dictionary<int, int=""> store)</int,>
{
numberOfStepsTaken += 1;
if (n <= 1)
return 1;
if (!store.ContainsKey(n))
store[n] = FibFast(n - 1, ref numberOfStepsTaken, store) + FibFast(n - 2, ref numberOfStepsTaken, store);
return store[n];
}
</pre>If you run that same method on the same input (6) you should get 13 as the result (the same old result) but the number of iterations would be 11 which is about half the number of iterations the first method take. This doesn't seem to be a very huge enhancement, but let's see how the two methods act for bigger numbers. Running the first method of input equals to 30 we get the result 1346269 and number of iterations 2692537. Now running the second method on the same input (30) we get the result 1346269 -which is the same result- and number of iterations 59! That's a <b>HUGE </b>difference!<br />
<br />
<b>Now back to core, what does this have to do with the term Dynamic Programming??</b><br />
<i><b></b></i><i><span class="Apple-style-span" style="color: blue;">Actually, it's a very misleading term, historically it was invented by a mathematician called </span><b><span class="Apple-style-span" style="color: blue;">Bellmen </span></b><span class="Apple-style-span" style="color: blue;">and he was at the time being paid by the US defense department to work on something else. He didn't want them to know what he was doing, so he made up a name that he was sure it has no clue what it actually meant. Now we have to live with this forever :)</span></i>Unknownnoreply@blogger.com2tag:blogger.com,1999:blog-5568328146032664626.post-28096216596684868022010-01-21T13:39:00.000+02:002010-02-01T13:18:21.614+02:00The Zen Of PythonI found these fantastic guiding principles of the design of Python published <a href="http://www.python.org/dev/peps/pep-0020/">here </a>by Tim Peters, and once I saw them, I was like, Man! I ought to share these, so look them up on the site, or if you don't want to leave programming for COWARDS just yet, I'm quoting them here for you ;) : <br />
<br />
<i><b>The Zen of Python</b></i><br />
<i><br />
</i><br />
<i>Beautiful is better than ugly.</i><br />
<i>Explicit is better than implicit.</i><br />
<i>Simple is better than complex.</i><br />
<i>Complex is better than complicated.</i><br />
<i>Flat is better than nested.</i><br />
<i>Sparse is better than dense.</i><br />
<i>Readability counts.</i><br />
<i>Special cases aren't special enough to break the rules.</i><br />
<i>Although practicality beats purity.</i><br />
<i>Errors should never pass silently.</i><br />
<i>Unless explicitly silenced.</i><br />
<i>In the face of ambiguity, refuse the temptation to guess.</i><br />
<i>There should be one-- and preferably only one --obvious way to do it.</i><br />
<i>Although that way may not be obvious at first unless you're Dutch.</i><br />
<i>Now is better than never.</i><br />
<i>Although never is often better than *right* now.</i><br />
<i>If the implementation is hard to explain, it's a bad idea.</i><br />
<i>If the implementation is easy to explain, it may be a good idea.</i><br />
<i>Namespaces are one honking great idea -- let's do more of those!</i><br />
<br />
Those quotes are pure gold. One could think of writing them down on a board and keep that board hanged in front of his eyes, right above the computer screen!<br />
<br />
Awesome, awesome stuff!Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-5568328146032664626.post-30609201806463813282010-01-19T12:15:00.000+02:002010-02-01T13:30:39.929+02:00Into Git and Loving ItAs it is gaining popularity day by day,and as everyone I know likes it, I thought .. well, let's give it a try.<br />
Git is a powerful source control system. It's free, and open source. It's pretty simple to use, it's intended to handle both small and large projects, and it's so freakingly FAST.<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg3OdePywG7BXhSlhUNd6FN8LmWWkFoTlWUmh9sP3k1LOqz0L1F6JYVj-vgtnuykK9UdojmQMpyTYEhBDi4XxBcixplfObvwbIMRZDXEbZeGFsmFtqBpsVemHRif89Bc1jrnBqMtk9eCcM/s1600-h/chp_rocket.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg3OdePywG7BXhSlhUNd6FN8LmWWkFoTlWUmh9sP3k1LOqz0L1F6JYVj-vgtnuykK9UdojmQMpyTYEhBDi4XxBcixplfObvwbIMRZDXEbZeGFsmFtqBpsVemHRif89Bc1jrnBqMtk9eCcM/s320/chp_rocket.jpg" /></a></div><br />
<br />
Unlike SVN and TFS, Git is not centeralized. This means that every Git clone is a fully fledged repository with all versions and history information available.<br />
<br />
Git is written in C (well, mostly) and is available for many platforms. If you are a linux guy you can download Git from <a href="http://git-scm.com/">here</a> and if you are a Windows fellow then download <a href="http://code.google.com/p/msysgit/">msygit</a>.<br />
<br />
This post is aimed to be a tutorial introduction to Git. Together we will walk through the process of creating the repository, adding initial files to the repository, committing those files, changing them, creating branches, viewing differences, resolving conflicts, merging and finally pushing to the centeralized repository.<br />
<br />
Now to get started let's assume that you want to create a simple project which is basically an html file, a bunch of javascript files and a css file. Pick whatever directory you wish to create your initial files. After you're done right click the directory containing your files and select "Git Bash Here" (assuming that you already installed msygit). A command window will show up, to initialize your repository enter:<br />
<pre class="cpp" name="code">git init-db
</pre>This will create the repository for you (and will also create a default "master" branch). Now enter:<br />
<pre class="cpp" name="code">git add -a
</pre>to add all the files in this directory to the repository. You can select specific files by specifying the required file name like so:<br />
<pre class="cpp" name="code">git add filename.css
</pre>The selected files are now tracked by Git to your repsoitory, to commit those files to the repository (the LOCAL repository, remember?) :<br />
<pre class="cpp" name="code">git commit -a
</pre>This will open vim for you to enter a commit message. Enter your message, and quite vi, then Git will commit your changes to the DB.<br />
<br />
<b>Note: </b><br />
<i>If you're not familiar with vim or vi, to quite the editor saving the changes type ":wq" -that's colon wq- or ":q" to quit without saving. Or you can specify -m to the git commit command followed by the message you want in double quotes, like so: </i><br />
<pre class="cpp" name="code">git commit -a -m "my initial commit"
</pre><br />
Now try editing some files and then, to view the changes, type:<br />
<pre class="cpp" name="code">git diff
</pre>This will highlight the changes between your uncommitted version and the last committed version. If you want to see the history of your changes at any time, user:<br />
<pre class="cpp" name="code">git whatchanged
</pre>or use:<br />
<pre class="cpp" name="code">git whatchanged -p
</pre>to see the complete differences at each change.<br />
<br />
The very cool thing about Git is how easily it enables you to create new branches. For example, if you want to create an expreimental function inside a class file you're working on or inside a javascript file but you want it away from the master branch, you can easily create a new branch, checkout this branch, edit your file, and all the changes will be completely isolated from the master branch. To create a new branch:<br />
<pre class="cpp" name="code">git branch testBranch
git branch
</pre>The first command will create testBranch for you and the second command will list all the available branches on your repository (by far there should be only testBranch and the master branch "master").<br />
<br />
<b>Note:</b> <i>The selected branch has an * displayed before it. </i><br />
<i><br />
</i><br />
Now enter :<br />
<pre class="cpp" name="code">git checkout testBranch
</pre>to switch to the newly created branch. Try editing somefiles, and show the diffs.<br />
<pre class="cpp" name="code">git diff
</pre>You should now see the changes you made, commit those changes. And switch to the master branch:<br />
<pre class="cpp" name="code">git commit -a
git checkout master
</pre>If you look at the files you just edited when you were on testBranch -after switching to the master branch- you would notice that the changes you made while you were on testBranch are gone. However, if you switch to the testBranch again you will see your changes there. If you're happy with the changes you made on testBranch, you can merge those changes to the master branch by using the following command:<br />
<pre class="cpp" name="code">git merge testBranch
</pre>If there is no confilcts, you're allset. If there are conflicts you will have to resolve them manually and then commit the file. Git will show you which files have conflicts.<br />
Now, if you are done with the test branch and want to delte it, use:<br />
<pre class="cpp" name="code">git branch -d testBranch
</pre><br />
If you used to be a TFS and VSS guy like myself, take a deep sigh of relief and enjoy Git.<br />
I will try to blog more on Git on the next posts, stay tuned!Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5568328146032664626.post-92134284188896614272010-01-16T02:53:00.000+02:002010-01-16T02:54:06.244+02:00The Selected ORM and Isolation FrameworkA while ago I posted two little polls about the favorited isolation framework, and ORM. The results of the two posts were as follows<br />
<br />
Which ORM? <br />
1- NHibernate 49%(44 votes)<br />
2- LLBLGEN 34%(31 votes)<br />
3- Entity Framework 6%(6 votes)<br />
4- LINQ to SQL 6%(6 votes)<br />
5- Subsonice 2%(2 votes)<br />
<br />
Which Isolation Framework? <br />
1- Typemock Isolator 50%(10 votes)<br />
2- Moq 45%(9 votes)<br />
3- NMock2 5%(1 votes)<br />
4- RhinoMocks 0%(0 votes)<br />
5- Stubs 0%(0 votes)<br />
<br />
For myself I voted for NHibernate and Moq. I know all of those tools are purely awesome, though. <br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjtqoiuqX7lAi2-EW625thcXL60TuqgxaSYZnyI-v2J0S51BSJ9VSmi3locYhpIlhs8VZ7f-siLuHg0V0qZIVYGY3m71MK_jGASSRKrFutpgOIvlGI6CmRNM_yOtmhhFk_9vD213f_5mvc/s1600-h/testing.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjtqoiuqX7lAi2-EW625thcXL60TuqgxaSYZnyI-v2J0S51BSJ9VSmi3locYhpIlhs8VZ7f-siLuHg0V0qZIVYGY3m71MK_jGASSRKrFutpgOIvlGI6CmRNM_yOtmhhFk_9vD213f_5mvc/s320/testing.jpg" /></a><br />
</div><br />
So, dear reader, do you have any other suggestions for an ORM or an Isolation Framework?Unknownnoreply@blogger.com2tag:blogger.com,1999:blog-5568328146032664626.post-916248219431932322010-01-14T16:23:00.000+02:002010-01-14T16:32:52.807+02:00A Quick Tip: The Different Classes Of AlgorithmsAlgorithms are the heart of computer science. They are the thoughts, the ideas, and the most fun part of this industry. Scientists categorize the various known algorithms into 4 classes: Logarithmic, Linear, Quadratic and Exponential. Let's look at those briefly:<br />
1- Logarithmic Algorithms:<br />
This type is the fastest of those 4 classes. It has a run curve that looks something like this:<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhWsooe0s1wfj9QkrspGPxRojmJtxyGJ7wUF_qV7rF_skSqaoP-IMlVNWBdSWeBUrmccM8DUpsez380ET02F0frvtVNydDL9cHWMSSz1yCByhqjkQMYyAQJ6o2t2Pt709gtGytphonZfy4/s1600-h/x12-semi-log.gif" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhWsooe0s1wfj9QkrspGPxRojmJtxyGJ7wUF_qV7rF_skSqaoP-IMlVNWBdSWeBUrmccM8DUpsez380ET02F0frvtVNydDL9cHWMSSz1yCByhqjkQMYyAQJ6o2t2Pt709gtGytphonZfy4/s320/x12-semi-log.gif" /></a><br />
</div><br />
<div class="separator" style="clear: both; text-align: center;"><br />
</div>Where the x here is the number of items to be processed by the algorithm, and y is the time takes by the algorithm. As you can see from the figure, the time taken increases slowly when the number of items to be processed increase. Binary Search is a perfect example for a logarithmic algorithm. If you recall, binary search, divides the array into two halves and excludes one half each time it does a search. Here's a code example of binary search implementation in C#:<br />
<pre class="csharp" name="code">bool BSearch(int[] list, int item, int first, int last)
{
if(last - first < 2)
return list[first] == item || list[last] == item;
int mid = (first + last)/2;
if(list[mid] == item)
return true;
if (list[mid] > item)
return BSearch(list, item, first, mid - 1);
return BSearch(list, item, mid + 1, last);
}
</pre><br />
2- Linear Algorithms:<br />
Runs in time, linear to the input items. It's curve looks like the following:<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgLfcNAgKbejbF0SJxY0KN-b-M4iQ1w5gmQvYfHtXAuFAScuYkPuZFr8JELovT8orRuOJPksxZS6CmXRgicAtWMrnBUBOQ3ETkXkZhCybYNdHSoJ_yqy9pXyPU7yWFnAkLgIYp3ynnaJ_o/s1600-h/linear.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgLfcNAgKbejbF0SJxY0KN-b-M4iQ1w5gmQvYfHtXAuFAScuYkPuZFr8JELovT8orRuOJPksxZS6CmXRgicAtWMrnBUBOQ3ETkXkZhCybYNdHSoJ_yqy9pXyPU7yWFnAkLgIYp3ynnaJ_o/s320/linear.png" /></a><br />
</div><br />
<br />
A linear search is a typical example of that, where one would traverse the array or, whatever data structure, item by item. An implementation of linear search looks like this:<br />
<br />
<pre class="csharp" name="code">bool LinearSearch(int[] list, int item)
{
for(int i = 0; i < list.Length; i++)
if(list[i] == item)
return true;
return false;
}
</pre>3- Quadratic Algorithm: This one runs time grows to to the power of 2, with each increase in the input sizes, which means while processing 2 items the algorithm will do 4 steps, 3 items will take 9 steps, 4 items will take 16 steps, etc. The next figure shows how a quadratic curve might look like: <br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEilDtNfnhhMjDbWyQQdSzvUzhLJ62Sx54JcWRZBRhxOMsA0vIsyuIlBqkEkZ3jchmfKL_zsBv2aP-ei38TTvjtEa08DC6gT49Z-ukVjJgukg_lwNboqwlpNSj3DT6SlxRDaHbq0lriltMQ/s1600-h/quadratic.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEilDtNfnhhMjDbWyQQdSzvUzhLJ62Sx54JcWRZBRhxOMsA0vIsyuIlBqkEkZ3jchmfKL_zsBv2aP-ei38TTvjtEa08DC6gT49Z-ukVjJgukg_lwNboqwlpNSj3DT6SlxRDaHbq0lriltMQ/s320/quadratic.png" /></a> <br />
</div><br />
A famous example of an algorithm with quadratic growth is Selection Sort: <br />
<br />
<pre class="csharp" name="code">void SelectionSrot(int[] list)
{
int i, j;
int min, temp;
for (i = 0; i < list.Length - 1; i++)
{
min = i;
for (j = i + 1; j < list.Length; j++)
{
if (list[j] < list[min])
{
min = j;
}
}
temp = list[i];
list[i] = list[min];
list[min] = temp;
}
}
</pre><br />
4- Exponential Algorithm:<br />
This is the super slow of this list of four. It grows exponentially (that is, for 2 items it takes 2 ^ 2, for 3 items it takes 2^3, for 4 items it takes 2 ^ 4, etc.<br />
Again algorithms are the key to computer science, the most fun part of programmer's job. Choose your algorithms carefully and always try to improve.<br />
<br />
Hope this helps.Unknownnoreply@blogger.com2tag:blogger.com,1999:blog-5568328146032664626.post-90739202553058175402010-01-14T11:57:00.000+02:002010-01-17T13:35:20.754+02:00Tips For Web Developers: Minify Javascript Using Google's Closure CompilerA faster web site is a goal for every develoepr. We spend a lot of time optimizing server code and processes, parallelizing stuff, indexing<br />
and trying to enhance database performance. The goal behind all of these complicated actions is the ultimate goal: A Faster Site.<br />
These actions are necessary and handy to decrease your site response time, however, there are a lot of stuff that we, developers, usually ignore. Those are the optimizations required to happen on the client side. These client side optimizations are as important (probably more imprtant) as the server side optimizations.<br />
There are a lot of techniques to optimize the client side performance. These techniques include:<br />
<br />
<br />
<ul><li>Making Less HTTP Requests</li>
<li>Optimizing JavaScript</li>
<li>Optimizing CSS</li>
</ul><br />
<br />
And many more. For full details about all the possible techniques, check out <a href="http://code.google.com/speed/page-speed/docs/rules_intro.html">Google's page speed initiative</a>.<br />
In this post I will focus on optimizing javascript by minifying js files. For this I leverage <a href="http://code.google.com/closure/compiler/">Closure Compiler</a>, which is a very awesome tool to optimize Javascript developed by Google.<br />
Now suppose that I have an html document that looks like the following:<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhmVj1sIW6DO3S9fyFKbfacs2Vfb6VCUhQtQ27xkZoEn-BiLczBTUZnlRDJsLXZgwHLFTKSz4X89dhzFCTugzgsL9-ii1lLcaQcuqRyS0QJLG0bjDS4nb85ikKK1V0EPEHbrcxgfCHHwz0/s1600-h/dampledoc.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhmVj1sIW6DO3S9fyFKbfacs2Vfb6VCUhQtQ27xkZoEn-BiLczBTUZnlRDJsLXZgwHLFTKSz4X89dhzFCTugzgsL9-ii1lLcaQcuqRyS0QJLG0bjDS4nb85ikKK1V0EPEHbrcxgfCHHwz0/s320/dampledoc.png" /></a><br />
</div><br />
<br />
This document shall do a very little job actually. Simply a user keys his name in the textbox and clicks salute me which we will display a simple alert saying hello to this user.<br />
<br />
Below are two buttons -hide, and show. As the name of each button implies, the hide button will hide the area including the label, text box, and the Salute me button.<br />
<br />
To do this I'm gonna make use of jQuery 1.3.2. Here's the code needed to achieve the required functionality:<br />
<pre class="js" name="code">/*
The follwoing code is not part of jqueyr framework
*/
$(document).ready(function() {
$('#hiFiver').click(function() {
var userName = $('#txtName').val();
alert ("Hello " + userName);
});
$('#showButton').click(function() {
$('#hidden').show();
});
$('#hideButton').click(function() {
$('#hidden').hide();
});
});
</pre> For the sake of this demo I will append my code at the end of the actual jQuery code itself. Now my app is working as required, and my Javascript file size is 122 KB.<br />
<br />
Now let's run Closure Compiler and try to minify this.<br />
Closure Compiler is a java application, which means that you will need jre (Java Runtime Engine) to run it. You can download it from here<br />
<br />
Now I got my files (sample.html, script.js, compiler.jar) in one directory. To run the compiler, launch your terminal, and enter the follwoing command:<br />
<br />
java -jar compiler.jar --js script.js --js_output_file scriptMini.js<br />
<br />
Check your directory. You should find a new file with the name "scriptMini.js" created. The new script file is 55 KB in size, which is less the half size of the original file. To make sure it's working, change the script src attribute in the sample document to point to the new file. You should see that the app is still functioning properly.<br />
<br />
If you examin the newly created file, you will find that it doesn't contain any comments or spaces, all the optional semi-colons are removed, variable names are changed to shorter names (usually one character long).<br />
<br />
The closure complier is a fascinating tool, it's really handy and easy to use.<br />
From now on you should develop the habit of always minifing your Javascript files.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5568328146032664626.post-26217316269891487942010-01-13T15:13:00.000+02:002010-03-07T17:08:06.037+02:00Why is O(n) Is Pronounced "Big Oh" of n And Why Is "Geek" So Close To "Greek"?<div class="separator" style="clear: both; text-align: auto;"><br />
</div><div class="separator" style="clear: both; text-align: auto;"><br />
</div><div class="separator" style="clear: both; text-align: auto;">This one is really short, Today, some guy on the internet asked why is the asymptotic form O(n) is pronounced Big Oh? I instantly answered "because we are using the capital letter O to write it".<br />
</div><br />
This answer is wrong, the letter used is the Greek letter <a href="http://en.wikipedia.org/wiki/Omicron">Omicron</a>.<br />
So that's why it's pronounced Big Oh!<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><br />
</div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEji0dayAOUGURZ9nigEBGm2Wi4VB8Tw3_IaoQ2SBvBWOf5y3eZOIvIY4eWWQbY6RIXB6nwtoExPx_7vGHxUsIVL3UQAPooywhw6rWU07xCmo5nTnA8yhmaIX31CDy84nLaQ4EEnHxcYrgk/s1600-h/160px-Omicron_uc_lc.svg.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEji0dayAOUGURZ9nigEBGm2Wi4VB8Tw3_IaoQ2SBvBWOf5y3eZOIvIY4eWWQbY6RIXB6nwtoExPx_7vGHxUsIVL3UQAPooywhw6rWU07xCmo5nTnA8yhmaIX31CDy84nLaQ4EEnHxcYrgk/s320/160px-Omicron_uc_lc.svg.png" /></a><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjTLUs1_dMqa-dwNJHn4YuVcan8ib2aDJQEIcUTTgIUJaCyE8PZmAJqTGoPbcDEc-zOqd5viAdgO9Ca6brs8Y1vo969cUqSovQ7jONH-ikgmFxNAhu3_rCZ7wi4B2DOu6h5Bx079mb6Fag/s1600-h/images+(1).jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjTLUs1_dMqa-dwNJHn4YuVcan8ib2aDJQEIcUTTgIUJaCyE8PZmAJqTGoPbcDEc-zOqd5viAdgO9Ca6brs8Y1vo969cUqSovQ7jONH-ikgmFxNAhu3_rCZ7wi4B2DOu6h5Bx079mb6Fag/s320/images+(1).jpg" /></a><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjQK36jRWPe0S0qYwW-R3VVAyOpIL4N0PMIBegvVR1eq8RuPytWb_VpJb7jyqyGpKKMpDAgDIbHypirIkcoRT_aRqtHQErb_Sm554hyphenhyphenDtTA20LPtCjM-hffWENb4E75pxiriZo0UyTK83U/s1600-h/images.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjQK36jRWPe0S0qYwW-R3VVAyOpIL4N0PMIBegvVR1eq8RuPytWb_VpJb7jyqyGpKKMpDAgDIbHypirIkcoRT_aRqtHQErb_Sm554hyphenhyphenDtTA20LPtCjM-hffWENb4E75pxiriZo0UyTK83U/s320/images.jpg" /></a><br />
</div><br />
And the same reason applies to Big Theta, and Big Omega, because of using the Greek letters Theta and Omega represented in the above picture (the second and third figure respectively). It's all coming from the Greeks buddy! <br />
And probably this is also why the word Geek is so close to the word Greek in spelling, I'm not sure about this one though.<br />
<div><br />
</div><div><br />
</div>Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-5568328146032664626.post-68172912438050760282010-01-13T08:50:00.000+02:002010-01-17T13:34:19.930+02:00Remove Duplicate Items From an Array - A Classic Puzzle Today I cam a cross a kinda cool problem. A friend of mine who is at the same time a colleague working with me at the same office was trying to remove a duplicate item from an array of positive integers.<br />
The array has n items all unique except only one item. We need to come up with an algorithm that tells us which item is duplicated in maximum time of<br />
O(n) where n is the length of the array.<br />
<br />
To do that, let's first come up with some (less efficient) working algorithms. Here's the first one:<br />
<br />
We loop over the array starting from the item at index 0, then we traverse the remaining part of the array (1 : n-1) searching for the first item<br />
The C# code for this algorithm looks like the following:<br />
<pre class="csharp" name="code"> static int FirstDuplicate(int[] arr)
{
for(int i = 0; i < arr.Length - 1; i++)
{
for(int j = i + 1; j < arr.Length; j++)
{
if (arr[i] == arr[j])
return arr[i];
}
}
return -1;
}
</pre> As you can see, this algorithm is pretty bad. Foreach item in the array an inner loop is initiated to linerally look for that specific element in the<br />
rest of the array. If you do the math, you shall find that this algorithm runs in O(n2) order of growth.<br />
<br />
One way to improve this is to use an extra HashSet to store the items, and then look up each item in the HashSet. This is considered improvement as the<br />
lookup inside the HashSet is really fast.<br />
Here's the code in C#:<br />
<br />
<pre class="csharp" name="code"> static int FirstDuplicateWithHashSet(int[] arr)
{
HashSet<int> hashHset = new HashSet<int>(); </int></int>
for(int i = 0; i < arr.Length; i++)
{
if (hashHset.Contains(arr[i]))
return arr[i];
hashHset.Add(arr[i]);
}
return 0;
}
</pre>This is pretty good, but still not O(n).<br />
The next algorithm is quite tricky. The idea simply is to create a second array and insert each elemnt in the first array at an index equivalent to its<br />
value in the second array.<br />
For example if we have a list of 5 items [2, 4, 5, 2, 6], where the item 2 is duplicated at the 0 index and third index, and the maximum value in this<br />
array is 6. Now to find the duplicates in this list we create a second list with length 6 ( the length of the second array equals the maximum value in<br />
the first array). After creating this second list we loop over the first array take the first item (2 in our case) and insert it at the index 2 in<br />
the second array, then we take the second item (which is 4) and insert it at the 4th index in the second array, and so on. Each time we try to insert<br />
an item in the second array we check if it has a value first, if it is, then this item is duplicated.<br />
here's how the code would look like:<br />
<br />
<pre class="csharp" name="code">static int FirstDuplicate(int[] arr, int maxVal)
{
int[] temp = new int[maxVal+1];
for(int i =0; i < arr.Length; i++)
{
if (temp[arr[i]] == arr[i])
return arr[i];
temp[arr[i]] = arr[i];
}
return 0;
}
</pre> Note: The method expects the maximum value as an input, however, if you don't get the maximum value you can create the temp array with a size<br />
equal to int.MaxValue (which is not a good idea)<br />
<br />
This algorithm is probably not realistic but it doesn run in O(n) time.<br />
One more trick to add here, if you know the range of the items in the array (e.g. from 1 to 10) you can get the sum of the numbers of the array<br />
then subtract from it the sum of the numbers from 1 to 10, the remainder is the duplicated value.<br />
<br />
That was a quick tip that I thought is cool and wanted to share with ya! So what do you think dear fellows? Do you know of any possibly better<br />
algorithms? Do you suggest any optimization to the current ones?Unknownnoreply@blogger.com5tag:blogger.com,1999:blog-5568328146032664626.post-33448290172389967612010-01-06T10:27:00.000+02:002010-01-06T10:38:56.367+02:00Scalability Tip In ASP.NET And The MachineKey ElementYesterday, I came a cross a pretty annoying problem with a web application I'm working on nowadays.<br />
In short, the app is an ASP.NET MVC 1 app, that uses forms authentications to handle users logins.<br />
The app was working just fine, but when I started to scale the app and deploy it to more servers in the server farm, the weired behavior started to show up. When a user logs in to the application, the application preforms the operation successfully, logs in the user to the system and takes him to his personalized page. That sounds normal, however, if the user navigated to another part of the application (or just refreshes the current page), the application no longer recognizes him as a logged in user! If he refreshes two or three times, the app will see him as a logged in user again, a few more refreshes and he's nor more logged in and so on.<br />
<br />
<b>Similar Problem: </b><br />
I encountered a similar problem before, but the other one was because of accidental session expiration, and this happened because I was saving SessionState InProc, which (as you may have guessed) will be stored on the server memory (i.e. will not be shared between all server in the web farm).<br />
<br />
<b>This Problem: </b><br />
This problem is different because I'm not using SessionState at all. I'm just using cookies and you know that cookies are stored on the client, and is sent to the server with every request, so it will be sent to all servers (i.e. all servers should be able to read the cookie and determine if the user is logged in or not).<br />
<br />
<b>How Cookies Are Written: </b><br />
This got me thinking, the problem must be with the cookie itself. It seems like some servers can read the cookie successfully, and some can't. Why would that be?!!<br />
<br />
<b>Different Encryption/Decryption Key/Algorithm:</b><br />
Aha .... Cookies are encrypted before they are written on the client and decrypted before they are read again by the server. When the server that served the login request wrote the cookie, it encrypted it first (using an AutoGenerated encryption key and its chosen encryption algorithm. So apparently the chosen encryption keys and/or algorithms are different across the severs!<br />
<br />
<b>The Solution: </b><br />
The solution is quite simple actually. All I need to do is to ensure that all the servers use the same encryption algorithms and keys.<br />
This can be done by explicitly specifying the keys and algorithms in web.config inside the <b>machineKey </b><machinekey><b> </b>tag. </machinekey><br />
It should look something like this:<br />
<br />
<pre class="xml" name="code"><machinekey decryption="AES" decryptionkey="C9D61286123285F6FA496CFA190FC219BEF44A0943705404CF023C15A1FFFE02" validation="SHA1" validationkey="4B04D08CAA210ABF91B5E6E86763E0EEA4044284B4C962B4E51227868DF44D1D6D20F7309FBA3CE323404FA0FC39E6C8C6CE9FB842C9481B9938EB268AF5F85D">
</machinekey></pre><br />
PS: The keys lengths depend on the algorithms selected<br />
<span style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 11px; line-height: 15px;"></span><br />
<ul style="line-height: 15px; list-style-position: outside; list-style-type: disc; margin-bottom: 4px; margin-left: 17px; margin-top: 3px;"><li>For SHA1, set the <strong>validationKey</strong> to 64 bytes (128 hexadecimal characters).</li>
<li>For AES, set the <strong>decryptionKey</strong> to 32 bytes (64 hexadecimal characters).</li>
<li>For 3DES, set the <strong>decryptionKey</strong> to 24 bytes (48 hexadecimal characters).</li>
</ul><div><span style="line-height: 15px;"><br />
</span><br />
</div><div><span style="line-height: 15px;">The keys can be generated whatever way you like. Here's a simple function for generating these keys: </span><br />
</div><span style="font-family: monospace;"><span style="line-height: 15px; white-space: pre;"><span style="font-family: 'Times New Roman';"><span style="line-height: normal; white-space: normal;"><br />
</span></span></span></span><br />
<span style="font-family: monospace;"><span style="line-height: 15px; white-space: pre;"><span style="font-family: 'Times New Roman';"><span style="line-height: normal; white-space: normal;"></span></span></span></span><br />
<span style="font-family: monospace;"><span style="line-height: 15px; white-space: pre;"><span style="font-family: 'Times New Roman';"><span style="line-height: normal; white-space: normal;"></span></span></span></span><br />
<span style="font-family: monospace;"><span style="line-height: 15px; white-space: pre;"><span style="font-family: 'Times New Roman';"><span style="line-height: normal; white-space: normal;"><pre class="csharp" name="code">static string GenerateKey(int requiredLength)
{
byte[] buffer = new byte[requiredLength / 2];
RNGCryptoServiceProvider rng = new
RNGCryptoServiceProvider();
rng.GetBytes(buffer);
StringBuilder sb = new StringBuilder(requiredLength);
foreach (byte t in buffer)
sb.Append(string.Format("{0:X2}", t));
return sb.ToString();
}</pre></span></span></span></span><br />
<div><span style="line-height: 15px;"></span><br />
<span style="line-height: 15px;"></span><br />
<span style="line-height: 15px;"><br />
</span><br />
<span style="line-height: 15px;"><div>For more information about the <machinekey> tag see <a href="http://msdn.microsoft.com/en-us/library/w8h3skw9.aspx">here</a>, and <a href="http://msdn.microsoft.com/en-us/library/ms998288.aspx#paght000007_webfarmdeploymentconsiderations">here </a>to how to configure it, and if you wanna scroll a full page see <a href="http://msdn.microsoft.com/en-us/library/ms998288.aspx#paght000007_webfarmdeploymentconsiderations">this</a> for recommendations about deploying to server farms. </machinekey><br />
</div><div><br />
</div><div>Hope this helps.<br />
</div></span><br />
</div>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5568328146032664626.post-42705859866314058272010-01-06T08:55:00.000+02:002010-01-06T09:38:58.216+02:00Mix 2010 and My Chosen SessionsMix 2010 is open for public! <br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEja6qfgSbOWApL9-3OOGioMtWefJAXMYH1LplEZ8V_SYbPW8XJuiSux257JnpZrDgoANnd7gRDyyttjSlGmOhcvDg7CrIMo-XYSH4PkbtICJiKGTVD07RTjQvM-gApLixliRqOZnUlnBWw/s1600-h/mix_mosaic.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEja6qfgSbOWApL9-3OOGioMtWefJAXMYH1LplEZ8V_SYbPW8XJuiSux257JnpZrDgoANnd7gRDyyttjSlGmOhcvDg7CrIMo-XYSH4PkbtICJiKGTVD07RTjQvM-gApLixliRqOZnUlnBWw/s320/mix_mosaic.jpg" /></a><br />
</div><br />
Microsoft is using a different strategy for a major conference (Mix) this year. Developers and designers can now submit their sessions and those sessions will be voted up by the community. The chooses sessions will be included in the conference.<br />
<a href="http://visitmix.com/opencallvote/">Here's</a> a list of all the sessions available for voting. The voting started yesterday, Jan 5th. and will last for for 10 days. The selected sessions will be announced Jan 18th. <br />
Go ahead and vote for your session of choice. A lot of sessions out there? Would you like me to recommend some sessions to you? <br />
O.K I will .... <br />
Here are the sessions that I voted for: <br />
<br />
<ul><li> <a href="http://visitmix.com/opencallvote/Entry?entryId=BECOMI063">BECOMING SOCIAL. How to power up your website using social networks</a> by <a href="http://twitter.com/molant">@Anton Molleda</a></li>
<li><a href="http://visitmix.com/opencallvote/Entry?entryId=TENPRO121">Ten Protips for Javascript</a> by <a href="http://twitter.com/odetocode">K. Scott Allen</a></li>
<li><a href="http://visitmix.com/opencallvote/Entry?entryId=THINGS096">6 Things Every jQuery Developer Must Know by</a> <a href="http://www.twitter.com/elijahmanor">Elijah Manor</a></li>
<li><a href="http://visitmix.com/opencallvote/Entry?entryId=TOOLSF165">Tools for Agility</a> by <a href="http://twitter.com/cory_foy">Cory Foy</a><br />
</li>
<li><a href="http://visitmix.com/opencallvote/Entry?entryId=DESIGN038">Design for Developer</a> by Ian Muir</li>
</ul><div>Go ahead now, visit <a href="http://visitmix.com/opencallvote/">VisitMix.com</a> and vote!<br />
</div>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5568328146032664626.post-76741130317538180922009-12-30T15:38:00.000+02:002009-12-31T09:16:29.733+02:00.NET 4.0 Dynamic with ASP.NET MVC.NET 4.0 ships with a lot of cool, new stuff. For C# the major new feature is the support of dynamic programming. The idea with dynamic support in C#, in short, is that you can statically type a variable as dynamic (yeah, this sounds funny, statically typed as dynamic, I know) in which case the compiler will not check any methods or property binding on this object, rather it will defer all of these resolutions to runtime.<br />
It's not just that, but with dynamic support you can also declare your own objects to act as dynamic objects by implementing IDynamicMetaObjectProvider or -- as a shortcut -- by extending DynamicObject. Both types exist in the namespace System.Dynamic.<br />
There's also a very famous type called ExpandoObject.<br />
ExpandoObject is a dynamic object that you can simply create properties on it at runtime.<br />
Now the trick that I want to use, is to declare my views to extend the generic System.Web.Mvc.ViewPage<dynamic>. This will allow me to pass to my view any dynamic object and access its properties through the Model property of the view. </dynamic><br />
Here's a code example:<br />
<pre class="csharp" name="code"> using System.Dynamic;
using System.Web.Mvc;
public class ArticlesController : Controller
{
public ViewResult Index()
{
dynamic x = new ExpandoObject();
x.Title = "Programming for Cowards";
x.Url = "http://galilyou.blogspot.com";
//I even can nest
x.Author = new ExpandoObject();
x.Author.Name = "Galilyou";
return View(x);
}
}
</pre>In the above code I declare an ExpandoObject and start to set some properties on it like Title, Url, etc.<br />
I do this by simply using the syntax var.Property = value; which will <i>automagically </i>create a property on the dynamically created object which type will be the type of value.<br />
If you look closely you would notice that the Author property is an ExpandoObject itself. This nesting is allowed to as many levels as you want.<br />
Here's how my view looks like:<br />
<pre class="html" name="code">< %@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
</dynamic></pre><div><br />
Note, the view is declared to extend System.Web.Mvc.ViewPage<dynamic>. </dynamic><br />
</div><div>Now you can use the values of the model like so:<br />
<pre class="csharp" name="code">Model.Url
Model.Title
Model.Author.Name
</pre>here's how the entire view will look like: <br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgQT4vK0NVgll_9Ryw3EHezsWiOPe4ZWQ7kWLHg_PcFYbTnXs7Ksf0Be0eRpj0_GwvAQu77h3lmqCfxyR0SrSir7IlG4UeKV_YwU5SNJJS4rWbUISjZC-hWTAGz5KvoIZD9t1QU4cG2_Ko/s1600-h/view.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgQT4vK0NVgll_9Ryw3EHezsWiOPe4ZWQ7kWLHg_PcFYbTnXs7Ksf0Be0eRpj0_GwvAQu77h3lmqCfxyR0SrSir7IlG4UeKV_YwU5SNJJS4rWbUISjZC-hWTAGz5KvoIZD9t1QU4cG2_Ko/s640/view.png" /></a><br />
</div>And here's the page after running the application:<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEie2PulFuq6yacbtiT61PFvqGswIYv3CGfHRJDvNkK4TGGzNfm8bMB8HckDBk0SPKn1pRTBgF1Vcd76bwPX47CYWM95a0_BpFf_jGqekNMIPTOwhSIRYXAH61kf8i1DScpV2O99JD3vsbw/s1600-h/Untitled.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEie2PulFuq6yacbtiT61PFvqGswIYv3CGfHRJDvNkK4TGGzNfm8bMB8HckDBk0SPKn1pRTBgF1Vcd76bwPX47CYWM95a0_BpFf_jGqekNMIPTOwhSIRYXAH61kf8i1DScpV2O99JD3vsbw/s640/Untitled.png" /></a><br />
</div><br />
<br />
<b>Disclaimer: </b><br />
<i> You shouldn't do this in a large scale application. View model objects are still the best tool for the job when the application grows. However, if you want to quirk something pretty quickly -- a small thing-- you might get away with that.</i><br />
</div><div>Hope this helps.<br />
</div>Unknownnoreply@blogger.com3tag:blogger.com,1999:blog-5568328146032664626.post-13414422341386855752009-12-30T14:34:00.000+02:002009-12-30T14:42:41.226+02:00Back to Basics: Square Root Implementation in Python and C# (Newton's Method)In my last <a href="http://galilyou.blogspot.com/2009/12/back-to-basics-square-root.html">post</a> I introduced to you an extra simple algorithm to calculate square roots, it's called the Bi Section method. The Bi (pronounced by) part comes form the word binary. This is due to the fact that each time we pick a guess we pick it at a point in the middle between an upper bound and a lower bound. This technique is very useful in many cases in computer science (e.g. Binary Search is a very famous example of that).<br />
<br />
As you see the Bi Section method is really simple, however, it's not that effective.<br />
This time I will introduce a different method to calculate square roots, this method is called "<span style="font-family: verdana, arial, helvetica, sans-serif; font-size: small;">Newton-Raphson's method", it's named after <a href="http://en.wikipedia.org/wiki/Isaac_Newton">Issac Newton</a>, and <a href="http://en.wikipedia.org/wiki/Joseph_Raphson">Joseph Raphson</a>.</span><br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiEddhQLcBq0XYRS0TwgJ4Kn6jKYFgjU6jDtI9FDRtDrOI6HCTjEBCZ8nlBpqiB6ym7MKtRWoFwJOzE-YAV3m2xGm1UCdDH0z2MWQ3dCFWW66uEfQFgNp20IW0wBiiDpeqhySk64CkC4tQ/s1600-h/isaac_newton.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiEddhQLcBq0XYRS0TwgJ4Kn6jKYFgjU6jDtI9FDRtDrOI6HCTjEBCZ8nlBpqiB6ym7MKtRWoFwJOzE-YAV3m2xGm1UCdDH0z2MWQ3dCFWW66uEfQFgNp20IW0wBiiDpeqhySk64CkC4tQ/s320/isaac_newton.jpg" /></a><br />
</div><span style="font-family: verdana, arial, helvetica, sans-serif; font-size: small;"><br />
</span><br />
<span style="font-family: verdana, arial, helvetica, sans-serif; font-size: small;">This method is known to be really effective --especially when the initial guess is near from the correct answer-- and it's considered to be <i>the </i><span style="font-family: sans-serif; font-size: 13px; line-height: 19px;"><i> best known method for finding successively better approximations to the zeroes (or </i><a href="http://en.wikipedia.org/wiki/Root_of_a_function" style="background-attachment: initial; background-clip: initial; background-color: initial; background-image: none; background-origin: initial; background-position: initial initial; background-repeat: initial initial; color: #002bb8; text-decoration: none;" title="Root of a function"><i>roots</i></a><i>) of a </i><a href="http://en.wikipedia.org/wiki/Real_number" style="background-attachment: initial; background-clip: initial; background-color: initial; background-image: none; background-origin: initial; background-position: initial initial; background-repeat: initial initial; color: #002bb8; text-decoration: none;" title="Real number"><i>real</i></a><i>-valued </i><i><a href="http://en.wikipedia.org/wiki/Function_(mathematics)" style="background-attachment: initial; background-clip: initial; background-color: initial; background-image: none; background-origin: initial; background-position: initial initial; background-repeat: initial initial; color: #002bb8; text-decoration: none;" title="Function (mathematics)">function</a>. </i></span></span><br />
<span style="font-family: sans-serif; font-size: small;"><span style="font-size: 13px; line-height: 19px;">Explaining this method will require a certain amount of familiarity with Calculus and Algebra, so I'm not going to delve into this here. However, I will show you the code to do it in Python and C# (which, surprisingly you will find very simple). </span></span><br />
<span style="font-family: sans-serif; font-size: small;"><span style="font-size: 13px; line-height: 19px;"><br />
</span></span><br />
<span style="font-family: sans-serif; font-size: small;"><span style="font-size: 13px; line-height: 19px;">First, the code in Python:<br />
<br />
</span></span><br />
<span style="font-family: sans-serif; font-size: small;"><span style="font-size: 13px; line-height: 19px;"></span></span><br />
<span style="font-family: sans-serif; font-size: small;"><span style="font-size: 13px; line-height: 19px;"></span></span><br />
<span style="font-family: sans-serif; font-size: small;"><span style="font-size: 13px; line-height: 19px;"></span></span><br />
<span style="font-family: sans-serif; font-size: small;"><span style="font-size: 13px; line-height: 19px;"><pre class="python" name="code">def sqrtWithPrecisonNR(x, precision):
assert x >= 0, 'x must be non-negative, not' + str(x)
assert precision > 0, 'epsilon must be positive, not' + str(precision)
x = float(x)
guess = x/2.0
diff = guess**2 -x
ctr = 1
while abs(diff) > precision and ctr <= 100:
guess = guess - diff/(2.0*guess)
diff = guess**2 -x
ctr += 1
assert ctr <= 100, 'Iteration count exceeded'
print 'NR method. Num. iterations:', ctr, 'Estimate:', guess
return guess
</pre></span></span> <span style="font-family: sans-serif; font-size: small;"><span style="font-size: 13px; line-height: 19px;"> </span></span> <span style="font-family: sans-serif; font-size: small;"><span style="font-size: 13px; line-height: 19px;"> </span></span> <span style="font-family: sans-serif; font-size: small;"><span style="font-size: 13px; line-height: 19px;">Second, the code in C#: </span></span><br />
<span style="font-family: sans-serif; font-size: small;"><span style="font-size: 13px; line-height: 19px;"></span></span><br />
<span style="font-family: sans-serif; font-size: small;"><span style="font-size: 13px; line-height: 19px;"></span></span><br />
<span style="font-family: sans-serif; font-size: small;"><span style="font-size: 13px; line-height: 19px;"></span></span><br />
<span style="font-family: sans-serif; font-size: small;"><span style="font-size: 13px; line-height: 19px;"><pre class="csharp" name="code">float SqrtWithPrecisonNR(float x, float precision)
{
if (x < 0 || precision <= 0)
throw new ArgumentException("x, and precission gotta be non negative numbers");
float guess = x/2.0f;
float diff = guess*guess - x;
int counter = 1;
while(Math.Abs(diff) > precision && counter <= 100)
{
guess = guess - diff/(2.0f*guess);
diff = guess*guess - x;
counter++;
}
if(counter > 100)
throw new Exception("100 iterations done with no good enough answer");
Console.WriteLine("Num of Iterations: {0} , estimate: {1}", counter, guess);
return guess;
}
</pre><br />
Now, I want you to try this method with the <a href="http://galilyou.blogspot.com/2009/12/back-to-basics-square-root.html">last one</a> and see the difference. <br />
Here's a helper function that will test the two methods with input 2 as the root and 0.000001 precision: <br />
<br />
<br />
<br />
<pre class="python" name="code">def testMethods():
sqrtWithPrecision(2, 0.000001)
sqrtWithPrecisionNR(2, 0.000001)
</pre></span></span><span style="font-family: sans-serif; font-size: small;"><span style="font-size: 13px; line-height: 19px;"><br />
You should see that the Newton's method is much faster and this difference in speed will be totally apparent when you try it on bigger numbers.<br />
</span></span> <span style="font-family: sans-serif; font-size: small;"><span style="font-size: 13px; line-height: 19px;"> </span></span> <span style="font-family: sans-serif; font-size: small;"><span style="font-size: 13px; line-height: 19px;"> </span></span> <br />
<span style="font-family: sans-serif; font-size: small;"><span style="font-size: 13px; line-height: 19px;">For more details about the Newton's method including the mathematical stuff see <a href="http://en.wikipedia.org/wiki/Newton's_method">here</a></span></span>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5568328146032664626.post-68065484094911888922009-12-29T17:54:00.000+02:002009-12-30T09:20:15.530+02:00Back to Basics: Square Root Implementation in Python<span style="font-family: Arial; font-size: small;"><span style="font-size: 13px;">Two days ago a friend of mine who is a computer science student asked me about the simplest square root algorithm that I know about. Well, I know how pesky students suffer when trying to computer square roots, so I had to choose an easy one.</span></span><br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9d9tnTyyEpSIDrqVNqMNUWVy5S1hnVSv0MEezl-S_E2FOEPLxaLgpBJmWf7Xz5NnEI5I4bswVEmXvC4f4NwYfLwvMcePyYK5mJDENTYCONL2Uc9_rcGpx6Y5_tx44gUpJ1TtfStDtMMQ/s1600-h/445spongebobsquareroot.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9d9tnTyyEpSIDrqVNqMNUWVy5S1hnVSv0MEezl-S_E2FOEPLxaLgpBJmWf7Xz5NnEI5I4bswVEmXvC4f4NwYfLwvMcePyYK5mJDENTYCONL2Uc9_rcGpx6Y5_tx44gUpJ1TtfStDtMMQ/s320/445spongebobsquareroot.png" /></a><br />
</div><span style="font-family: Arial; font-size: small;"><span style="font-size: 13px;"><br />
</span></span><br />
<span style="font-family: Arial; font-size: small;"><span style="font-size: 13px;"><br />
</span></span><br />
<span style="font-family: Arial; font-size: small;"><span style="font-size: 13px;">I know about the famous <a href="http://www.codemaestro.com/reviews/9">Cramack method</a> but this sounds complicated to me (though it's the most efficient method AFAIK). So I preferred the goody (Guess, Evaluate, Improve) method. So for example if I want to calculate the square root of the number let's say, 2, my strategy will be like the following: </span></span><br />
<span style="font-family: Arial; font-size: small;"><span style="font-size: 13px;"><br />
</span></span><br />
<span style="font-family: Arial; font-size: small;"><span style="font-size: 13px;">1- Pick a guess (1 for example)</span></span><br />
<span style="font-family: Arial; font-size: small;"><span style="font-size: 13px;">2- Evaluate that guess: is 1 * 1 <b><i>near enough</i></b> to 2 (see the bold near enough expression!)</span></span><br />
<span style="font-family: Arial; font-size: small;"><span style="font-size: 13px;">3- If the guess is not near enough, Improve it. </span></span><br />
<span style="font-family: Arial; font-size: small;"><span style="font-size: 13px;"><br />
</span></span><br />
<span style="font-family: Arial; font-size: small;"><span style="font-size: 13px;">Note that I didn't use the term "<b>equals</b>" when evaluating the expression, rather I used the term "<b>near enough</b>" and this is because, with numbers that are not full squares (like 2 for example), the square root is going to be a floating point number (square root of 2 = 1.414213562373095). Now if you multiply this number --the square root of 2-- by itself, you should expect to have 2 as an answer. Well, that's not gonna happen, rather you're going to get (2.0000000000000004). This is happening due to the way that computers handle floating point numbers --which is a topic of other series of posts by itself. In this case if you used the term equals (or == operator) when evaluating the guess you will never make it, and your program will not halt. That's why I carefully used the term <b>near enough. </b>Defining what near enough means is your choice now, for certain situations you might consider a number that is less than the square root by 0.1 is near enough or 0.001 or 0.0001, etc. This depends on the level of precision that you need for your specific scenario.</span></span><br />
<span style="font-family: Arial; font-size: small;"><span style="font-size: 13px;"><b><br />
</b></span></span><br />
<span style="font-family: Arial; font-size: small;"><span style="font-size: 13px;"><b>The implementation: </b></span></span><br />
<span style="font-family: Arial; font-size: small;"><span style="font-size: 13px;">Here's a python implementation of this algorithm.</span></span><br />
<span style="font-family: Arial; font-size: small;"></span><br />
<span style="font-family: Arial; font-size: small;"></span><br />
<span style="font-family: Arial; font-size: small;"></span><br />
<span style="font-family: Arial; font-size: small;"></span><br />
<span style="font-family: Arial; font-size: small;"></span><br />
<span style="font-family: Arial; font-size: small;"></span><br />
<span style="font-family: Arial; font-size: small;"></span><br />
<span style="font-family: Arial; font-size: small;"><pre class="python" name="code">## calculates the square root of a positive number
## with the passed in precision
def sqrtWithPrecision(x, precision):
## The precision must be greater than zero,
## root must be a positive number
assert(precision > 0, str(precision), 'is not a valid value, it must be a positive integer')
assert x > 0, 'root can not be a negative number'
low = 0
high = max(x, 1)
counter = 0
guess= (low + high) /2.0
while abs (guess ** 2 -x) > precision and counter <= 100:
if(guess ** 2 < x):
low = guess
else:
high = guess
guess = (low + high) / 2.0
counter += 1
assert counter <= 100, '100 iterations done and no good answer'
## printing the number of iterations,
## in productive code, you might want to remove the next line
print 'Num of iterations:', counter, 'Estimate:', guess
return guess</pre><div><br />
And here's a c# example:<br />
<br />
<pre class="csharp" name="code">float sqrtWithPrecision(float x, float precision)
{
if (x < 0 || precision <= 0)
throw new ArgumentException("x, and precission gotta be non negative numbers");
float low = 0;
float high = Math.Max(1f, x);
float guess = (low + high)/2f;
int counter = 0;
while( Math.Abs(guess * guess - x) > precision && counter <= 100)
{
if (guess * guess < x)
low = guess;
else
high = guess;
guess = (low + high)/2f;
counter++;
}
if(counter > 100)
throw new Exception("100 iterations done with no good answer");
Console.WriteLine("Num of Iterations: {0} , estimate: {1}", counter, guess);
return guess;
}</pre></div></span>Unknownnoreply@blogger.com2tag:blogger.com,1999:blog-5568328146032664626.post-71840913848328119542009-12-29T11:08:00.001+02:002009-12-29T14:22:06.282+02:00What Can You Learn From Us? What Can We Learn From You?<div class="formspringmeQuestion">Today I got a very interesting question from one of my Twitter friends <a href="http://twitter.com/splattne">splattne</a>. The question was:<br />
</div><div class="formspringmeQuestion"><a href="http://www.formspring.me/Galilyou/q/11132997">What can we (Europeans/Americans) learn from your culture? What can you learn from ours?</a> <br />
</div><div class="formspringmeQuestion"><br />
</div><div class="formspringmeQuestion">Here's how I answered the question:<br />
</div><div class="formspringmeQuestion"><br />
</div><div class="formspringmeAnswer"><i>Wow, that's a big one! <br />
I really like your question, Stefan. This kind of constructive thinking is one of the most important methods we can use to avoid conflicts (which might eventually develop wars, and bad stuff).<br />
I will start by what I think that we can learn from you: </i><br />
</div><div class="formspringmeAnswer"><i><br />
<b> 1- Hardwork:</b></i><br />
</div><div class="formspringmeAnswer"><i> yes, we're lazy people. Even for the poorer countries (like mine) people are satisfied by working less and gaining less (less than enough). </i><br />
</div><div class="formspringmeAnswer"><i><br />
<b> 2- Democracy:</b></i><br />
</div><div class="formspringmeAnswer"><i> I'm not gonna through a discussion with this because it's very obvious for everyone that democracy in our countries is just a shallow word. I mean, come on, every president is preparing for his son to take his place nowadays. This is happening in Egypt, Libya, Tunisia, and many others. </i><br />
</div><div class="formspringmeAnswer"><i><br />
<b> 3- How to learn and teach: </b></i><br />
</div><div class="formspringmeAnswer"><i>Education systems in most (if not all) of the Arabic countries are ridiculously inefficient. Chemistry students here enters the chemistry lab one or two times for the whole semester. </i><br />
</div><div class="formspringmeAnswer"><i><br />
<b> What can you learn from us: </b></i><br />
</div><div class="formspringmeAnswer"><i><br />
<b> 1- Socializing:</b></i><br />
</div><div class="formspringmeAnswer"><i><b></b> Around here the social relationships are much much better that there in US and Europe. </i><br />
</div><div class="formspringmeAnswer"><i><br />
<b> 2- Conviction:</b></i><br />
</div><div class="formspringmeAnswer"><i> Though poor is everywhere, we are not so obsessive with money! A little can satisfy us. </i><br />
</div><div class="formspringmeAnswer"><i><br />
<b> 3- Harmony:</b> </i><br />
</div><div class="formspringmeAnswer"><i>Different races live together with harmony and love. I've never heard (in an Arabic community) that some one shot another because of his skin color.</i><br />
</div><div class="formspringmeAnswer"><i><br />
At the end, the thing that can really teach you a lot is the Arabic History. We are a bunch of shallow nations nowadays, our influence on the outer environment is very weak, but once we were a real example of a united, well educated, merciful, and highly organized nation. <br />
Thank you again for asking this question Stefan, and I really hope if my answer helps.</i><br />
</div><div class="formspringmeFooter"><br />
</div><div class="formspringmeFooter">What do you think dear reader? What else can we learn from the Europeans/Americans (the good things)? And what can they learn from us(only the good things)?<br />
</div>Unknownnoreply@blogger.com2tag:blogger.com,1999:blog-5568328146032664626.post-57305779402167061282009-12-29T10:20:00.001+02:002009-12-29T10:30:35.302+02:00FormSpring<b><br />
</b><br />
<b>ASK ME ANYTHING</b><br />
<br />
Today I came a cross this <a href="http://formspring.me/">site</a>. The main idea here is that people can ask each other questions and get them to answer them. It also integrates with a lot of other sites like <a href="http://twitter.com/">Twitter</a>, <a href="http://www.blogger.com/">Blogger</a>, etc. There are a lot of my twitter friends on FormSpring.<br />
I think the idea is simple and very appealing. Take a look at it and feel free to ask me anything <a href="http://formspring.me/Galilyou" target="_blank">http://formspring.me/Galilyou</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5568328146032664626.post-85904998674100443392009-12-10T14:01:00.000+02:002009-12-13T16:35:48.864+02:00Pretty Neat Extensions For Google ChromeToday I took a quick whirl to look at some of the avilable extensions for Google Chrome. And here are some of those that I find interesting:<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgNOKs4B6sQaZI71dLxZ_4gGGUSRdB-38iWf3WWHTu8sWAiczx1hfBAO6SBjHrBnx94UCobl9DBCSiO7EcdJDC8lHofd2WhxEWgMOndLhjYWTPjthu4fjrg8Jy1kkkaPV0S_RQAx-gZjxM/s1600-h/chrome1.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgNOKs4B6sQaZI71dLxZ_4gGGUSRdB-38iWf3WWHTu8sWAiczx1hfBAO6SBjHrBnx94UCobl9DBCSiO7EcdJDC8lHofd2WhxEWgMOndLhjYWTPjthu4fjrg8Jy1kkkaPV0S_RQAx-gZjxM/s320/chrome1.jpg" /></a><br />
</div><br />
<ol><li><a href="https://chrome.google.com/extensions/detail/aphncaagnlabkeipnbbicmcahnamibgb">Wave Notifier</a> : As the name implies it's a notification plugin for <a href="http://wave.google.com/">Google Wave</a>. Wave Notifier let's you know if you have any new waves or replies and display a counting number holding the number of the new waves. You don't have to keep your wave page open and switch to it every minute or so to see if you get a new wave, or if x of your friends replied to a wave you sent to them. </li>
<li><a href="https://chrome.google.com/extensions/detail/ajpgkpeckebdhofmmjfgcjjiiejpodla">Xmarks Bookmark Sync</a>: A bookmarks plugin that synchronizes your bookmarks to <a href="http://www.xmarks.com/">Xmarks</a>. You just login using your Xmarks account (or register if you don't already have one) and then you can click the Xmarks button and then click Sync Now.</li>
<li><a href="https://chrome.google.com/extensions/detail/aapbdbdomjkkjkaonfhkkikfgjllcleb">Google Translate</a>: Translate any web page using Google Translator just for one click. </li>
<li><a href="https://chrome.google.com/extensions/detail/pengoopmcjnbflcjbmoeodbmoflcgjlk">Blog This</a>: This is actually a cool one --still overwhelmingly buggy though. It lets you post to your blogger blog from any webpage. </li>
<li><a href="https://chrome.google.com/extensions/detail/mihcahmgecmbnbcchbopgniflfhgnkff">Google Mail Checker</a>: A notification for Gmail that let's you know whenever you get new emails.</li>
<li><a href="https://chrome.google.com/extensions/detail/apflmjolhbonpkbkooiamcnenbmbjcbf">Google Reader Notifier</a>: Notifies you with your new Google Reader items.</li>
<li><a href="https://chrome.google.com/extensions/detail/ookhcbgokankfmjafalglpofmolfopek">Google Calendar Notifier</a>: Same as the two above, it notifies you with your calendar events.</li>
<li><a href="https://chrome.google.com/extensions/detail/nnbmlagghjjcbdhgmkedmbmedengocbn">Doc Viewer</a>: Automatically views PDF/PPT documents using Google Docs Viewer.</li>
<li><a href="https://chrome.google.com/extensions/detail/hehijbfgiekmjfkfjpbkbammjbdenadd">IE Tab</a>: Yes, it's an Internet Explorer tab inside Google Chrome! </li>
<li><a href="https://chrome.google.com/extensions/detail/ognampngfcbddbfemdapefohjiobgbdl">Speed Tracer</a>: This one is actually the rock star of all of these extensions (at least for me). You enable it, and then it goes and analyze the processing of a web page that you are requesting. It displays very useful graphs and charts that are extremely helpful for you as a developer to inspect and discover areas of improvements in your web site. More on the very thing later, stay tuned!</li>
</ol><div>Those were some of the many extensions available now for Google Chrome. Go ahead and take a look at the official extensions page from Google <a href="https://chrome.google.com/extensions/">here</a>.<br />
</div><div><br />
</div><div>Those were some of what I liked, what do you like dear reader?<br />
</div>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5568328146032664626.post-83880614347798086212009-12-06T11:09:00.000+02:002010-01-17T13:52:04.868+02:00Which Isolation Framework?In the world of unit testing Isolation Frameworks are everywhere. Isolation Frameworks are very handy tools to help you create mock objects. According to <a href="http://en.wikipedia.org/wiki/Mock_object">Wikipedia</a>:<br />
<i>“</i><b><i>mock objects</i></b><i> are simulated objects that mimic the behavior of real objects in controlled ways”</i><br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijW6AIkIK4zTdD387sQ9j5gyzlIrqdz3R66IRKBuHnbOE8aZ6jYEhV1pPGnkcJv5mi-P9hXfoqn8XhlDo5IGThyzqUV1HOPW2FXyKUnQKqjYyMd0AlB7n6TGKpAbfy975WleyhAcayhvE/s1600-h/peaceful-isolation.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijW6AIkIK4zTdD387sQ9j5gyzlIrqdz3R66IRKBuHnbOE8aZ6jYEhV1pPGnkcJv5mi-P9hXfoqn8XhlDo5IGThyzqUV1HOPW2FXyKUnQKqjYyMd0AlB7n6TGKpAbfy975WleyhAcayhvE/s640/peaceful-isolation.png" /></a><br />
</div><br />
<div class="separator" style="clear: both; text-align: center;"><br />
</div><br />
In the world of .NET there are a lot of tools out there to be used as Isolation Frameworks. There have been a lot of debate around the best isolation framework –Including this <a href="http://stackoverflow.com/" target="_blank">StackOverflow</a> <a href="http://stackoverflow.com/questions/37359/what-c-mocking-framework-to-use" target="_blank">question</a>. <br />
If you have used any mocking framework, and felt like it’s a good tool to use, please vote on the poll on the left to this post or leave a comment about your experience with your preferred isolation framework.Unknownnoreply@blogger.com0