Fiction and human achievement

 

For almost 200,000 years, humans were indistinguishable from animals. 

For 5,000 years, we had only achieved the advancements of agriculture and prostitution.  Nothing to be sneezed at for sure, but certainly not the pinnacle of potential.

In 100 years, we went from farming to the Industrial Revolution.  There were a lot of reasons, but note the sudden easy availability of fiction.  I know, I know, correlation doesn’t equal causation, but I can’t help but wonder how much the insurgence of fiction, and how it influenced the play of children, impacted the next generation and the ideas they worked from.  Factories? Space travel?  Computing?

Fast forward to Asimov, Clarke, and the other Science Fiction writers of the 50s.  They pointed our eyes to the stars and our minds to the unimaginable.  Is it a surprise that the generation that grew up reading their books and reenacting it in their play gave us the fathers of the Internet?

Please don’t dismiss child’s play as a waste of time.  Please don’t assume that the introduction of fictional universes into a children’s playtime is an “overdose of media.”  You don’t know what the availability of universes is doing for our children’s fertile minds.  Wouldn’t you rather let them run with it and see what becomes of it, rather than shut it down, afraid of the future it might bring?

Being Object Stingy

 

This is clipped content from my C# Book. 

You can’t construct an object without using a constructor of some sort. If you define your own constructor, C# takes its constructor away. You can combine these two actions to create a class that can only be instantiated locally.

For example, only methods that are defined within the same assembly as BankAccount can create a BankAccount object with the constructor declared internal, as in the bold text in this chunk of code:

// BankAccount -- Simulate a simple bank account.
public class BankAccount
{
    // Bank accounts start at 1000 and increase sequentially.
    private static int _nextAccountNumber = 1000;
    // Maintain the account number and balance.
    private int _accountNumber;
    double _balance;
    internal BankAccount() // Here’s the internal, not public, constructor.
    {
        _accountNumber = ++_nextAccountNumber; 
        _balance = 0;
    } 

    public string GetString()
    {
        return String.Format("#{0} = {1:N}", _accountNumber, _balance);
    }
}

If

IF you can keep your head when all about you
Are losing theirs and blaming it on you,
If you can trust yourself when all men doubt you,
But make allowance for their doubting too;
If you can wait and not be tired by waiting,
Or being lied about, don't deal in lies,
Or being hated, don't give way to hating,
And yet don't look too good, nor talk too wise:

If you can dream - and not make dreams your master;
If you can think - and not make thoughts your aim;
If you can meet with Triumph and Disaster
And treat those two impostors just the same;
If you can bear to hear the truth you've spoken
Twisted by knaves to make a trap for fools,
Or watch the things you gave your life to, broken,
And stoop and build 'em up with worn-out tools:

If you can make one heap of all your winnings
And risk it on one turn of pitch-and-toss,
And lose, and start again at your beginnings
And never breathe a word about your loss;
If you can force your heart and nerve and sinew
To serve your turn long after they are gone,
And so hold on when there is nothing in you
Except the Will which says to them: 'Hold on!'

If you can talk with crowds and keep your virtue,
' Or walk with Kings - nor lose the common touch,
if neither foes nor loving friends can hurt you,
If all men count with you, but none too much;
If you can fill the unforgiving minute
With sixty seconds' worth of distance run,
Yours is the Earth and everything that's in it,
And - which is more - you'll be a Man, my son!


-Kipling

Brew day: “Get fresh with me” American Ale

 

I was lucky to be able to pick almost a pound and a half of Nugget hops at Ohio Hops in Galloway.  Nice folks.  Brian was great – I recommend him for all your Ohio Hop needs!  Anyway, I created a recipe with a single hop to showcase the flavor, and I think it will be a good one:

Get Fresh With Me

Brew Type: Extract Date: 9/5/2010
Style: American IPA Brewer: Bill Sempf
Batch Size: 5.00 gal Assistant Brewer: Adam Sempf
Boil Volume: 4.08 gal Boil Time: 60 min
Equipment: Brew Pot (5 Gallon)


Ingredients
Amount Item Type % or IBU
7.00 lb Extra Light Dry Extract (3.0 SRM) Dry Extract 87.50 %
0.50 lb Caramel/Crystal Malt - 40L (40.0 SRM) Grain 6.25 %
0.50 lb Special Roast (50.0 SRM) Grain 6.25 %
2.00 oz Nugget [13.00 %] (60 min) Hops 68.3 IBU
1.00 oz Nugget [13.00 %] (20 min) Hops 20.7 IBU
1.00 oz Nugget [13.00 %] (10 min) Hops 12.4 IBU
1 Pkgs SafAle English Ale (DCL Yeast #S-04) Yeast-Ale  

Beer Profile
Estimated Original Gravity: 1.062 SG (1.056-1.075 SG) Measured Original Gravity: 1.060 SG
Estimated Final Gravity: 1.016 SG (1.010-1.018 SG) Measured Final Gravity: 0.000 SG
Estimated Color: 8.8 SRM (6.0-15.0 SRM) Color [Color]
Bitterness: 101.4 IBU (40.0-70.0 IBU) Alpha Acid Units: 39.0 AAU
Estimated Alcohol by Volume: 6.02 % (5.50-7.50 %) Actual Alcohol by Volume: 0.00 %
Actual Calories: 0 cal/pint

Please brew it and let me know how it goes.  The hop numbers are for dry, to keep th AA calculations right.  You can substitute fresh whole hops for the dry by multiplying by 5 or so. I used 10, 6 and 4.

Obligatory dinner post: ratatouille from the movie

 

Last night I made ratatouille just like Remy made it in the Disney movie, Ratatouille.  Gabrielle thought of the idea, and got the recipe from Smitten Kitchen, which – if you haven’t been there – has amazing stuff.

IMG_20100831_181651

It turned out incredible, and only took about 20 minutes to put together.  Gabrielle even tweeted about my efforts – funny.  What’s more, it is a very flexible recipe, and I am betting that you could mess around with it a lot.

IMG_20100831_191730

We served it with couscous and chevre, and Adam ate so much I thought I would have to wheel him out with a forklift.  Highly recommended.

Handling fixed width text with Regular Expressions (RegEx)

 

When most developers are faced with a fixed width text file, they reach for the String object.  While this is effective, it isn’t efficient.  .NET doesn’t handle strings that well, and use if SubString is memory intensive.  A better way is to use the RegularExpressions classes in System.Text.RegularExpressions.

A fixed width file is one where the columns are defined by the number of spaces consumed.  For instance, here is a list of the Big 10 (11? 12?), locations, and years founded:

University of Illinois          Champaign, Illinois         1867 
Indiana University              Bloomington, Indiana        1820 
University of Iowa              Iowa City, Iowa             1847
University of Michigan          Ann Arbor, Michigan         1817
Michigan State University       East Lansing, Michigan      1855
University of Minnesota         Minneapolis, Minnesota      1851
Northwestern University         Evanston, Illinois          1851
Ohio State University           Columbus, Ohio              1870
Pennsylvania State University   State College, Pennsylvania 1855
Purdue University               West Lafayette, Indiana     1869
University of Wisconsin–Madison Madison, Wisconsin          1848

The university is 32 characters, the location is 28 characters, and the year is 4 characters.  We can debate up and down the benefits of such a format, but it is what it is, and we often get them from legacy systems.

Instead of using the String.Substring object to get the values out, we can use the Match class in System.Text.Regular expressions.  When you use this class, you get back a Match object, that has a collection of the matches (shocker that) found in the intersection of the expression and the input.

Here is an example program that loads the file, and uses an expression (note that format) to break up the file into a collection, basically an array.  Notice that there isn’t a single String in the project other than the pattern itself.  To run the program, save the above formatted text into a file called “BigTen.txt” on your C drive.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace BigTen
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamReader sr = new StreamReader(@"c:\BigTen.txt");
            string pattern = @"^(?<school>.{32})(?<location>.{28})(?<joined>.{4})$";
            Regex re = new Regex(pattern);
            while (sr.Peek() != -1)
            {
                Match match = re.Match(sr.ReadLine());
                Console.WriteLine(match.Groups["school"].Value.TrimEnd());
                Console.WriteLine(match.Groups["location"].Value.TrimEnd());
                Console.WriteLine(match.Groups["joined"].Value.TrimEnd()+"\n");
            }
            sr.Close();
            Console.ReadLine();
        }
    }
}

Of course, there are downsides to regular expressions.  They are difficult to debug, and the formatting is arcane.  For this, however, they make for an excellent solution, and for formatting of the expression is quite readable.  Only one expression is used, so it is easier than some to debug.  I think it is a good solution to the problem at hand.  Give it a try!

From the archives: Economics

(from "The Renaissance Page", circa 1995)

 

Economics

Another subject that I hold dear. I adore the simplicity of economics, almost as much as its accuracy. The New Classicals have what my dad would call a "Good Point" almost every time they open their mouths.

My latest deals with taxes, and the power of government. (This will be discussed further in Philosophy.) Imagine there are but two types of firms: monopolies and perfect competitors. I know, in reality nobody is either; but, if you filter and carefully select your inputs, you can compare firms like this. If the State (my word for the government of the US) needs control of a firm, its easiest recourse is to tax. But there is more to it than that.

In the case of a monopoly, let's take OPEC and the gasoline industry, the government saw an opportunity to fund the Department of Transportation. The more a consumer drives, the more money that driver should give to the DOT. Therefore, a per unit tax has been imposed on gas. You see, a firm produces where its marginal cost equals its marginal revenue. In a monopoly, the amount the average cost exceeds the marginal cost is the excess profits of the firm. If a per unit tax (a la the gas tax) is imposed on gasoline the average cost will be affected along with the marginal cost. Less gas will be desired, at a higher price, but the firm will suffer no loss of profits. Thus, the government has gotten the tax money from the consumers, the consumers don't know, and the firms are not hurt.

Now let's take a monopoly such as the caviar import trade. The government would really like to see it shut down. They know that, as a luxury, caviar has a very elastic demand curve. Therefore, a lump sum tax that effects average cost, but nothing else, will cut heavily into the firm's profits.

This is just something to think about. Run the curves (Basic Micro should get you through it) and see what you think then drop me a line. Remember - the more you think, the better off everyone is.

FIX: Classes converted from VS2008 to VS2010 appear as Components

 

I don’t remember how this happens (I was told at one point) but sometimes, when you convert a project from VS2008 to VS2010 some classes will appear to be components.  This is annoying, because when you double click to open them, they try to load in the designer, which doesn’t work at all.

To fix this:

  1. Open your Visual Studio Project file in Notepad.  It should be .csproj or .vbproj.  You’ll have to close Visual Studio first.
  2. Locate the reference to the file in question.  It will look like this:
  3. <Compile Include="Connection.cs">
    <SubType>Component</SubType>
    </Compile>
  4. Delete the Component subtype, so the line looks like this:
  5. <Compile Include="Connection.cs" />
  6. Rinse and repeat for each file affected.

Doing Regular Old Database Programming (RODP) with LINQ to Entities

 

ICC has me on a project where I am essentially writing a service backend to a video-enabled LMS of sorts.  I need to track interactions with a set of videos, and present completion percentages by user, video or category.

I am storing every interaction wit hthe video for every user, with a start second and a stop second.  So if you log in and watch a video, and start at Seconds 100 and stop at Seconds 240, I record that.  Since the front end software won’t let you go past where you last stopped, the highest Stopped figure for a given video and user is the total watched minutes – even if they replayed something.

To do this, I created a public PercentComplete method for each service, and then created private TotalSeconds and SecondsWatched methods for each as well.  Here is the common PercentComplete method, that calls the two private methods.

public static double PercentComplete(Guid userId, int videoId)
{
double result = 0.0;
int elapsed = WatchedSeconds(userId, videoId);
int total = TotalAvailableSeconds(videoId);
try
{
result = Math.Round(Convert.ToDouble(elapsed) / Convert.ToDouble(total), 2);
}
catch (DivideByZeroException)
{
result = 0;
}
return result;
}

To calculate TotalSeconds, I just needed to add up all of the lengths for all of the videos.  That was easy enough.  The length is stored in the database, and available to the entity model.

private static int TotalAvailableSeconds(int videoId)
{
VirtualVideoEntities context = new VirtualVideoEntities();
var videoData = context.Videos.FirstOrDefault(c => c.VideoId == videoId);
return Convert.ToInt32(videoData.Length);
}

Calculating the watched seconds was another matter, and would have to be custom to each entity.  Video seemed the easiest – what percent of a given video has a given user watched?  I can just get the Stopped value from all of the Interactions in the database, then get Max, right?

private static int WatchedSeconds(Guid userId, int videoId)
{
using (VirtualVideoEntities context = new VirtualVideoEntities())
{
var watchedSeconds = from c in context.Interactions
where c.User == userId && c.Video == videoId
select c.Stopped;
int sumSeconds = watchedSeconds.Max().GetValueOrDefault();
return sumSeconds;
}
}

Jammin.  Now, how about for a User?  Now I need to get all of the max values for all of the videos and sum them.  That’s harder, but it can be done with a GroupBy (hat tip to @jimwooley and @craigstuntz).

private static int WatchedSeconds(Guid userId)
{
using (VirtualVideoEntities context = new VirtualVideoEntities())
{
var maxWatchedSeconds = from c in context.Interactions
where c.User == userId && c.Stopped != null
group c by c.Video into g
select new {Video = g.Key, MaxStopped =
(from t2 in g select t2.Stopped).Max()};
int sumSeconds = maxWatchedSeconds.Sum(m => m.MaxStopped).GetValueOrDefault();
return sumSeconds;
}
}

Right on.  Now, categories.  Uh, how am I going to do that?  In SQL, I would use a JOIN on Category with the VideoId, but I’m not USING SQL.  Seems weird to use a Join in LINQ but it does have one … hmm.  Not sure what to do here.

Then I though – wait a minute.  I remember someone saying “If you have to use a Join in L2E, your entity model isn’t right.  So the context.Video should have a Category collection, right?  I tried to add a conditional of c.Category but after the c I pressed dot … and got nothing.  Bummer. Makes sense though.  Interactions don’t have categories.

Then I deleted the dot, and intellisense for c came up.  There was ‘Videos.’  Boom.  I selected Videos, then dot, then there was Category.  Amazing.

private static int WatchedSeconds(Guid userId, int categoryId)
{
VirtualVideoEntities context = new VirtualVideoEntities();
var maxWatchedSeconds = from c in context.Interactions
where c.User == userId && c.Videos.Category == categoryId
group c by c.Videos into g
select new { Video = g.Key, MaxStopped =
(from t2 in g select t2.Stopped).Max() };
int sumSeconds = maxWatchedSeconds.Sum(m => m.MaxStopped).GetValueOrDefault();
return sumSeconds;
}

I am sold on Linq.  I still don’t think it makes a good ORM, like Linq2SQL tries to be, but I am totally sold on using it for object manipulation when a domain model is present.  I won’t use anything else, unless I have to.

Smartphone enhanced, large scale live action role playing

 

It all started with a dream – literally.

The other night I had this weird ass dream.  I was playing a live action game (sorta like Assassin) with a GPS enabled smartphone as my guide – in this case, my Nexus One.   It seemed to go like this:

When the game was starting, the application I had purchased and downloaded notified me.  From then on, I had an assassination target, and someone had me as a target.  Additionally, there were teams – but you didn’t know who was on your team.  In fact, I hadn’t met any of the people I was playing with.

The application gave me salient information about the target, and would notify me when I was near a team member.  It was up to me to track down the target on my own and neutralize them – the app didn’t have their location information.  It did, however, have location info on my team members.  No one had a team member as a target – those people were allowed to work together if they could find each other.

This led to a wide assortment of weirdness in my dream, including finding Gabrielle (who wasn’t my wife in the dream) to be one of my team members, and large amounts of urban exploration in what was apparently a post-apocalyptic Downtown Columbus.

What’s more interesting to me is that the idea is totally feasible.  Using technology available right now, one could write an application that lets a person register for the live action game.  The app could be terminate and stay resident in order to provide notifications, or the central server could text users with broadcast information.

Once the game is started and everyone is online, you would log into the app, and your target information would be available from the application.  Research tools might be built in.  Mapping with waypoints is essential.

Most interesting is the peer to peer sharing of GPS data.  If you got near a team member, the application would let you know – perhaps even using bluetooth as a closer metric than the GPS.  Once thus notified, observation and hensojutsu would be your guide, and you may have a valuable partner in the game, if you play the cards right.

This could be played in a company, or a group (like a school) or a city, or even nationally or globally is money no object.  What’s more, it shouldn’t be that tough to write. I don’t have the chops to do it on any mobile platform as things stand right now, but it would probably have to be built for Android, iPhone and Windows Mobile 7.  There would be pretty strict requirements for the hardware, but I bet you could make some coin if you set it up, and it would be a hell of a lot of fun.

If someone does it, invite me.  I might not build the app, but I sure will play.

Bill Sempf

Husband. Father. Pentester. Secure software composer. Brewer. Lockpicker. Ninja. Insurrectionist. Lumberjack. All words that have been used to describe me recently. I help people write more secure software.

PageList

profile for Bill Sempf on Stack Exchange, a network of free, community-driven Q&A sites

MonthList