/* 0 = Sunday, 1 <= m <= 12, y > 1752 or so */
int dayofweek(int y, int m, int d)
{
static int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
y -= m < 3;
return (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;
}
Wednesday, March 18, 2015
Favorite Day-of-Week calculation
Wednesday, January 28, 2015
A slight-of hand with .NET Lazy
The following is an example of a better way to read a value from a C# dictionary.
In C#/.NET, you will get an exception if you specify an non-existent key when attempting to read a value from a Dictionary. The workaround is to call the TryGetValue method, which is awkward because of the out parameter, and the requirement of the additional variable declaration (< C#6).
Sometimes the behavior that you want is to get a null or 0 value when using an invalid key. Other times you want to simply test the returned value to see if actually has a value, similar to Option/Maybe idiom in other languages.
Because of the extensible nature of C#, you can kinda have your cake an eat it to. There's multiple ways to solve this problem, and some cool functional libraries have this built in (such as https://github.com/louthy/language-ext ), but with some slight-of hand, you can actually re-purpose the .NET built-in Lazy class to do this for you.
A Lazy object is an object that holds another object (or value), but it may be empty. The reason it exists is for "memoization", in that, the Lazy object starts out empty, and then later, it may be filled with a value.
But no is stopping you from using Lazy as a way to indicate an optional value. The following is an extension to IDictionary called GetValue. When called with an existing key, it returns a Lazy object containing the value. If the key does not exist, it returns an empty Lazy object. You just have to call IsValueCreated on the Lazy object to determine if the value exists. Alternatively, you can just use the .Value property and use the type's default value, such as 0 or null, when the key doesn't exist. Depending on what you're doing, that may be what you want.
Either way, you don't have to use TryGetValue
References:
http://programmers.stackexchange.com/questions/159096/return-magic-value-throw-exception-or-return-false-on-failure/264516#264516
http://www.extensionmethod.net/csharp/idictionary/idictionary-getvalue
In C#/.NET, you will get an exception if you specify an non-existent key when attempting to read a value from a Dictionary. The workaround is to call the TryGetValue method, which is awkward because of the out parameter, and the requirement of the additional variable declaration (< C#6).
Sometimes the behavior that you want is to get a null or 0 value when using an invalid key. Other times you want to simply test the returned value to see if actually has a value, similar to Option/Maybe idiom in other languages.
Because of the extensible nature of C#, you can kinda have your cake an eat it to. There's multiple ways to solve this problem, and some cool functional libraries have this built in (such as https://github.com/louthy/language-ext ), but with some slight-of hand, you can actually re-purpose the .NET built-in Lazy class to do this for you.
A Lazy object is an object that holds another object (or value), but it may be empty. The reason it exists is for "memoization", in that, the Lazy object starts out empty, and then later, it may be filled with a value.
But no is stopping you from using Lazy as a way to indicate an optional value. The following is an extension to IDictionary called GetValue. When called with an existing key, it returns a Lazy object containing the value. If the key does not exist, it returns an empty Lazy object. You just have to call IsValueCreated on the Lazy object to determine if the value exists. Alternatively, you can just use the .Value property and use the type's default value, such as 0 or null, when the key doesn't exist. Depending on what you're doing, that may be what you want.
Either way, you don't have to use TryGetValue
References:
http://programmers.stackexchange.com/questions/159096/return-magic-value-throw-exception-or-return-false-on-failure/264516#264516
http://www.extensionmethod.net/csharp/idictionary/idictionary-getvalue
Wednesday, January 21, 2015
C# Dictionary to XML
Do you have a string dictionary in .NET code (C#) that want to write out to disk in nicely formatted XML?
A single line of text will do this:
new XElement("root", d.Select(
kv => new XElement(kv.Key, kv.Value)))
.Save(filename, SaveOptions.OmitDuplicateNamespaces);
To read the XML file back later into a dictionary, is another single line:
var d = XElement.Parse(File.ReadAllText(filename))
.Elements()
.ToDictionary(k =>
k.Name.ToString(),
v => v.Value.ToString());
That's it!
A single line of text will do this:
new XElement("root", d.Select(
kv => new XElement(kv.Key, kv.Value)))
.Save(filename, SaveOptions.OmitDuplicateNamespaces);
To read the XML file back later into a dictionary, is another single line:
var d = XElement.Parse(File.ReadAllText(filename))
.Elements()
.ToDictionary(k =>
k.Name.ToString(),
v => v.Value.ToString());
That's it!
Monday, January 19, 2015
Easily Zip just the source of a Visual Studio project
When playing around, creating new Visual Studio projects such as a weekend project, you want an easy way to zip up my source and not worry about .pdb, obj/bin files, etc. files.
The .gitignore file is created when you create a Visual Studio project with the "Create new Git repository" selected.
You don't need to use pkzip because Git has the archiving feature built-in. Just type:
git archive -o all.zip HEAD
and it will create all.zip of the latest source, without any of the stuff you don’t want in the .zip file like bin, obj, exes, nuget assemblies, etc.
Sunday, January 18, 2015
Double click file to run a PowerShell script
Typically, you cannot double click on a PowerShell script (.ps1 file) and have it automatically run, like you could with a batch file (.bat or .cmd). This is a good thing because someone may accidentally run something that was not meant to be run.
But what if you need to have someone run a PowerShell script and you just want them to double click a shortcut of some sort to make it happen.
The trick is to create a batch file that invokes the PowerShell. If you give the batch file and PowerShell script the same base name, then the batch file content doesn't have to change:
But what if you need to have someone run a PowerShell script and you just want them to double click a shortcut of some sort to make it happen.
The trick is to create a batch file that invokes the PowerShell. If you give the batch file and PowerShell script the same base name, then the batch file content doesn't have to change:
@echo off
pushd "%~d0"
pushd "%~dp0"
powershell.exe -sta -c "& {.\%~n0.ps1 %*}"
popd
popd
So, for instance, if you wish to run a PowerShell script called xyz.ps1, just create xyz.bat with the above content.
That's it!
By the way, the two pushd/popds are necessary in case the user's CDs is on a different drive. Without the outer set, the CD on the drive with the script will get lost.
That's it!
By the way, the two pushd/popds are necessary in case the user's CDs is on a different drive. Without the outer set, the CD on the drive with the script will get lost.
Friday, November 21, 2014
How do I specify Git Commit id (hash) when launching a build with TFSBuild.exe?
TFSBuild.exe is the method by which you launch TFS build from the command line. TFSBuild.exe doesn't indicate how to specify a Git commit Id (the hash of the commit).
TFSBuild.exe discusses the /getOption:Custom option which, when used, lets use specify the change-set or label to base the build on, by specifying the change-set or label identifier with the /customGetVersion option. For a label, you start with an "L". For a change-set, you start with a "C".
You specify the git commit-id using the "Label" syntax, but add a "G:ref:" before the commit ID. As in: /customGetVersion:LG:ref:
Full syntax:
TFSBuild start teamProjectCollectionUrl teamProject definitionName /queue /getOption:Custom /customGetVersion:LG:ref:
Example usage:
TFSBuild start http://gitsourceserver:8080/tfs/MyCompany MyTeamProject MyBuildDefinition /queue /getOption:Custom /customGetVersion:LG:ref:0c9cc3ce
Saturday, November 15, 2014
Closures in C#, just like in JavaScript
How would I rewrite this JavaScript routine in C# using closure?
function makeConverter(toUnit, factor, offset) {
offset = offset || 0;
var converter = function (input) {
return ((offset + input) * factor).toFixed(2) + " " + toUnit;
};
return converter;
}
var milesToKm = makeConverter('km', 1.60936);
var poundsToKg = makeConverter('kg', 0.45460);
var farenheitToCelsius = makeConverter('degrees C', 0.5556, -32);
log(milesToKm(10));
log(poundsToKg(2.5));
log(farenheitToCelsius(98));
You can do the same thing in C#:
public static Func<double, string> makeConverter(string toUnit, double factor, double offset = 0.0)
{
return (input) => string.Format("{0:0.##} {1}", (offset + input) * factor, toUnit);
}
public static void Main()
{
var milesToKm = makeConverter("km", 1.60936);
var poundsToKg = makeConverter("kg", 0.45460);
var farenheitToCelsius = makeConverter("degrees C", 0.5556, -32);
Console.WriteLine("{0}", milesToKm(10));
Console.WriteLine("{0}", poundsToKg(2.5));
Console.WriteLine("{0}", farenheitToCelsius(98));
}
You can further reduce it down to a single method:
public static void Main()
{
Func<string, double, double, Func<double, string>> makeConverter =
(toUnit, factor, offset) => (input) => string.Format("{0:0.##} {1}", (offset + input) * factor, toUnit);
var milesToKm = makeConverter("km", 1.60936, 0.0);
var poundsToKg = makeConverter("kg", 0.45460, 0.0);
var farenheitToCelsius = makeConverter("degrees C", 0.5556, -32);
Console.WriteLine("{0}", milesToKm(10));
Console.WriteLine("{0}", poundsToKg(2.5));
Console.WriteLine("{0}", farenheitToCelsius(98));
}
You can even use old-style can use C# 2 syntax (yes, C# has had closure since 2005)
public delegate string del_t(double input);
public static del_t makeConverter(string toUnit, double factor, double offset = 0.0)
{
return delegate(double input)
{
return string.Format("{0:0.##} {1}", (offset + input) * factor, toUnit );
};
}
public static void Main()
{
var milesToKm = makeConverter("km", 1.60936);
var poundsToKg = makeConverter("kg", 0.45460);
var farenheitToCelsius = makeConverter("degrees C", 0.5556, -32);
Console.WriteLine("{0}", milesToKm(10) );
Console.WriteLine("{0}", poundsToKg(2.5) );
Console.WriteLine("{0}", farenheitToCelsius(98));
}
For comparison, if you didn't use closure, the traditional class-based way of solving this problem in C# would be:
public static void Main()
{
var milesToKm = new Converter("km", 1.60936);
var poundsToKg = new Converter("kg", 0.45460);
var farenheitToCelsius = new Converter("degrees C", 0.5556, -32);
Console.WriteLine("{0}", milesToKm.Convert(10) );
Console.WriteLine("{0}", poundsToKg.Convert(2.5) );
Console.WriteLine("{0}", farenheitToCelsius.Convert(98) );
}
class Converter
{
string m_toUnit;
double m_factor;
double m_offset;
public Converter(string toUnit, double factor, double offset = 0)
{
m_toUnit = toUnit;
m_factor = factor;
m_offset = offset;
}
public string Convert(double input)
{
return string.Format("{0:0.##} {1}", (m_offset + input) * m_factor, m_toUnit );
}
}
Wednesday, October 8, 2014
If you are surprised by how "this" works in JavaScript
If you are surprised by how "this" works in JavaScript, then you don't understand the fundamentals of JavaScript method invocation.
Twenty years ago when I was programming in C++ and learned COM, I recall the list of 12-15 of items that detailed the rules on how memory was allocated and freed across COM object method invocations. My peers would study and memorize these rules, and often use them for Interview questions. When I learned the rules, I had a "duh" moment because the COM rules were just a byproduct. There was no need to memorize them because there was only one possible way it could ever work. I used logic rather than memorization.
I see the same thing today with new JavaScript programmers who expect "this" to behave as it does in C++ or C#. Then they run into problems. They learn form their mistake but their approach is that "this" doesn't work right. Here's where it's broken and you have not the exceptions.
"this" in JavaScript is not like irregular verbs in English grammar. There's no exceptions to the rule. The key is to stop thinking that it's like "this" in Java. It's not.
The best explanation of how "this" works to date is Yehuda Katz' article on "Understanding JavaScript Function Invocation and 'this'". http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/ It's an old article, but it's best I've seen.
If you want a simple rule of thumb, it goes like this: 1. When you call a function like method using the syntax obj.method, as in: myObject.myMethod(), then mObject is passed in as a hidden parameter named "this" and can be used from within the myMethod() function. 2. If you call a function without using the method invocation, as in: myFunction(), then referencing "this" inside of the function does something you probably don't want, such as access to the global variable (like window) or it doesn't point to anything. It depends where your code is running. Don't use "this" inside of a function that's not invoked as a method invocation.
Now, if you have an object, myObject, that has to methods, myMethod1() and myMethod2(), if you call myObject.myMethod1(), "this" inside of myMethod1() will be myObject. However, if inside of myMethod1() you call myMethod2() without the object method invocation, i.e. you simply call myMethod2() directly, like you would in Java, C# and C++, then this will not get passed as a hidden parameter.
Your response should be "well duh, of course it wouldn't". But if you think "wtf? why!" then go read Yehuda's article.
[edit] One more point of clarification: In order to use a method invocation syntax, the method has to be a property of the object. That is, the right side of the dot, the method, has to be known by the object. In order for a.b() to work, b has to be in the property list of a. As long as the identifer exists, the syntax will be allowed.
Subscribe to:
Posts (Atom)