All posts by Steve Rives

The Raspberry Pi Diaries

Day 1:
Pi Day. 3.14 (Friday), 2014. I got my Raspberry Pi from William (a present!). CanaKit Ultimate Starter Kit. It also came with a real pi. Ate pi.

Unpacked kit and examined. Talked with engineer at work about MQTT application; remote monitor to talk to our company’s web server.

Day 4:
Forgot my HDMI-VGA converter at home.

Day 5:
It sits on my desk.

  1. My Raspberry Pi came with NOOB (New Out of Box)
  2. Hook up mouse, kb and monitor (I used an HDMI/VGA convertor)
  3. Install Raspbian (install with user: pi, pw: raspberry)
  4. Note that the “Debian” release is our Raspbian. You may need to remember this.

Alive.

Note: The Pi comes with two accounts (pi and root)
I set the passwords for my accounts to “admin” — easy for me to remember.

sudo passwd root

Day 6:
Want to run C# code on my computer, lights out — will use the Pi without a directly connected keyboard, monitor or mouse.
Keep pi.txt of accounts on Windows dt.

  1. Get the IP address of Raspberry Pi
  2. ifconfig
    This step is NOT needed. Just use the default hostname: raspberrypi

  3. Windows Side: SSH/PuTTY reader
  4. Get PuTTY here, http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html
    You can use PuTTY/SSH to attach and do everything from here on out.

  5. Install mono
  6. sudo apt-get install mono-complete

  7. Install tightvncserver and setup a Virtual Networking Computer session
  8. sudo apt-get install tightvncserver
    sudo vncserver :1

  9. If you ever want to change your password
  10. vncpasswd

  11. Use VNC viewr to remote into the machine
  12. www.realvnc.com
    Connect to the IP, say raspberrypi:1 (with the :1)

  13. Install FTP Server
  14. sudo apt-get install vsftpd

  15. Edit FTP config file (with VNC Viewer, LeafPad)
  16. /etc/vsftpd.conf

    anonymous_enable=NO
    Ascii_upload_enable=YES
    Ascii_download_enable=YES
    local_enable=YES
    write_enable=YES
    local_umask=022
    chroot_local_user=YES
    user_sub_token=pi
    local_root=/home/pi/ftp

    sudo service vsftpd restart

    mkdir /home/pi/ftp
    mkdir /home/pi/ftp/files
    chmod a+w /home/pi/ftp
    (note: later I see this is not going to work, see Day 8, below)

    Success. Ftp worked.

  17. Build Visual Studio C# app.
  18. Wrote HelloMono.exe in Visual Studio (simple command line app).
    FTP copied to the Pi.
    Ran it.

Success: Ran C# program on Raspberry Pi.

Day 7:
Lost IP from night before, use hostname, raspberrypi to access the device. Will code-name this project Aristotle, so here is chance to change the name of The Pi.

  1. Change name of The Pi from raspberry to aristotle
  2. edit /etc/hosts, change 127.0.0.1 to aristotle
    edit /etc/hostname, change the name to aristotle
    sudo /etc/init.d/hostname.sh

    sudo reboot
    (it takes a bit of time for the name to propagate)

  3. To run any C# EXE without specifying “mono”
  4. chmod +x HelloMono.exe
    Now I can simply run ./HelloMon.exe in place. Works.

  5. Fix FTP
  6. I suddenly can’t log on to FTP.
    This fixes it: chmod a-w /home/pi/ftp
    If I have it set to a+w, I can’t log in.
    If I have it set to a-w, I can’t upload.
    Solution: create another directory under ftp
    mkdir /home/pi/ftp/upload
    chmod a+w /home/pi/ftp/upload
    Now I can upload to this directory.

  7. Forget FTP. Switch to WinSCP.
  8. Installed Wiccp, http://winscp.net/eng/index.php
    WHY would I ever use FTP now?!?!

  9. Linked in C# DLL
  10. Yes, I can also run a DLL from Mono.
    In particular, one of my main generic protocol libraries.
    Major step forward. Now I can begin the linkage to our web server.

  11. Attach Aristotle to the experimenter board.
  12. Ribbon cable from board with red strip (pin one).
    Here is the pintout: http://www.hobbytronics.co.uk/raspberry-pi-gpio-pinout

Ready to read and write pins (General purpose I/O): GPIO

  1. Reading the pins in C#
  2. Just use https://github.com/cypherkey/RaspberryPi.Net
    Built into project. I loaded everything into Visual Studio 2012 at this point.
    Not working…

  3. Get GPIO library
  4. Running on Aristotle, the program I build dies. It does not have the binary.

    http://www.airspayce.com/mikem/bcm2835/

    Get the latest TAR file, and copy it to Aristotle.
    The run the following make commands (where .xx is 36 in my case):

    tar zxvf bcm2835-1.xx.tar.gz
    cd bcm2835-1.xx
    ./configure
    make
    sudo make check
    sudo make install
    cd src
    cc -shared bcm2835.o -o libbcm2835.so
    copy libbcm2835.so to same directory as my EXE and DLLs

    Run the project, still problems… Linux code (bcm2835) failing.

Login Reminder:
If I Putty
hostname: aristotle
user: pi
pw: admin

Once on, start the vncserver
sudo vncserver :1
pw: raspberrypi (read only)
or
pw: elecsys (full rihgts)

From the Windows side, enter into VNCView
aristotle:1

Day 8:
When I left, Aristotle was still not loading the .NET GPIO library properly.
To fix, added to .NET library: bcm2835_set_debug(1);

static GPIOMem() {
bcm2835_set_debug(1);

THIS WORKS!
(weekend now… hope to have more on Monday).

Day 11:
Wired up experimental board. I have pin 17 wired to an LED with a 180 Ohm resistor.
Changed C# program to turn on LED. Fail.
Is the wiring bad, or software, or the board interface?

  1. Download and install validation of GPIO
  2. cd
    git clone git://git.drogon.net/wiringPi
    cd wiringPi
    git pull origin
    ./build

  3. Manipulate the LED on pin 17
  4. gpio mode 17 out
    gpio write 17 1
    gpio write 17 0

    Still failing.

  5. Ah, a numbering problem.
  6. run:
    gpio readall

    +----------+-Rev2-+------+--------+------+-------+
    | wiringPi | GPIO | Phys | Name   | Mode | Value |
    +----------+------+------+--------+------+-------+
    |      0   |  17  |  11  | GPIO 0 | IN   | Low   |
    |      1   |  18  |  12  | GPIO 1 | IN   | Low   |
    |      2   |  27  |  13  | GPIO 2 | IN   | Low   |
    |      3   |  22  |  15  | GPIO 3 | IN   | Low   |
    |      4   |  23  |  16  | GPIO 4 | IN   | Low   |
    |      5   |  24  |  18  | GPIO 5 | IN   | Low   |
    |      6   |  25  |  22  | GPIO 6 | IN   | Low   |
    |      7   |   4  |   7  | GPIO 7 | IN   | Low   |
    |      8   |   2  |   3  | SDA    | OUT  | Low   |
    |      9   |   3  |   5  | SCL    | IN   | High  |
    |     10   |   8  |  24  | CE0    | IN   | Low   |
    |     11   |   7  |  26  | CE1    | IN   | Low   |
    |     12   |  10  |  19  | MOSI   | IN   | Low   |
    |     13   |   9  |  21  | MISO   | IN   | Low   |
    |     14   |  11  |  23  | SCLK   | IN   | Low   |
    |     15   |  14  |   8  | TxD    | ALT0 | High  |
    |     16   |  15  |  10  | RxD    | ALT0 | High  |
    |     17   |  28  |   3  | GPIO 8 | OUT  | Low   |
    |     18   |  29  |   4  | GPIO 9 | IN   | Low   |
    |     19   |  30  |   5  | GPIO10 | IN   | Low   |
    |     20   |  31  |   6  | GPIO11 | IN   | Low   |
    +----------+------+------+--------+------+-------+
    

    The pin that I think is 17 (P17 on my board adapter), is really the 0th GPIO entry.

  7. Manipulate the LED on pin 17 using 0th address
  8. gpio mode 0 out
    gpio write 0 1
    gpio write 0 0

    Works: this manipulates P17!

  9. Run my C# program, sudo ./Aristotle.exe, as sudo (must use sudo)… Works!
  10. using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using ScadaNetSite.Shared;
    using Messages.Models;
    using RaspberryPiDotNet;
    
    namespace Aristotle
    {
        class Aristotle
        {       
            static void Main(string[] args)
            {
                Console.WriteLine("Rives Pi, Aristotle");
                
                int pin = 0;
                int value = 0;
                if (args.Length != 2)
                    Console.WriteLine("Usage: Aristotle <pin> <0|1>");
                else
                {
                    if (int.TryParse(args[1], out value))
                    {
                        bool bVal = false;
                        if (value == 1)
                            bVal = true;
                        if (int.TryParse(args[0], out pin))
                        {
                            GPIOPins gPin = (GPIOPins)pin;
                            Console.WriteLine("Writing to pin " + pin + " == " + gPin.ToString());
                            GPIOMem led = new GPIOMem(gPin, GPIODirection.Out);
    
                            led.Write(bVal);
                        }
                        else
                            Console.WriteLine("Invalid argument. Pass in an integer to specify a pin");
                    }
                    else
                        Console.WriteLine("Invalid argument. Pass in an integer to apply to the pin (1 or 0)");
                }
                
            }
        }
    }
    
    

Day 12:
Added switch. Straightened out pins to get it to sit on board well. New version of Aristotle.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ScadaNetSite.Shared;
using Messages.Models;
using RaspberryPiDotNet;

namespace Aristotle
{
    class Aristotle
    {       
        static void Main(string[] args)
        {
            Console.WriteLine("Raspberry Pi, Aristotle");
            
            int ledPin = 17;
            int ioSwitch = 22; // Pin 22 is normally high
            int milliseconds = 5000; // seconds
            int value = 0;
            if (args.Length == 3)
            {
                if (int.TryParse(args[1], out ioSwitch))
                {
                    if (int.TryParse(args[0], out ledPin))
                    {
                        if (int.TryParse(args[2], out milliseconds))
                        {
                            GPIOPins sPin = (GPIOPins)ioSwitch;
                            GPIOPins oPin = (GPIOPins)ledPin;

                            Console.WriteLine("Watching switch on pin " + ioSwitch + " == " + sPin.ToString());
                            Console.WriteLine("Will light up LED pin " + ledPin + " == " + oPin.ToString());
                            GPIOMem led = new GPIOMem(oPin, GPIODirection.Out);
                            GPIOMem sw = new GPIOMem(sPin, GPIODirection.Out);
                            while (true)
                            {
                                if (sw.Read())
                                    led.Write(false);
                                else
                                    led.Write(true);
                                System.Threading.Thread.Sleep(milliseconds);
                            }
                        }
                        else
                            Console.WriteLine("Invalid miliseconds specified.");
                    }
                    else
                        Console.WriteLine("Invalid LED pin specified.");
                }
                else
                    Console.WriteLine("Invalid Switch pin specified.");
            }
            else if (args.Length == 2)
            {
                if (int.TryParse(args[1], out value))
                {
                    bool bVal = false;
                    if (value == 1)
                        bVal = true;
                    if (int.TryParse(args[0], out ledPin))
                    {
                        NamedBits nb = new NamedBits(32);
                        nb.nameBit(0, 32, "DATETIME");
                        nb.UtcNowSeconds("DATETIME");
                        DateTime dt;
                        nb.GetDateTimeFromSeconds("DATETIME", out dt);
                        Console.WriteLine(nb["DATETIME"] + " == " + dt);
                        Console.WriteLine(nb.ToString("DECODE"));

                        GPIOPins gPin = (GPIOPins)ledPin;
                        Console.WriteLine("Writing to pin " + ledPin + " == " + gPin.ToString());
                        GPIOMem led = new GPIOMem(gPin, GPIODirection.Out);

                        led.Write(bVal);
                    }
                    else
                        Console.WriteLine("Invalid argument. Pass in an integer to specify a pin");
                }
                else
                    Console.WriteLine("Invalid argument. Pass in an integer to apply to the pin (1 or 0)");
            }
            else
            {
                Console.WriteLine("Usage: Aristotle <LED pin> <0|1>");
                Console.WriteLine("       Turn on or off the given pin.");
                Console.WriteLine("Usage: Aristotle <LED pin> <Switch pin> <sleep miliseconds>");
                Console.WriteLine("       When the given Switch is pressed, LED lights");
                Console.WriteLine("       We wait so many sleep seconds between checking the switch.");
                Console.WriteLine("       E.g., sudo ./Aristotle 17 22 5");
            }
            
        }
    }
}

In my case: sudo ./Aristotle.exe 17 22 1000

Where pin 17 is an LED on my board, and pin 22 is a switch.

Day 31
April 15th, 2014.
It’s been a while since I worked on Aristotle.
Added JSON deserialize code to Aristotle.cs for a large number of database tables.
Aristotle is now a protocol droid.

Day 32
Added TCP code to Aristotle.cs
Now configure it to run off the wireless network

  1. Configure WiFi
  2. Instructions are here: http://www.maketecheasier.com/setup-wifi-on-raspberry-pi/
    I used my VNC client to attach, and ran wpa_gui (WiFi Config utility).

  3. Putty to device and start VNC
  4. In my case:
    hostname: aristotle
    user: pi
    pw: admin
    sudo vncserver :1
    From the Windows side, enter into VNCView
    aristotle:1
    pw: elecsys

2 + 2 = 4 is not a proof for moral absolutes.

Because of the charged nature of this subject, I want to state up front that I think of myself as more conservative than Mark Levin and Rush Limbaugh. So, please don’t bail on this article yet, as I am not going to argue that 2 + 2 = 5, as to support an Orwellian view of reality (see the book 1984). I am not going to argue that 2 + 2 = 4 is a bendy idea; nor am I going to call it a lie. I have no liberal agenda (quite the opposite). To get to my conclusion, I know that some things I am about to write will make conservatives question my motives. But if you can hang on to the end, and suspend judgement till you get to the final paragraph, this article will truly delight your mind. The payoff is worth it, and by loosing one logical idea to roam about in your brain, you will experience a powerful chain reaction of well-reasoned thoughts. The payoff is worth it…

Despite what we teach kids in elementary school, there are many maths. But I am not saying this because I am an advocate of liberal education in America (far from it!).

Mathematics is many flowering and mushrooming inventions, expanding in many directions out of the creative minds of many humans. Each one is useful for its own problem domain. Yet, it would be a mistake to imagine these inventions as being handed down from heaven as divine revelation.

That humans invent math is itself offensive to religious people. So, in case you are religious, let me offer a mild proof. First, notice that people do invent things. Secondly, we don’t credit God with the invention of what we invent — for example, the car. This is not because we are atheists, but because God made man capable of inventing. Third, notice that men invent new objects used for all sorts of harm and wickedness that God would not invent (I will let you imagine such objects). In this article, when I speak of math as invention, the religious will immediately protest, but if they consider that God made humans as inventors, then I cannot be understood as being irreligious.

Mathematical systems are invented languages used to describe various human experiences. Again, the religious will protest. They may grant that humans can invent wicked objects. Religious people are even fine with humans inventing fake languages (like Klingon), but they never think of math as an invented language (and certainly not credited to men). But men do invent languages that work (again, I point to the silly example of Klingon, which is a modern made-up language that works as a closed system with its own invented grammar — i.e., its own logic).

There is no attack on piety in saying that mathematical systems are invented languages. Most of those languages work accurately and precisely within the closed systems for which they were intended. I am not saying these symbolic languages fail to truly describe what they describe, nor are their descriptions dubious. Rather, I am saying that each one works within the closed system where it is meant to be used. However, there is a fallacy afoot (the fallacy called equivocation) which extracts the propositions of certain of those closed contextual systems, and presses them as proof or samples of the largest context of all: the absolute.

I have in mind the statement, “2 + 2 = 4″, and how it is alternatively used as a proof of ultimate reality or as proof of divine reality. I believe in the ultimate and final reality of God (the only creator, the Trinity), but not because 2 + 2 = 4. So I am not denying the existence of God, nor arguing for relative truth. Not at all. My interest is that the statement, “2 + 2 = 4″ is often used as the irrefutable example of a universal absolute.

Consider a pretend conversation between a theist (someone who believes in a divine creator), and a moral relativist:

The theist: “God exists.”
The moral relativist: “How do you know.”
The theist: “2 + 2 = 4.”

Okay, the discussions are never that silly, but very often, 2 + 2 = 4 shows up in the proofs and appeals of the theist (I am not trying to mock any religious people, I just want to get to the point). The religious types may boldly and loudly assert that 2 + 2 = 4, as if that assertion automatically belongs to the set of absolutes to which their deity also belongs, or as a statement their deity delivered inscribed on stone (something they would never say about Klingon). Here, I want to examine that religious claim (no matter if the claim is explicitly or implicitly made).

Again, I am not denying that there is a God — may it never be! Rather, we must scrutinize the appeal to “2 + 2 = 4″, as it is often stated as some kind of irrefutable triumph of human thought and inquiry that has application in all realms of discourse (used as an axiom in theological proofs). My humble desire is to suggest that even “2 + 2 = 4″ has a limited context and application (even though those limits are quite broad), and is not to be ranked higher than experience, reason and context allow.

If anyone claims that “2 + 2 = 4″ has the force of an axiom useful for theological proof, they must establish what they mean by “2″ and “+” and “=” and “4″. These are words. These are words that may or may not have the same meaning when switching domains of discourse. Words have context. I am not denying that words work (they do!). I am not denying that words have real fixed meanings (they do!). I am saying that the meaning is context driven as much as it is dictionary driven. Both a context and a dictionary are needed (consider, for example, how the word, ‘draft’ has many contextual meanings as stated in a dictionary).

It is legitimate to say that in any conversation, we must establish what is meant by “2″ and “plus” and “equals” and “4″. We can’t move from a number system context to a theological one without naming the context switch (unless we want to be guilty of term switching — i.e., equivocating). So, let me circle back and restate the thesis in case I am less than plain:

There is a nearly universal, unquestioned and unfounded acceptance that 2 + 2 = 4 belongs to a super-context. It is a statement taken as one which defies any challenge from any lesser contexts. It is taken as the Super-Truth of all facts irrespective of any context. Since we were wee little ones, our parents have told us that 1 + 1 = 2, and 2 + 2 = 4. These rank among the cherished anchors of our childhood, reinforced in our education, and confirmed by our experience. We are free, however, to logically (and experientially!) disagree. Indeed, I wish to show that “2 + 2 = 4″ is not logically appropriate to all experiences and contexts.

I have done some work in the field of mathematics, and it is in that context that I developed a few thoughts about the matter.

2 + 2 = 4 is a powerful and useful philosophical construct that is not rooted in absolute truth, nor does it cross all boundaries, and ultimately is a creative expression of human experience that is accurate to its own context (that is, in its right context, it is reliable and fixed).

Now let me try to back that up. I will start with an apparent given. Namely, let’s assume that 1 + 1 = 2 is always true in all contexts of discourse. If 1 + 1 = 2, then by the law of non-contradiction 1 + 1 = 1 is false. However, I propose that 1 + 1 = 1 is true in this context:

1 + 1 = 1 inasmuch as 1 Fox + 1 Chicken = 1 satisfied Fox

It does not take years of mathematical study to figure this out. Even if we add things of the same type, 1 Rabbit + 1 Rabbit, we may get 5 Rabbits under the experience of multiplication (which is not the same as multiplication on the natural numbers, where 1 * 1 = 1, as in nature the idea of multiplication of the species from a pair is more like addition). In the case that 1 Rabbit + 1 Rabbit = 5 Rabbits, “+” is a term which may not mean what we think it means if we don’t account for the context. Addition is a verb or adverb, it is not a reality of its own. Likewise, numbers do not exist in reality, but are conceptual terms that have meaning according to the topic. I am not the first to observe this. Someone speaking of love and life has poetically said:

“I used to think the sum of one and one was two”, There Must be Something More, Theme song from Charlotte’s Web.

In all of this, we discover that “1″ is an adjective to describe something. “1″ is what it is, depending on what we are talking about. It is 1 Fox or 1 Chicken, and the + means adding the two together according to their kind. This way of describing reality is mathematical (within the closed system wherein the math is applied), but it is not the same math as what we find in the rulebook used in Algebra I courses (which is its own system).

And herein we discover that there is not one math, but many maths. For example, there are many “geometries.” There is Euclidean Geometry and non-Euclidean Geometry. I did not make this up, it is the way of things in the college curriculum. This is not an argument for philosophical or moral relativism. I am not pitting the different systems of math against each other, Euclidean vs. non-Euclidean (as if I have found some way to say that 2 + 2 = 4 is never true nor false)! If you think that is my argument here, you are changing subjects in your own head. I am merely arguing for the concept of Context, and against the fallacy Equivocation. Nothing I am saying here supports ethical relativism unless my words are wrenched out of context.

I can argue as I have (in part) because numbers are not abstract realities that have independent and real existence. You cannot go and get “5″ for me. “5″ is not a reality in and of itself; it is a description, and numbers on paper are descriptions of reality. They are adjectives. They are not real-nouns. I thus reject Plato’s Ideals, as there is not a thing called “5″ to which all sets of “5″ conform to.

An analogy may help here. Think of a musician and all those funny markings on paper they read as they play the piano. The music notation on the sheet is not the music, but the sound coming from the piano is the music. Likewise, math is not simply what happens on paper as we manipulate symbols — not any more than we would confuse sound with the dots and lines on the piano player’s ruled paper.

“2 + 2 = 4″ has more to do with our experience of a certain event in a certain context than it has to do with some ideal about an absolute statement that applies to all subject areas. 2 + 2 = 4 is a way we can describe certain ideas within a certain system (and in the right system, the integers, it is invariable and true).

Any particular mathematical system is not representative of the final absolute truth of all other domains of discourse, and is thus contingent. 2 + 2 is 4 on the integers. In fact (if we wanted) we could invent another system of integer rules where we don’t allow this (for more on this, I direct the interested reader to the study of Abstract Algebra and ring theory, and more tangentially, to modulus arithmetic).

I am not trying to pull a fast-one over you. I am saying that when you were a kid in grade school, we were speaking like children about one subset of language (arithmetic). But we are not children anymore, so we can expand our understanding of words to see that they have meaning according to their context. Words work. And they work accurately and precisely as to their context. I am not arguing against 2 + 2 = 4, and I don’t know of any logical system where 2 + 2 = 5 on the naturals, wholes, or integers (etc.).

I tell all of my math students that the rules of math are the inventions of people to describe systems, and we are free to make new rules — and in making new rules we may invent a clever and useful system of thought. Mathematicians are constantly inventing new ideas and rules. Math is not a set science because there are many domains of discourse and many humans discoursing. The high-school idea of math needs to give way to this more robust grown-up view of maths as being languages.

Mathematicians often make up new ways of thinking (to solve problems or to invent new thoughts). This kind of creativity happens all the time. For example, there was Newtonian Physics and then there came Einsteinian Physics. The best we can do is say that these “physics” conform to our current or observed experiences, and another Physics may be invented to describe reality. Newton is not eternally right across all domains of discourse, nor were his laws. There was a time when energy (which he said can’t be created or destroyed) was created — if we deny this, then we are forced to postulate that energy is eternal (whatever that would mean). Another way to say this may be less controversial: We have no sure facts to prove that Newton’s laws have always worked, and now Einstein tells us that things are different anyway.

Take another example of “infinity” as it is used in Algebra I or in math books. We talk about infinity as if it has a given meaning on the integer numbers (namely, counting on and on forever). But then Cantor came along and invented different kinds of infinities. It turns out that “infinity” is not the thing we always thought it was. There are countable and uncountable infinities now, thanks to Cantor’s invention. See, Math happens! There are maths, not math.

I am writing this, in part, to help take away any false assurance that math is some pure and absolute discovery that sits alongside divinity. I would like to extend my thesis to say that maths are invented, not discovered (for example, Russell gets credit for his set theory).

I like mathematical languages. But I don’t kid myself to imagine that they cross domains and take the place of divinity (contra those who claim that mathematics is the one source of pure absolutes). Mathematical language is not inherently false (I have not argued that), but neither is the language of the integers appropriate to all contexts.

If a person wants to dethrone God and install math in His place, they cannot claim that they have math as ultimate truth. Math does not rise to the level of deity (unless you want to invent a deity). To reject Jesus while claiming to be mathematically sure about math and science is to deify math. Secular mathematicians are known to do this. I encourage them, if they reject Christ, do not do it because you have found a universal truth in math. You have not. “2 + 2 = 4″ is not the final hook you can hang your hat on in all contexts.

Russell’s Paradox for a Twitter Age (Set Theory for Tweeters)

Bertrand Russell was a philosopher and mathematician, famous for many things, not least being the paradox named after him. To illustrate Russell’s Paradox for a Twitter age, I thought it appropriate to restate it in terms of an actual Tweet (given below). In case you are unfamiliar with Twitter, it is a collection of accounts that users create. Each account can follow other accounts; though an account can’t follow itself (it can’t self-follow), as that doesn’t make much sense. But consider this:

If Twitter let us self-follow, and I followed only and every non-self-following account, would I follow myself?

Do you see the paradox? Consider:

* If I did follow myself, then I would violate the rule: follow ONLY non-self-following accounts.
* If I did not follow myself, I would violate the rule: follow EVERY non-self-following account.

You see, if the rules of the Tweet are strictly followed, a darned-if-you-do, darned-if-you-don’t situation results.

Russell expressed this paradox in reference to Sets. In my tweet version, Twitter accounts are conceived of as Sets. These Sets contain other Sets (where follow is the metaphor of containment, so that Accounts Following Accounts is the analogical to Sets Containing Sets). That is, one Set contains other Sets, with the elements of any Set being many things (including the “followed by” and “following” lists, and also actual “tweets”).

And, so, here you have it, Russell’s Paradox for a Twitter Age. He came up with this paradox to reveal a weakness in a certain system of thought–with a view to implementing a system of his own devoid of such a paradox.

The Halving Algorithm and the Guessing Game for the TI-83/TI-84

The first task for each student is to write a program where the computer thinks of a number, and the student gets to guess the number (and the program says if the guess is too high, too low, or just right). The program keeps soliciting the user for a guess until the correct answer has been provided. On the TI-83, to have the computer pick a number from 1 to 1000, you use the random number generator under Math->Prb->randInt. The following line of code is how the Ti-83 picks a number from 1 to 1000, and stores it into the variable A:

randInt(1,1000) -> A

I will leave the rest of the program writing to you. You’ll use Lbl, if, Input, math tests (>, <) and Disp.

I originally got the idea for a number guessing program when I was 12. I got it from the book, Basic Computer Games. This book made quite an impression upon me, so it is a pleasure to pass along a snippet (click on the image below to see page 75):

guess

The second task for the student is to think of the best way to guess numbers. For example, consider that I am thinking of a number from 1 to 1000, and I ask you to guess that number (and I will tell you if you are too high or too low). Two bad ways to go about guessing would be to begin at one and count up to 1000 till you got it, or to begin and 1000 and count down. There must be a better way. Find that way. And then come up with a statement that will tell me the most number of guesses it would take for a person to figure out the secret number.

Do the same thing as if the number to be guessed is between 1 and 10.

Then do it again for a number between 1 and 100. Then 1 and 1000. Can you find a general pattern that will tell you the maximum number of guesses it would take to find the hidden number for any range?

Bonus Assignment: This following line of thinking was not covered in our last class. But consider what it would be like to play the game of Guess in reverse… bear with me, and I’ll try to explain. Imagine that instead of randomly picking a number, the computer randomly picks “too high” or “too low” at each guess. That is, the computer itself does not know the secret number, but discovers it with the guesser. Can any number be written as a sequence of “too high” and “too low” statements? Don’t worry if this Bonus Assignment makes no sense. But if you follow the gist, have fun thinking about it. And welcome to the world of open-ended questions.

Encrypting My Thoughts by Encrypting Twitter Messages

Twitter has become a kind of extension to my brain. And now, like a brain, my Twitter messages are only accessible to me. But it didn’t start this way.

In the beginning, what I wrote on Twitter was a simple index into my latest thoughts. To the outside observer (and especially to the unsympathetic reader) the appearance of my thoughts appeared thoughtless. I was accused of thoughtless thinking. But I imagine that thinking, for many of us, would externally appear to be an undirected or thoughtless activity, and maybe my thinking is. Regardless, thinking is a mostly private affair, and when it was opened up to the world around me, it came off as a collection of unrelated and even crass ciphers. As I began to spread my thoughts, the offense spread.

I never thought that my Twitter account was just for me. But I acted like it was, and so my thoughts were escaping my brain and making it into the wild, but I was thinking like they were still in my head.

My rational was simple. I was writing sentences for the benefit of wanting to recall them later — they were for me to remember (and I still want that Twitter-benefit). But now I am using Twitter as my memories according to this new dictum: Not everything I want to remember do I want to share.

Twitter has evolved for me. First it was a noteworthy little place on the web, and I had an account. Then I tied it to my cell phone and I could easily send messages and track ideas. Then I tied it to my Facebook and I could update my Facebook from my cell phone. I had lots of friends and social media was good to me. But then I wrote more things. And then Twitter was not so good. Soon, my social media was antisocial. So I deleted my Facebook, kicked everyone off of my Twitter account, pulled everything back, and made all my ideas hidden and private.

My Twitter-Cards are now held close; every madly-scribbled thought is a note to me, or a memo to myself. These sentences live in my auxiliary storage–Twitter is an extension of my memory. But Twitter is different than normal memories; I can search these auxiliary sentences and go back to my thoughts and deliberately pick up where I left off in my thinking. My Twitter account is not just an index into my latest thoughts, but is a placeholder for a whole history of thoughts.

My previous mistake was that I was thinking too loudly.

Now I am thinking quietly. I am not claiming to be profound (probably I need to encrypt my thoughts just to spare the world). In fact, just as my thoughts are locked up behind my skull, my Twitter-Thoughts now live behind a mathematical barrier I thought up.

That’s the setup for the cryptography code I am about to show you. Now that my Twitter is closed, I thought: What if some of these thoughts escape? I write some pretty intense things that aren’t safe to share. I still want to use up my 140 character space, but I want some encryption.

I can now encrypt my Twitter comments. I wrote a simple encryption, nothing fancy, just enough to block the casual observer (especially if I leave my Twitter account up on a computer).

Here is the code for that (I had to sacrifice one character to pull this off — my encrypted tweets are thus limited to 139 characters, with one character marking the fact that it is encrypted):

/// <summary>
    /// pw is optional.  If not supplied, we just return the plain text passed in.
    /// Encrypt the plain text, then add a "*" to the end of the string (indicating a encrypted string)
    /// </summary>
    /// <param name="plain"></param>
    /// <param name="pw"></param>
    /// <returns></returns>
    public static string enc(string plain, string pw)
    {
        const byte space = 32;
        const int elements = 126 - space;
        string res = plain;
        if (pw != null && pw != string.Empty)
        {
            byte[] key = Encoding.ASCII.GetBytes(pw);
            byte[] data = Encoding.ASCII.GetBytes(plain);

            int k = 0;
            for (int i = 0; i < data.Length; i++)
            {
                int e = data[i] - space;
                e = (e + key[k]) % elements;
                data[i] = Convert.ToByte(e);
                data[i] += space;
                k++;
                if (k >= key.Length)
                    k = 0;
            }

            res = Encoding.ASCII.GetString(data) + "*";
        }
        return res;
    }
    /// <summary>
    /// Any string that ends in '*' is treated as encrypted.
    /// But we only decrypt it if you pass in a password (and, FYI, the '*' is not part of the encryption).
    /// </summary>
    /// <param name="enc"></param>
    /// <param name="pw"></param>
    /// <returns></returns>
    public static string dec(string enc, string pw)
    {
        const byte space = 32;
        const int elements = 126 - space;
        string res = enc;
        if (pw != null && pw != string.Empty)
        {
            if (enc[enc.Length - 1] == '*')
            {
                byte[] key = Encoding.ASCII.GetBytes(pw);
                byte[] data = Encoding.ASCII.GetBytes(enc.Substring(0, enc.Length - 1));
                int k = 0;
                for (int i = 0; i < data.Length; i++)
                {
                    int d = data[i] - space;
                    d = d - key[k];
                    while (d < 0)
                        d += elements;
                    d = d % elements;
                    d += space;
                    data[i] = (byte)d;
                    k++;
                    if (k >= key.Length)
                        k = 0;
                }
                res = Encoding.UTF8.GetString(data);
            }
        }
        return res;
    }

And here you see how these Twitter messages look when encoded. I map everything to the ASCII printable character set. That’s important to know. I don’t have to worry about hitting those reserved Twitter characters. I also have it so that the encrypted text is as long as the plain text. Except for the one character that I sacrifice in order to notate that a message is encrypted (which I don’t have to do, but I have my reasons), I get to keep using Twitter as normal.

If you got this far, you may want to use this encryption for yourself. In that case, you have some options. The fastest and easiest option is to use my stand-alone crypt program [see my later article for download instructions].

Optionally, I have my own Twitter program I wrote. To use the encryption code I have offered here, you need to use this or some other custom Twitter software. You can write your own (and add the above code to it), or you can use my free MicroSpeak140. Click the following link to read more about MicroSpeak140 (where you can also get all the code).

Now think. And with encrypted Twitter, you can think quietly like you have always done.

About the Method and the Encryption Strength
Someone who is acquainted with cryptographic methods may detect a weakness of what I have implemented. I will address that below, and I will give a fairly substantial defense. Yet, even if my defense is weak and my method is poor, let me set the context: I’m not trying to protect Fort Knox. My brain is not a vault of treasures. I am not trying to encrypt government secrets. I just want a little bit of bone structure to encase some sensitive tissues. My encryption scheme fits the bill.

Mine is a Vigenere Cipher (which, as you will read, is a improvement upon the older Caesar Cipher). The Vigenere method meets my five chief requirements: 1. Most obviously, I want to change the plain text (that is, I want to obscure the original message), 2. I want to use a password scheme so that each use gets different results based on the password, 3. I want to be able to use the same password to recover the plain text, 4. I want to obscure the frequencies of the English letters in the plain text, and finally, 5. As important as items 1 through 4, I want the encrypted text length to be the same or less than the length of the plain text (some encryption schemes yield an encrypted text that is longer than the plain text).

Now, we know that a Viegenre cipher is mathematically breakable if the key length is known and if your attacker is the NSA (or is a sufficiently motivated geek who is extremely patient and determined). That is, someone would have to want your memories to try to crack them, and it would require some good effort on their part (the Twitter equivalent to being captured and interrogated).

Ah, but, you can use a password that is the same length as the message you are encoding! After all, with Twitter, we are talking about messages not more than 140 characters long; we have a reasonable shot at picking memorable sentences as pass-phrases. Furthermore, you can use any number of sentences as pass-phrases. That is, you don’t have to use the same password (or pass-phrase) for every single Tweet. And, at this point, using passwords that run the length of your message (which you could database), you have a nearly unbreakable cipher.

But that means if you forget your passwords, you lose your memories (the Twitter equivalent to Alzheimer’s).

If you still want something stronger, you can try an AES and encrypt a string so that it comes out equal length — for more on this subject, look here. I did not take that route as I wasn’t that interested (nor sufficiently motivated), but with OpenSSL, these sorts of things are not so hard.

Remote copy a file across an intranet that times-out

If you have an intranet that times out part way through file copies, this program may be of use to you. This program keeps track of where it was in a file copy and will pick up where it left off.

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

namespace RCopy
{
    /// <summary>
    /// Remote Copy a file on an IntraNet.
    /// </summary>
    class RCopy
    {
        /// <summary>
        /// Copy a file starting at position.
        /// </summary>
        /// <param name="fname"></param>
        /// <param name="pos">Where to start copying,</param>
        /// <returns></returns>
        static bool Copy(FileStream fs, FileStream destination, long start, out long howFarWeMadeIt)
        {
            bool ret = true;
            howFarWeMadeIt = start;
            try
            {
                BinaryWriter w = new BinaryWriter(destination);
                BinaryReader r = new BinaryReader(fs);
                long length = r.BaseStream.Length;
                if (length > start)
                {
                    r.BaseStream.Seek(start, SeekOrigin.Begin);
                    Console.WriteLine("rem Starting at " + start + " and going to " + length);
                    while (howFarWeMadeIt < length)
                    {
                        byte[] buffer = new byte[] { 0 };
                        r.BaseStream.Read(buffer, 0, 1);
                        w.BaseStream.Write(buffer, 0, 1);
                        howFarWeMadeIt++;
                    }
                }
                r.Close();
            }
            catch
            {
                ret = false;
            }

            if (fs != null)
                fs.Close();
            return ret;
        }
        static int Main(string[] args)
        {
            if (args.Length < 2 || args.Length > 3)
            {
                Console.WriteLine("rem Usage: RCopy <source> <destination> [pos]");
                Console.WriteLine("rem");
                Console.WriteLine("rem        Remote Copy a source file off an intranet.");
                Console.WriteLine("rem               If your connection times-out while copying, you can call this program many times.");
                Console.WriteLine("rem               This program will pick up copying from the last position.");
                Console.WriteLine("rem               Pass in the position for how far the file copy got before it timed out.");
                Console.WriteLine("rem");
                Console.WriteLine("rem        <destination> will be appended if [pos] is zero or not passed in.");
                Console.WriteLine("rem");
                Console.WriteLine("rem");
                Console.WriteLine("rem        [pos] is a positive integer to start copying at the given offset");
                Console.WriteLine("rem              Default value is zero.");
                Console.WriteLine("rem");
                Console.WriteLine("rem        This program sets RCOPY to -1 if the copy failed;");
                Console.WriteLine("rem        This program sets RCOPY to 0 if it has success;");
                Console.WriteLine("rem        This program sets RCOPY to a positive number if got partially done.");
                Console.WriteLine("rem");
                Console.WriteLine("rem        This program returns an errorlevel as well.");
                Console.WriteLine("rem             errorlevel 0 means the program is done or will not work.");
                Console.WriteLine("rem             errorlevel 1 means the program worked and has more work to do.");
                Console.WriteLine("rem");
                Console.WriteLine("rem");
                Console.WriteLine("rem        This is slow program. It copies one byte at a time. It is not meant for speed.");
                Console.WriteLine("rem        It is meant to work on an unreliable network.");
                Console.WriteLine("rem");
                Console.WriteLine();
                Console.WriteLine("set RCOPY=-1");
                return -1;
            }
            long start = 0;

            if (args.Length == 3)
            {
                try
                {
                    start = Convert.ToInt64(args[2]);
                }
                catch
                {
                    Console.WriteLine("rem Invalid integer value: " + args[2]);
                    Console.WriteLine("set RCOPY=-1");
                    return 0;
                }
            }


            FileStream dest = null;
            try
            {
                if (start == 0)
                    dest = File.Open(args[1], FileMode.Create);
                else
                    dest = File.Open(args[1], FileMode.Append);
            }
            catch
            {
                Console.WriteLine("rem Error: Could not write to " + args[1]);
                Console.WriteLine("set RCOPY=-1");
                return 0;
            }

            FileStream source = null;
            Console.WriteLine("rem Reading " + args[0] + " starting at " + start);
            try
            {
                source = File.Open(args[0], FileMode.Open);
            }
            catch
            {
                Console.WriteLine("rem Could not open " + args[0]);
                Console.WriteLine("set RCOPY=-1");
            }

            long pos = 0;
            while (!Copy(source, dest, start, out pos))
            {
                start = pos;
                bool bail = false;
                try
                {
                    source.Close();
                    source = File.Open(args[0], FileMode.Open);
                }
                catch
                {
                    bail = true;
                }
                if (bail)
                {
                    Console.WriteLine("rem Call this program again: rcopy " + args[0] + " %RCOPY% ");
                    Console.WriteLine("set RCOPY=" + start);
                    dest.Close();
                    return 1;
                }
            }
            try
            {
                source.Close();
                dest.Close();
            }
            catch
            {
                Console.WriteLine("rem Closed files.");
            }
            Console.WriteLine("rem Success");
            Console.WriteLine("set RCOPY=0");

            return 0;
        }
    }
}

Chris Keck, d. March 22, 2012

KANSAS CITY, Kan. – A wrong-way crash killed one man during morning rush hour in Kansas City, Kan.

The Kansas Highway Patrol identified the victim as Christopher T. Keck, 45, of Gardner, Kan.

The crash occurred about 8:45 a.m. in a northbound lane of Interstate 635 just north of Interstate 70.

Keck was traveling north when his car was hit head-on by a vehicle headed the wrong way on the interstate.

How to deploy a new MVC 4 or MVC 5 app to and older IIS 6 server

You can install newer MVC apps on an older Windows 2003 server (it can be done very easily). You must simply configure your Web.Config with a few settings (as shown below) and you may need to go into the Windows file explorer and grant the correct rights to your web user for the path you install to. Ignore the bit about the ASP.NET user (that’s for something unrelated to what I am showing you here):

Notice I added customErrors with the value, mode=”Off” and I added a whole section called system.codedom section.

You will also need to configure your project by right clicking on your project, and selecting “Add Deployable Dependencies…” and then check all the boxes in the dialog that follows.

Then, highlight and select all the references in your new _bin_deployableAssemblies and set the properties for all of the to either “Copy always” or “Copy if newer”

Finally, make sure that Global.asax is added to the list of files you can access. This is done under IIS under the Virtual directory you care about (where you installed your web site) or under the web site itself.

Programming by existence

If something is there, it has existence.

In C# this makes all the difference. I realized this morning that I don’t wire-up relationships, but the C# MVC system works on the basis of mere existence.

If a filename with a certain name exists, it is accessed by a controller. In the Data Entity Model, the existence of a table name is mapped to a class name. By existence. I don’t tell the C# system what to associate with what. I just create the item, and its existence makes it alive.

C# MVC programming is programming by existence.

It is also programming by name. When something exists, it must be named (a file name, a class name, a property name, etc.). If it exists, its name is how it relates to the system.

C# MVC programming is programming by existence with right naming.

This is eloquent.

Edit .CMD files with Visual Studio Editor

Do you use Visual Studio to edit Windows batch files? Do you want these .bat or .cmd files to show up with all the colors you see in your C# files?

If this is what you seek, then let me point you to the TextHighlighterExtensionSetup by Frederic Torres (you can use Visual Studio, Tools->Extension Manager to obtain it, or do the following steps).

Step 1: Install the Iron Python 2.6 or greater (for .NET 4). It was a one or two click install, I didn’t change any settings, it just worked. Try this link: http://ironpython.codeplex.com/releases/view/41236#DownloadId=159515 or get 2.7 here: http://ironpython.codeplex.com/releases/view/62475. If the link is no good, just go to Iron Python, click on the Download menu, and get the latest download.

Step 2: Get and install the .CMD extension itself: http://visualstudiogallery.msdn.microsoft.com/6706b602-6f10-4fd1-8e14-75840f855569 If this link dos not work, go to the Visual Studio Gallery and search for TextHighlighterExtensionSetup (note, there are a few search boxes, make sure to use the one that searches the extensions).

For another useful extension, see also Spell Checker which adds the little red underline to misspelled words in comments. Very nice.

Write a Windows Console Application in C# that uses Twitter (and do it in 30 minutes or less)

I decided to write a program called “microSpeak140″ that would be a Windows command-line tool to let me post Twitter updates. The reason for such a seemingly useless tool comes from an idea I had about subscription-based communication to unmanned devices, which naturally led to the thought about implementing an Erlange-like language distributed over Twitter. Hence I started down this path. But none of that is terribly relevant to this post, so I’ll skip all the “whys?” and go right to the “how?”

Step 1: Pick a name for your program (I picked “microSpeak140″).

Step 2: Go to Twitter developer’s site and register the name you picked: https://dev.twitter.com/apps/

If you are like me, you may want to skip this step and go right to the TCP/IP interface (thinking, “just tell me what port to connect to and I’ll start talking”). But it’s not like that. Twitter won’t let you near their servers so easily; there is no skipping this really simple step–it only takes a minute and it is free. So go register your program name at https://dev.twitter.com/apps/ and grab the ASCII strings they give you.

Namely, they will give you two string, the “Consumer key” and the “Consumer secret”. These are the two ASCII strings we need to complete the following steps (you will add them to the Speak140 object). You need them for Twitter to let your program talk to their servers, and you will put them into your C# code file (again, in this case, Speak140.cs).

Step 3: Download the .NET library, TweetSharp from TweetSharp (or use NuGet in Visual Studio).

Step 4: Create a new project in Visual Studio, a Visual C# > Windows > Console Application (give it the same name — in my case, again, this is microSpeak140.cs). Note, I also like to rename the default “program.cs” to “microSpeak140.cs”

Step 5: Add a ref to TweetSharp (which you downloaded in Step 3).

Step 6: Create your Main program as follows (inside program.cs or, in my case, microSpeak140.cs):

using System;
namespace microspeak140
{
    class microSpeak140
    {
        static void Main(string[] args)
        {

            int len = args.Length;
            int start = 0;
            string pw = string.Empty;

            
            if (len > 0 && args[start] == "-P")
            {
                if (args.Length > 1)
                {
                    pw = args[1];
                    start = 2;
                    len -= 2;
                }
            }

            if (len > 0 && len < 3)
            {
                Speak140 t = new Speak140();
                if (len == 2 && args[start] == "-W")
                    t.theirWall(args[start+1], 0, pw);
                else if (len == 1 && args[start] == "-F")
                    t.iFollow();
                else if (len == 1 && args[start] == "-M")
                    t.followMe();
                else if (len == 1 && args[start] == "-W")
                    t.myWall(0, pw);
                else if (len == 1) // they are leaving a comment.
                    t.Say(args[start], true, pw);
            }
            else
            {
                Console.WriteLine("Usage: microSpeak140 [-P password] <-F> | ");
                Console.WriteLine("            <-W [name of someone else]> | ");
                Console.WriteLine("            <\"message to send (max 140 character)\">");
                Console.WriteLine();
                Console.WriteLine("       -P   Pass in -P followed by a password if you want"); 
                Console.WriteLine("            to encrypt or decrypt messages.");
                Console.WriteLine("       -W   Show me what is on my wall, or [someone else]'s wall.");
                Console.WriteLine("       -F   List the people I follow.");
                Console.WriteLine("       -M   List the people that follow me.");
            }
        }
    }
}

Step 9: Include this object I created: Speak140.cs.
Speak140.cs is my own wrapper around the Twitter DLLs. I had a very narrow purpose for my console application, so this object helps me to zero-in on the narrow set of functions I really wanted to leverage, along with helping me with Twitter key management and encryption. I’ll have more to say about encryption below–by which I mean the option to encrypt the messages you post to Twitter.

Step 10: Build your program.
Note: you may need to go to Project->microSpeak140 properties->Application and set the target framework as .NET 3.0 (i.e., not the default 4.0). Then build it. Then switch it back to 4.0 and try again.

Step 11: Drop down to a command window, go to the build directory, and run it:

    microSpeak140  "At coffee house writing Twitter app in 30 minutes or less"

Step 12: Encrypt your comments
You will notice in the program that I provide a command-line option for a password. This allows you to encrypt your comments. But I will save the details about that for another post. [Indeed, read my later article here for a discussion of encrypting and decrypting messages using MicroSpeak140].

Step 13: What Next: Make it your own!
Maybe you will want to add your own reader functions to the Speak140 object. Or, it might be a good idea to add code to use the registry as opposed to files, and thus handle multiple twitter accounts. You have all the code, so enjoy it and make it your own.

The sum of consecutive cubes is a square

Summing up some cubes I noticed that 13 + 23 + 33 + 43 = 100, which is 102. And the pattern held as I added more cubes (i.e., I kept getting squares). This is well known in the world of mathematics and number theory, but it was new to me. Extending the pattern:

The sum of the consecutive cubes is a square

And that makes these triangular numbers. And that means that every triangular number squared is the sum of cubes. It works both way in being interesting.

Free Sequence Diagram PNG and PDF Generator

I want to share a link quite useful for explaining the sequence of events. In the technology world, there is a thing called a sequence diagram. A sequence diagram is useful for showing messages that pass back and forth between parties (in order, and sequenced).

For example, this little text here shows how I log onto my bank web site securely using SSL and certificates:

Me->www.MyBank.com: Browse to web site
note left of Me: I think I am attaching to my bnak
www.MyBank.com->Me: My bank sends an SSL Certificate
note right of www.MyBank.com: My bank got an SSL certificate file VeriSign or GoDaddy
note left of Me: I decrypting the cert using the Verisign public key.
Me->www.MyBank.com: Now I send my password
www.MyBank.com->Me: Display my bank account

Feeding that text into the FREE web site, http://www.websequencediagrams.com/, I get the following PNG image file showing the flow of messages:

This free web site is a wonderful resource, especially as sequence diagrams are useful for showing the relationships of events, messages and entities.

Customize the front page of a WordPress blog to merely list your articles

In my WordPress 3.x blog, I use the default theme, and now I want the main page to be a list of all my articles — nothing more, and nothing fancy. I don’t want any of the articles to have a preview paragraph, or the author, or the date and time of publication on the main page. None of that. I only want a list of all my articles, ordered by date, with each entry being a link to the entire article.

Here is how to do it:

1. Create a file called loop-index.php; it will get used instead of loop.php
2. Populate that file as per the loop-index.php file below
3. See my WordPress blog at http://www.mrrives.com/Gezer, to see how it looks

<?php
/*   THE LOOP - Rives Simple Version, cf. http://codex.wordpress.org/Function_Reference/get_template_part
     This file is called by index.php, get_template_part( 'loop', 'index' ), which does a PHP require() 
      for the first file that exists among these, in this priority:
        wp-content/themes/twentytenchild/loop-index.php then wp-content/themes/twentytenchild/loop.php
        wp-content/themes/twentyten/loop-index.php      then wp-content/themes/twentyten/loop.php
 */
?>

<h1><i>The Articles</i></h1>
<?php $pcounter = $wp_query->post_count; ?>
<?php $first_time = 1; ?>
<ol>
 <?php while ( have_posts() ) : the_post(); ?>
  <?php if ($first_time == 1): $first_time = 0; ?>
     <i>Ordered by date of publication with the most recent article listed first<br/>
      Date of last publication: <?php echo get_the_date(); ?><br/></i><br/>  
  <?php endif; ?>
  <div>
     <li value="&lt;?php echo $pcounter--; ?>">
     <h5 class="entry-title" style="font-size: 15px; font-weight: normal;">
     <a href="&lt;?php the_permalink(); ?>"
 STYLE="text-decoration: none" 
title="<?php printf( 
esc_attr__( 'Permalink to %s', 'twentyten' ), 
the_title_attribute( 'echo=0' ) ); ?>" 
rel="bookmark"><?php the_title(); ?></a></h5>
     </li>
   </div>

 <?php endwhile; ?>
</ol>

Pipe Stdin to a C# program and filter out data

I need a program that will filter command line input, and strip out CR+LF from any line that has a certain text.

Solution (in C#):

http://www.mrrives.com/Programming/Filter/Filter.cs

And the EXE file:

http://www.mrrives.com/Programming/Filter/Filter.exe

Here is the code (simple):

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

namespace Filter
{
    class Filter
    {
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("FILTER: Parameter format not correct");
                return;
            }
            if (args[0] == "/?")
            {
                Console.WriteLine("Searches for a text string typed at the prompt or piped from another program");
                Console.WriteLine("");
                Console.WriteLine("FILTER \"string\"");
                Console.WriteLine("");
                Console.WriteLine("if string in a line, line is echoed without a CR+LF, otherwise it is.");
                return;
            }

            string s = string.Empty;
            try
            {
                while (System.Console.In.Peek() != -1)
                {
                    s = System.Console.In.ReadLine();
                    if (s.Contains(args[0]))
                        Console.Write(s);
                    else
                        Console.WriteLine(s);
                }
            }
            catch
            {

            }

        }
    }
}

Note, I was able to use the really nice web site, http://www.manoli.net/csharpformat/format.aspx to format my C# code into HTML

Part 1: Building an ActiveX Control in C# (with CAB file via CabArc)

I will show you how to write MyActiveX.cs, turn it into a DLL, place it on an HTML page and distribute it with a CAB file. But I will start in reverse order.

I will start with the HTML code and the CAB file. If you are going to build an ActiveX control in C#, then you need to be able to send it around (by the way, ActiveX controls only work in IE, not Chrome or Firefox, so you will only send it around to IE browsers).

When IE tries to access an ActiveX file (and it does not already have it on the hard drive), then the HTML code tells it to download a CAB and install it. For the sake of simplicity, let’s say your index.html file points to your ActiveX control this way:

<OBJECT id="MyActiveX" name="MyActiveX" 
classid="clsid:3026b51e-a3ff-4587-9ed2-36d7d527bbe6" VIEWASTEXT 
codebase="MyActiveX.cab#Version=1,0,2,0">

MyActiveX.cab is in the same folder as index.htm, and if the MyActiveX.dll is missing, then the CAB file is downloaded and installed. But you have to make that CAB file. To build the CAB file (which is like a ZIP file), you need to use the free CABARC program. You will pass it the name of the ActiveX, and a few support tools that will get stuffed in there with it. I will explain all the files in time, but here is the command line to create a CAB:

cabarc -s 6144 n MyActiveX.cab MyActiveX.dll RegNetX.exe setup.cmd MyActiveX.inf

(You can Download Microsoft’s cabarc.exe here).

This creates the CAB file, MyActiveX.cab, and inside it is the other four files. The final file, MyActiveX.inf, tells the CAB file what to do and what is inside it. It tells us that the ActiveX DLL will go to DestDir=11 (which is a secret Microsoft code meaning windows\sytem32). DestDir=11. Write it down. Use it. The -s command means to add on an extra 6144 bytes so that we can sign this CAB file when all is said and done (I will talk about signing CAB files in Part 2 or Part 3 — do not underestimate how important it is to sign your CAB file and ActiveX file if you want clients to be able to install and use your software).

Let’s look first at MyActiveX.inf (which tells the CAB file how to install on the client):


[Setup Hooks]
hook1=hook1

[hook1]
run=%EXTRACT_DIR%\setup.cmd

[version]
signature="$CHICAGO$"
AdvancedINF=2.0

[Add.Code]
MyActiveX.dll=MyActiveX.dll
MyActiveX.inf=MyActiveX.inf
setup.cmd=setup.cmd
RegNetX.exe=RegNetX.exe

[MyActiveX.dll]
file-win32-x86=thiscab
clsid={3026b51e-a3ff-4587-9ed2-36d7d527bbe6}
RegisterServer=no
FileVersion=1,0,2,0
DestDir=11

[MyActiveX.inf]
file=thiscab

[setup.cmd]
file=thiscab

[RegNetX.exe]
file=thiscab

If you inspect this file, you see that the CAB file will run setup.cmd as the install script when it arrives at a target machine. There is a good article on CAB files and hooks on the Microsoft web site, but that article fails to give you the extra steps required to release a .NET based ActiveX control. Still, go read it and get familiar with the subject, or keep moving along here and you’ll get the gist.

The reason you need all this specialty code for a .NET project, is because a CAB file uses RegSvr32 to register an ActiveX, and that won’t work for a .NET DLL. You need to use Microsoft’s RegAsm to register a .NET ActiveX, but CAB files don’t know about RegAsm. The install location of RegAasm is in your .NET directory. So Setup.cmd is called as the install program, and it handles the registration.

That’s the trick! Setup.cmd is the trick. And here is Setup.cmd


@echo off
set MyACTIVEX=%windir%\system32\MyActiveX.dll
copy MyActiveX.dll %MyACTIVEX%
RegNetX

You may be wondering: What is RegNetX?

It is a little install program I wrote. All it does is install my one ActiveX program. I compile the install program from the command line using csc (which comes free with .NET and is in your Framework directory):

csc RegNetX.cs

Here is the code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.Diagnostics;

namespace RegNetX
{
    class Program
    {
        static void Main(string[] args)
        {

	    string DLL = Environment.SystemDirectory + "\\MyActiveX.dll";

 	    Console.WriteLine("Usage: RegNetX [-u]");
 	    Console.WriteLine("    Will register " + DLL);
 	    Console.WriteLine("   -u unregisters it");

            // This is the location of the .Net Framework Registry Key
            string framworkRegPath = @"Software\Microsoft\.NetFramework";

            // Get a non-writable key from the registry
            RegistryKey netFramework = Registry.LocalMachine.OpenSubKey(framworkRegPath, false);

            // Retrieve the install root path for the framework
            string installRoot = netFramework.GetValue("InstallRoot").ToString();

            // Retrieve the version of the framework executing this program
            string version = string.Format(@"v{0}.{1}.{2}\",
              Environment.Version.Major,
              Environment.Version.Minor,
              Environment.Version.Build);

            // Return the path of the framework
            string path = System.IO.Path.Combine(installRoot, version);

            if (path == null)
                path = installRoot + version;

            try
            {
                Process regAsm = new Process();
                regAsm.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                regAsm.StartInfo.CreateNoWindow = true;
                regAsm.StartInfo.WorkingDirectory = path;
                regAsm.StartInfo.FileName = "regasm.exe";
                if (args.Length == 0)
                  regAsm.StartInfo.Arguments = "/silent /codebase " + DLL;
                else
                  regAsm.StartInfo.Arguments = "/unregister " + DLL;
 		
		Console.WriteLine(path + "regasm.exe " + regAsm.StartInfo.Arguments );
                regAsm.Start();
                regAsm.WaitForExit(); // based on comboFusion's comment below (in the comment section of this blog)
            }
            catch
            {
                Console.WriteLine("Error running regasm.exe " + args[0]);
            }
        }
    }
}

RegNetX will find the .NET install and call RegAsm. And note well: I hard coded everything to install the ActiveX DLL into the windows\system32 directory. It makes life so much easier if you know that %windir% is a real environment variable that will exist on your target client. When your code is actually installing, it is in a free fall, and your scripts are operating mostly blind, as it were, so you need to try to land in some known fixed location. For that reason, I coded setup.cmd with a fixed install location with an environment variable that will most likely exist. And how nice that DestDir in the INF file is also pointing to %windir%\system32.

After writing this article, I realized that the CAB building tool, cabarc, is old. It is no longer distributed (though it was on my Windows 7 machine). There is another CAB building tool from Microsoft called “MakeCab”. In Part 2 (if I write Part 2), I will go deeper into all this and show the actual ActiveX control. If there is a Part 3, it may be about MakeCab. Given the positive feedback I have received so far, I may just write that second article.

Generate an HTML Data Dictionary for your Microsoft Database

If you want to auto-generate an HTML Data Dictionary for your Microsoft SQL database, here is a free and simple tool to do it. It is a Windows command line script. Just drop down to a command window, and run this command script and pass in the name of your database (the script will give help if you pass in no parameters). Go get a coffee, come back and see the HTML results.

This data dictionary script is meant for developers who need to know the kind of data in the database, and the resulting HTML file is editable so that developer notes can be added over time. I wrote it one weekend as I was contemplating how to document a database. Tools exist to do this, of course, but this one is free, and sufficient for my needs.

This works with all versions of Microsoft SQL. If there is something about it that does not work, let me know, and I’ll see how easy it is to fix. Or, better, just edit it and fix it as you need.

Create a .NET 4 MVC 3 Web Site or Migrate MVC 2 to 3

In earlier posts, I explained the move from Silverlight 3 to 4. Now I want to explain the move from MVC 2 to 3. You need to upgrade, as one day we may well be on MVC 13, and you won’t want your site still running on MVC 2. Besides, MVC 3 has the new HTML Razor engine. Yeah!

In Part I, I briefly explain how to make the small jump from MVC 2 to 3.

In Part II, I give steps for creating an MVC 3 /Razor enabled web site from scratch.

Part I — Move from MVC 2 to 3

Step 1: Install MVC 3

To Install MVC 3, download it here: http://www.asp.net/mvc/mvc3

Step 2: Convert your existing project

To do this, use the automatic conversion tool found here:
http://aspnet.codeplex.com/releases/view/59008

This tool successfully converted my Web.config and Views\Web.config files.

That’s it, the conversion is that easy.

Part II — Creating an MVC Site from Scratch

An MVC 3 site which uses the Razor engine (as opposed to WebForms) is quite compelling, and is the engine of choice (as I understand it). To use this technology, you’ll need to spend three or four hours reading and implementing tutorials.

Step 1: Watch the Tutorials

This multiple part tutorial will get you going with a .NET 4 web site, MVC 3 and Razor. You can use the free Visual Studio browser to build your site, but you will need to purchase space on a .NET 4 compatible server (Discount ASP.NET is a good choice).

Part 1 of 9.

Step 2: Prepare your target server to receive your site

So, you have built your web site, and you want to get your public server ready to serve it up to the world. The exact steps you need to take to do this are dependent upon your particular brand of server, but what you will need to do looks something like what you see at Discount ASP.NET.

You will want to read my earlier article on Silverlight to see how to prepare your server for .NET apps.

Step 3: Deploy

MVC 3 is new, so your server may need some help recognizing your project files. Namely, add the following references to your project and for each one, go to the properties and set Copy Local to true (my source of information).

System.Web.Mvc

Microsoft.Web.Infrastructure

System.Web.Razor

System.Web.WebPages

System.Web.WebPages.Razor

System.Web.Helpers

System.Web.WebPages.Deployment

Conclusion

Programming dynamic web sites is getting a lot easier, and the .NET 4 framework with MVC 3 and the Razor engine is proof. These technologies represent hundreds of man-years (thousands maybe), which have been invested to build and perfect a truly reusable platform.

Pell’s equation (from 2 to 308)

Pell’s equation is a Diophantine equation stated this way:

(c)a2 + 1 = b2

The trick is to find answers on the integers (where a, b and c are all integers which satisfy the equation). I will call these Pell’s triples.

The first 102 Pell’s triples are listed in Beiler, A. H. “The Pellian.” Ch. 22 in Recreations in the Theory of Numbers: The Queen of Mathematics Entertains. New York: Dover, pp. 248-268, 1966 (and can be found at MathWorld).

Below is a C++ program that uses a MPIR / GMP to brute-force locate the first Pell’s triple for the value of c (or for some range of values). The program was run to find the following 308 triples. It takes a few minutes to run, and any listing with ??? beside it was bigger than a long (easy to fix in the program by changing the long to a long long, for which, see the size limits at this site):

(  2)         22 + 1 =          32
(  3)         12 + 1 =          22
(  5)         42 + 1 =          92
(  6)         22 + 1 =          52
(  7)         32 + 1 =          82
(  8)         12 + 1 =          32
( 10)         62 + 1 =         192
( 11)         32 + 1 =         102
( 12)         22 + 1 =          72
( 13)       1802 + 1 =        6492
( 14)         42 + 1 =         152
( 15)         12 + 1 =          42
( 17)         82 + 1 =         332
( 18)         42 + 1 =         172
( 19)        392 + 1 =        1702
( 20)         22 + 1 =          92
( 21)        122 + 1 =         552
( 22)        422 + 1 =        1972
( 23)         52 + 1 =         242
( 24)         12 + 1 =          52
( 26)        102 + 1 =         512
( 27)         52 + 1 =         262
( 28)        242 + 1 =        1272
( 29)      18202 + 1 =       98012
( 30)         22 + 1 =         112
( 31)       2732 + 1 =       15202
( 32)         32 + 1 =         172
( 33)         42 + 1 =         232
( 34)         62 + 1 =         352
( 35)         12 + 1 =          62
( 37)        122 + 1 =         732
( 38)         62 + 1 =         372
( 39)         42 + 1 =         252
( 40)         32 + 1 =         192
( 41)       3202 + 1 =       20492
( 42)         22 + 1 =         132
( 43)       5312 + 1 =       34822
( 44)        302 + 1 =        1992
( 45)        242 + 1 =        1612
( 46)      35882 + 1 =      243352
( 47)         72 + 1 =         482
( 48)         12 + 1 =          72
( 50)        142 + 1 =         992
( 51)         72 + 1 =         502
( 52)        902 + 1 =        6492
( 53)      91002 + 1 =      662492
( 54)        662 + 1 =        4852
( 55)        122 + 1 =         892
( 56)         22 + 1 =         152
( 57)        202 + 1 =        1512
( 58)      25742 + 1 =      196032
( 59)        692 + 1 =        5302
( 60)         42 + 1 =         312
( 61) 2261539802 + 1 = 17663190492
( 62)         82 + 1 =         632
( 63)         12 + 1 =          82
( 65)        162 + 1 =        1292
( 66)         82 + 1 =         652
( 67)      59672 + 1 =      488422
( 68)         42 + 1 =         332
( 69)       9362 + 1 =       77752
( 70)        302 + 1 =        2512
( 71)       4132 + 1 =       34802
( 72)         22 + 1 =         172
( 73)    2670002 + 1 =    22812492
( 74)       4302 + 1 =       36992
( 75)         32 + 1 =         262
( 76)      66302 + 1 =      577992
( 77)        402 + 1 =        3512
( 78)         62 + 1 =         532
( 79)         92 + 1 =         802
( 80)         12 + 1 =          92
( 82)        182 + 1 =        1632
( 83)         92 + 1 =         822
( 84)         62 + 1 =         552
( 85)     309962 + 1 =     2857692
( 86)      11222 + 1 =      104052
( 87)         32 + 1 =         282
( 88)        212 + 1 =        1972
( 89)     530002 + 1 =     5000012
( 90)         22 + 1 =         192
( 91)       1652 + 1 =       15742
( 92)       1202 + 1 =       11512
( 93)      12602 + 1 =      121512
( 94)    2210642 + 1 =    21432952
( 95)         42 + 1 =         392
( 96)         52 + 1 =         492
( 97)   63773522 + 1 =   628096332
( 98)        102 + 1 =         992
( 99)         12 + 1 =         102
(101)        202 + 1 =        2012
(102)        102 + 1 =        1012
(103)     224192 + 1 =     2275282
(104)         52 + 1 =         512
(105)         42 + 1 =         412
(106)   31158902 + 1 =   320800512
(107)        932 + 1 =        9622
(108)       1302 + 1 =       13512
(109) -------------------- See comment Section Below --------------------------
(110)         22 + 1 =         212
(111)        282 + 1 =        2952
(112)        122 + 1 =        1272
(113)    1132962 + 1 =    12043532
(114)        962 + 1 =       10252
(115)       1052 + 1 =       11262
(116)       9102 + 1 =       98012
(117)        602 + 1 =        6492
(118)     282542 + 1 =     3069172
(119)        112 + 1 =        1202
(120)         12 + 1 =         112
(122)        222 + 1 =        2432
(123)        112 + 1 =        1222
(124)    4149602 + 1 =    46207992
(125)     832042 + 1 =     9302492
(126)        402 + 1 =        4492
(127)    4197752 + 1 =    47306242
(128)        512 + 1 =        5772
(129)      14842 + 1 =      168552
(130)       5702 + 1 =       64992
(131)       9272 + 1 =      106102
(132)         22 + 1 =         232
(133)    2244602 + 1 =    25885992
(134)     126062 + 1 =     1459252
(135)        212 + 1 =        2442
(136)         32 + 1 =         352
(137)    5197122 + 1 =    60830732
(138)         42 + 1 =         472
(139)   65788292 + 1 =   775632502
(140)         62 + 1 =         712
(141)         82 + 1 =         952
(142)        122 + 1 =        1432
(143)         12 + 1 =         122
(145)        242 + 1 =        2892
(146)        122 + 1 =        1452
(147)         82 + 1 =         972
(148)         62 + 1 =         732
(149)21137610202 + 1 = 258017414492
(150)         42 + 1 =         492
(151) 1406346932 + 1 = 17281480402
(152)         32 + 1 =         372
(153)       1762 + 1 =       21772
(154)      17162 + 1 =      212952
(155)        202 + 1 =        2492
(156)         22 + 1 =         252
(157) ???
(158)       6162 + 1 =       77432
(159)       1052 + 1 =       13242
(160)        572 + 1 =        7212
(161)       9282 + 1 =      117752
(162)      15402 + 1 =      196012
(163)   50191352 + 1 =   640800262
(164)       1602 + 1 =       20492
(165)        842 + 1 =       10792
(166) 1320156422 + 1 = 17009025652
(167)        132 + 1 =        1682
(168)         12 + 1 =         132
(170)        262 + 1 =        3392
(171)        132 + 1 =        1702
(172)   18489422 + 1 =   242486472
(173)    1900602 + 1 =    24998492
(174)       1102 + 1 =       14512
(175)       1532 + 1 =       20242
(176)        152 + 1 =        1992
(177)      46922 + 1 =      624232
(178)       1202 + 1 =       16012
(179)    3131912 + 1 =    41902102
(180)        122 + 1 =        1612
(181) ???
(182)         22 + 1 =         272
(183)        362 + 1 =        4872
(184)      17942 + 1 =      243352
(185)       6802 + 1 =       92492
(186)       5502 + 1 =       75012
(187)       1232 + 1 =       16822
(188)       3362 + 1 =       46072
(189)         42 + 1 =         552
(190)      37742 + 1 =      520212
(191)    6507832 + 1 =    89940002
(192)         72 + 1 =         972
(193) ???
(194)        142 + 1 =        1952
(195)         12 + 1 =         142
(197)        282 + 1 =        3932
(198)        142 + 1 =        1972
(199)11530800992 + 1 =162661965202
(200)         72 + 1 =         992
(201)     363322 + 1 =     5150952
(202)   13883222 + 1 =   197317632
(203)         42 + 1 =         572
(204)       3502 + 1 =       49992
(205)      27722 + 1 =      396892
(206)      41482 + 1 =      595352
(207)        802 + 1 =       11512
(208)        452 + 1 =        6492
(209)      32202 + 1 =      465512
(210)         22 + 1 =         292
(211) ???
(212)      45502 + 1 =      662492
(213)     133202 + 1 =     1943992
(214) ???
(215)         32 + 1 =         442
(216)        332 + 1 =        4852
(217)    2609522 + 1 =    38440632
(218)      85342 + 1 =     1260032
(219)         52 + 1 =         742
(220)         62 + 1 =         892
(221)       1122 + 1 =       16652
(222)        102 + 1 =        1492
(223)        152 + 1 =        2242
(224)         12 + 1 =         152
(226)        302 + 1 =        4512
(227)        152 + 1 =        2262
(228)        102 + 1 =        1512
(229)    3864602 + 1 =    58482012
(230)         62 + 1 =         912
(231)         52 + 1 =         762
(232)      12872 + 1 =      196032
(233)  702553042 + 1 = 10724006732
(234)       3402 + 1 =       52012
(235)         32 + 1 =         462
(236)     365702 + 1 =     5617992
(237)     148202 + 1 =     2281512
(238)       7562 + 1 =      116632
(239)    4007292 + 1 =    61951202
(240)         22 + 1 =         312
(241) ???
(242)      12602 + 1 =      196012
(243)      45052 + 1 =      702262
(244) 1130769902 + 1 = 17663190492
(245)      33122 + 1 =      518412
(246)      56622 + 1 =      888052
(247)      54272 + 1 =      852922
(248)         42 + 1 =         632
(249)    5420762 + 1 =    85538152
(250)   24969662 + 1 =   394804992
(251)    2319572 + 1 =    36748902
(252)         82 + 1 =        1272
(253) 2026042202 + 1 = 32226173992
(254)        162 + 1 =        2552
(255)         12 + 1 =         162
(257)        322 + 1 =        5132
(258)        162 + 1 =        2572
(259)     526442 + 1 =     8472252
(260)         82 + 1 =        1292
(261)  118918802 + 1 =  1921192012
(262)   64857182 + 1 =  1049805172
(263)      85792 + 1 =     1391282
(264)         42 + 1 =         652
(265)   45297122 + 1 =   737383692
(266)        422 + 1 =        6852
(267)       1472 + 1 =       24022
(268) 2914402142 + 1 = 47710819272
(269)       8202 + 1 =      134492
(270)       3222 + 1 =       52912
(271) ???
(272)         22 + 1 =         332
(273)        442 + 1 =        7272
(274)    2391902 + 1 =    39592992
(275)        122 + 1 =        1992
(276)       4682 + 1 =       77752
(277) ???
(278)       1502 + 1 =       25012
(279)        912 + 1 =       15202
(280)        152 + 1 =        2512
(281) ???
(282)       1402 + 1 =       23512
(283)   82195412 + 1 =  1382740822
(284)   14372402 + 1 =   242207992
(285)       1442 + 1 =       24312
(286)     332222 + 1 =     5618352
(287)        172 + 1 =        2882
(288)         12 + 1 =         172
(290)        342 + 1 =        5792
(291)        172 + 1 =        2902
(292)    1335002 + 1 =    22812492
(293)    7197802 + 1 =   123206492
(294)       2802 + 1 =       48012
(295)    1179002 + 1 =    20249992
(296)       2152 + 1 =       36992
(297)      28202 + 1 =      485992
(298) ???
(299)        242 + 1 =        4152
(300)        782 + 1 =       13512
(301) ???
(302)    2460922 + 1 =    42766232
(303)       1452 + 1 =       25242
(304)      33152 + 1 =      577992
(305)        282 + 1 =        4892
(306)         22 + 1 =         352
(307)   50526332 + 1 =   885292822
(308)        202 + 1 =        3512

And, here is the program that created that list:


#include < math.h>
#include < stdio.h>
#include < stdlib.h>
#include < gmpxx.h>
#include < iostream>
#include < iomanip>
#include < time.h>

using namespace std;

void main(int argc, char *argv[])
{
   
   int start=61,end=61;
   clock_t total = clock();
   if (argc == 3)
   {
	   end   = atoi(argv[2]);
	   start = atoi(argv[1]);
   }
   else
   {
	   cout << "Usage: Pell < start> < stop>\n";
	   return;
   }
   cout << setiosflags(ios::right);

   for (int c = start; c <= end; c++)
   {
	   cerr << "c = " << c << " ";
	   double guess, root = sqrt((double)c);  

	   if ((long)root * (long)root == (long)c) // skip squares
		   continue;
	   
	   mpz_class bi_b;
	   mpz_class bi_a  = c + 1; // c*1^2 + 1 = c + 1
	   mpz_class diff  = c * 3; // difference of first and second term
	   mpz_class delta = c * 2; // series grows this way
	   long a = 1;
	   bool bfound = false;
       
	   while (!bfound && a >= 0)  // when a wraps around negateve, bail
	   {
			if (mpz_perfect_square_p(bi_a.get_mpz_t()))
			{
				mpz_sqrt(bi_b.__get_mp(), bi_a.get_mpz_t());
				cout << "(" << setw(3) << c << ")" << setw(10) << a << "< sup>2< /sup> + 1 = " << setw(10) << bi_b << "< sup>2< /sup>\n";
				bfound = true;
			}
			bi_a += diff;  
			diff += delta;
			a++;
	   }

	   if (!bfound)
		   cout << "(" << setw(3) << c << ") ???\n";
   }
   cerr << "Total program time: " << (double)(clock() - total) / CLOCKS_PER_SEC << "\n";
}

Pell’s equation (from 3 to 80)

Find integers, a,b,b, such that (a)b2 + 1 = c2, and
find the non-trivial (i.e., large) answers:

( 3)  1095525752 + 1 =  1897506262
( 6) 18441601002 + 1 =  2222839532
( 7)  7865546882 + 1 = 20810280972
( 8) 15834079812 + 1 =  1835867872
(10)  4740947642 + 1 = 14992192812
(11)  1896071972 + 1 =  6288559302
(12)  2044278882 + 1 =  7081589772
(15)  9299445112 + 1 = 36016596042
(17)  1516933522 + 1 =  6254477132
(20) 12018817442 + 1 = 10800112652
(21)  9762892282 + 1 =  1789519912
(24)  9220800502 + 1 =  2222839532
(26) 10821200502 + 1 = 12227839552
(27)   365175252 + 1 =  1897506262
(28)  3932773442 + 1 = 20810280972
(30)  4969289122 + 1 = 27217917452
(32) 10463713912 + 1 = 16242031532
(34)  1439718062 + 1 =  8394926752
(35)   343560482 + 1 =  2032531212
(39)   249700042 + 1 =  1559376252
(40)  2370473822 + 1 = 14992192812
(42)  6132699022 + 1 = 39744432132
(45)  8012544962 + 1 = 10800112652
(46)  1746279602 + 1 = 11843844492
(47)  5943490632 + 1 = 40746518882
(48)  1022139442 + 1 =  7081589772
(51)  6997900072 + 1 =  7025329542
(54) 18146568322 + 1 =  4500480012
(55)   676727522 + 1 =  5018745612
(57)  5508600802 + 1 = 41589024012
(58)  1009162442 + 1 =  7685552172
(61)  2261539802 + 1 = 17663190492
(62)   160009922 + 1 =  1259919372
(63)  2621848962 + 1 = 20810280972
(66)   175739202 + 1 =  1427712012
(67)  5828804282 + 1 =  4761146312
(68)   758466762 + 1 =  6254477132
(70)  2567197762 + 1 = 21478717452
(74) 17726058602 + 1 = 23636302892
(75)   219105152 + 1 =  1897506262
(78)    71448242 + 1 =   631013772
(79)   368611202 + 1 =  3276288012
(80)  6009408722 + 1 = 10800112652

Part 3 of 3: Speed Comparison of C# BigInteger and C++ mpir

Jan, 2012 Update: With properly coded C#, C++ (in certain cases) is only 2.37x faster (for more, see Patrick’s comment below).

In Part 2 we looked at a C# program that does a little bit of large integer math (using BigInteger). The program was built in release mode, and it gave us its answer in about 55 seconds.

Now it is time to run the same program in C++ using the mpir library (discussed in Part 1 of this 3 part series). MPIR is a Windows-port of the GMP (GNU Multiple Precision Arithmetic Library).

Here is the code (converted from C# to C++):


#include < math.h>
#include < stdio.h>
#include < stdlib.h>
#include < gmpxx.h>
#include < iostream>
#include < time.h>

using namespace std;

void main(int argc, char *argv[])
{
   clock_t start = clock();

   long b, a = 0;
   double guess, root = sqrt(61.0);  

   mpz_class bi_a;
   mpz_class bi_b;
            
   while (a >= 0)  // when a wraps around negateve, bail
   {
        a++;
        guess = a * root; 
        b = (long)floor(guess);
        bi_a = 61 * a * a + 1;
        for (long j = 0; j < 1; j++) // change j < 1 to j < 2 if no answer found...
        {
            b += j;
            bi_b = b * b;
            if (bi_a == bi_b)
            {
                cout << "61 * " << a << "^2 + 1 = " << b << "^2\n";
                cout << "\n\nFinished in Seconds: " << (double)(clock() - start) / CLOCKS_PER_SEC << "\n";
                return;
            }
        }
   }
}

The output of the program is this:

61 * 226153980^2 + 1 = 1766319049^2

Finished in Seconds: 11.5

The C++ code is nearly 5x faster.

C++ wins.

Part 2 of 3: Speed Comparison of C# BigInteger and C++ mpir

In Part 1 I discussed how to use Visual Studio C++ with MPIR and how to use BigInteger and BigRational in C#. Now I want to compare the speed between the two number packages.

We may instinctively suspect that C++ release code is faster than C# — especially optimized large integer packages. So, I will put it to the test. In this part of the series, I write a C# program, and in Part 3 I write the same thing in C++; it is a program to solve a relatively simple Pell’s equation (a famous one too, from Amusements in Mathematics by Henry Dudeney):

129.—THE BATTLE OF HASTINGS.

All historians know that there is a great deal of mystery and uncertainty concerning the details of the ever-memorable battle on that fatal day, October 14, 1066. My puzzle deals with a curious passage in an ancient monkish chronicle that may never receive the attention that it deserves, and if I am unable to vouch for the authenticity of the document it will none the less serve to furnish us with a problem that can hardly fail to interest those of my readers who have arithmetical predilections. Here is the passage in question.

“The men of Harold stood well together, as their wont was, and formed sixty and one squares, with a like number of men in every square thereof, and woe to the hardy Norman who ventured to enter their redoubts; for a single blow of a Saxon war-hatchet would break his lance and cut through his coat of mail…. When Harold threw himself into the fray the Saxons were one mighty square of men, shouting the battle-cries, ‘Ut!’ ‘Olicrosse!’ ‘Godemitè!’”

Now, I find that all the contemporary authorities agree that the Saxons did actually fight in this solid order. For example, in the “Carmen de Bello Hastingensi,” a poem attributed to Guy, Bishop of Amiens, living at the time of the battle, we are told that “the Saxons stood fixed in a dense mass,” and Henry of Huntingdon records that “they were like unto a castle, impenetrable to the Normans;” while Robert Wace, a century after, tells us the same thing. So in this respect my newly-discovered chronicle may not be greatly in error. But I have reason to believe that there is something wrong with the actual figures. Let the reader see what he can make of them.

The number of men would be sixty-one times a square number; but when Harold himself joined in the fray they were then able to form one large square. What is the smallest possible number of men there could have been?

In order to make clear to the reader the simplicity of the question, I will give the lowest solutions in the case of 60 and 62, the numbers immediately preceding and following 61. They are 60 × 42 + 1 = 312, and 62 × 82 + 1 = 632. That is, 60 squares of 16 men each would be 960 men, and when Harold joined them they would be 961 in number, and so form a square with 31 men on every side. Similarly in the case of the figures I have given for 62. Now, find the lowest answer for 61.

Essentially, solve this equation:

61a2 + 1 = b2

Here is the C# code (basically, it counts through values of a, checking b with the assumption that b is essentially a * sqrt(61):


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;
using System.Diagnostics;

namespace Euler61
{
    class Program
    {
        static Stopwatch sw;

        static void Start()
        {
            sw = new Stopwatch();
            sw.Start();
        }
        static void Stop()
        {
            sw.Stop();
            TimeSpan ts = sw.Elapsed;
            string elapsedTime = String.Format("Hours: {0:00} Minutes: {1:00} Seconds: {2:00}.{3:00}",
                ts.Hours, ts.Minutes, ts.Seconds,
                ts.Milliseconds / 10);
            Console.WriteLine(elapsedTime, "RunTime");
        }

        // Brute force find a number, 61*x^2 + 1 = y^2
        //   Practically speaking, y = 8x
        //   Well, more like, y = sqrt(61)*x
        static void Main(string[] args)
        {
            Start();

            long b, a = 0;
            double guess, root = Math.Sqrt(61);  
            
            BigInteger bi_a;
            BigInteger bi_b;

            while (a >= 0)  // when a wraps around negateve, bail
            {
                a++;
                guess = a * root; 
                b = (long)Math.Floor((decimal)guess);
                bi_a = 61 * a * a + 1;
                for (long j = 0; j < 1; j++) // change j < 1 to j < 2 if no answer found...
                {
                    b += j;
                    bi_b = b * b;
                    if (bi_a == bi_b)
                    {
                        Console.WriteLine("61 * " + a.ToString() + "^2 + 1 = " + b.ToString() + "\n" );
                        Stop();
                        return;
                    }
                }
            }
        }
    }
}


Time to run and find the solution (on my system): 55.37 seconds.

Program output:

61 * 226153980^2 + 1 = 1766319049

Hours: 00 Minutes: 00 Seconds: 55.37

In the next installment we see about C++ and the mpir package. In the meantime, here are comments from Dudeney about the problem and solution in general (i.e., no brute force!):

129.—THE BATTLE OF HASTINGS.—solution

Any number (not itself a square number) may be multiplied by a square that will give a product 1 less than another square. The given number must not itself be a square, because a square multiplied by a square produces a square, and no square plus 1 can be a square. My remarks throughout must be understood to apply to whole numbers, because fractional soldiers are not of much use in war.

Now, of all the numbers from 2 to 99 inclusive, 61 happens to be the most awkward one to work, and the lowest possible answer to our puzzle is that Harold's army consisted of 3,119,882,982,860,264,400 men. That is, there would be 51,145,622,669,840,400 men (the square of 226,153,980) in each of the sixty-one squares. Add one man (Harold), and they could then form one large square with 1,766,319,049 men on every side. The general problem, of which this is a particular case, is known as the "Pellian Equation"—apparently because Pell neither first propounded the question nor first solved it! It was issued as a challenge by Fermat to the English mathematicians of his day. It is readily solved by the use of continued fractions.

Next to 61, the most difficult number under 100 is 97, where 97 × 6,377,3522 + 1 = a square.

The reason why I assumed that there must be something wrong with the figures in the chronicle is that we can confidently say that Harold's army did not contain over three trillion men! If this army (not to mention the Normans) had had the whole surface of the earth (sea included) on which to encamp, each man would have had slightly more than a quarter of a square inch of space in which to move about! Put another way: Allowing one square foot of standing-room per man, each small square would have required all the space allowed by a globe three times the diameter of the earth.

Part 1 of 3: Doing Large Integer Math with Visual Studio 2010 in C# or C++

If you want to work on Number Theory problems, or Diophatine Equations, you need a math package that allows you to use large integers (MATLAB, e.g.). Optionally, you need to encode your ideas as programs and test your theories the old-fashioned way, with Fortran or some other language. I prefer C++ (it’s the language I have been using for 20 years now). To that end, I want to show you how to use Visual Studio 2010 to build a C++ program to work on large integers. As a bit of a bonus, I’ll also show how to do the same thing in C#.

For fun, we’ll write a small program to verify an old Pell’s equation (which is a kind of Diophantine Equation) where the answer has been given by by Brahmagupta and then Euler. The equation is:

61x2 + 1 = y2

Our goal is not to study the math of Pell’s equations, but to plug a large integer package into your Visual Studio. So I will show you all the steps you need to follow to get this done in a Windows environment using C++ (Section I) and C# (Section II), and then we’ll see about Euler’s answer (3,119,882,982,860,264,401).


Section I — C++

Step 1: Download the large integer math package. We will go to Brian Gladmann’s site, and read about the packages, then go to the Multiple Precision Integers and Rationals page and download the latest source tarball (which happens to be version 2.2.1 at the time of this writing). The version won’t change the code, you’ll be able to use the same C++ code no matter which version you get. At the risk of adding confusion: MPIR is a Windows-port of the GMP (GNU Multiple Precision Arithmetic Library).

Step 2: Decompress the package (I use WinRAR for tarball files, but find something on the internet — something free! — and install it on your machine).

Decompress the file to some location on your computer, let’s say c:\projects\ (for the sake of of discussion).

Step 3: Launch Visual Studio 2010, and load the build file you just decompressed. In our sample case, the 2010 build file would be:

c:\projects\mpir-2.2.1\build.vc10\mpir.sln

Step 4: Build the dll_mpir_gc project.

Screen shot of visual studio

The results (in the sample case of c:\projects\) are in this directory:

c:\projects\mpir-2.2.1\build.vc10\dll\Win32\Release

All the .h files you need, the libs, and the DLL are there.

Step 5: Now we get to use the results! So, create a new blank console application project and name it something related to the problem we are going to solve. We are going to use the results of the above steps which means you’ll place c:\projects\mpir-2.2.1\build.vc10\dll\Win32\Release in your include directory and in your library linking path. Next, you’ll link in the library mpir.lib. The header file you will include is gmpxx.h. For more about this file and the C++ objects in it, go to the gmp site.

Step 6: Create a C++ file in your project with the following code,



#include < stdio.h>
#include < stdlib.h>
#include < gmpxx.h>
#include < iostream>

using namespace std;

void main(int argc, char *argv[])
{
     	
   mpz_class answer_a = 226153980;
   mpz_class answer_b = 1766319049;
   if ((61*answer_a*answer_a + 1) == (answer_b * answer_b))
	cout << "Euler was right!\n";
   else
	cout << "Oooops.  My math package has failed me.\n";

}

Notice that instead of using int or long, we now use mpz_class. Everything else is as expected.

Other large integer tools exist (OpenSSL comes with a BigNum package that is quite nice -- you'll have to build it with the help of some tools I provide in an early article). Of course, the list of tools is impressive, my goal here was to show you a free C++ method that fits within your life easily (if you are a Visual Studio users).


Part II -- C#

Using Big Numbers in C# (.NET 4) is as easy as adding a reference to System.Numerics and then using BigNumber.

But there is also a BigRational which you can use by hooking C# into F#. To use BigRational, follow these steps:

Step 1: Install the F# PowerPack tool which has the big number class we'll be using. Get PowerPack here:

http://fsharppowerpack.codeplex.com/

Download this package and install it on your system,

You need to install F# PowerPack

To be fair, this will make my comments here "dated", for I predict that Microsoft will move the F# code we care about out of PowerPack and put it somewhere else (probably in the F# core). Anyway, for now it is in PowerPack.

Step 2: Add a reference to the PowerPack into your C# project.

Right click on "References", and browse to the PowerPack (in your Program Files\FSharpPowerPack directory:

Drill down into the bin directory, and select FSharp.PowerPack.dll

Step 3: Use FSharp.Math in your program. Now that you have added a reference to the PowerPack, you can use Microsoft.FSharp.Math via the "using" clause in your C# program as follows:

Writing a C# program to use BigRational or BigInteger:

Having followed the above steps, our C# program looks like this:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.FSharp.Math;      // gets us BigRational
using System.Numerics;            // gets us BigInteger
namespace ConsoleApplication1
{
	class Program
	{
		static void Main(string[] args)
		{
			BigInteger bi_a = 226153980;
			BigInteger bi_b = 1766319049;         // one way to do it...
			bi_b = BigInteger.Parse("1766319049"); // or do it this way
			BigInteger sq   = bi_b * bi_b;
			if ((61 * bi_a * bi_a  + 1) == (bi_b * bi_b))
			{
				Console.WriteLine("Euler was right!");
				Console.WriteLine(sq.ToString());
			}

			BigRational br_a = BigRational.FromInt(226153980);
			BigRational br_b = BigRational.FromInt(1766319049);

			BigRational br_answer_a = BigRational.FromInt(61) * br_a * br_a + BigRational.FromInt(1);
			BigRational br_answer_b = br_b * br_b;

			if (br_answer_a.Equals(br_answer_b))
			{
				Console.WriteLine("\nEuler was right again!");
				Console.WriteLine(br_answer_b.ToString());
			}
		}
	}
}

You should see the output that Euler was right. If you don't something went wrong in the code or in one of the steps.

In Part 2 and Part 3 I compare C++ to C# in terms of speed. I also explore more about the historical background behind our sample problem (61x2 + 1 = y2).

My Diophante-Quest: Fermat’s Last Theorem and Integer Math

I originally started this site for my exploration of this subject. My first articles were on the subject of Diophantine equations, and a report on some software I had written in my quest. But then the site got deleted (my own fault), and it has taken me a very long time to rewrite those original articles. This is the original article (or, more like the original idea that stood behind that first article).

My daughter’s middle name is Diophante (being the feminine form of Diophontus). I named her after the father of algebra, and more particularly, after a certain class of mathematical problems having to do with integer based polynomials (Diophantine Equations). My interest in that class of problems and number theory in general, goes back to high school and hearing about Fermat’s Last Theorem. Fermat was reading Diophantus’ book, Arithmetica, and he made a note in the column that he could prove the following statement (but that the book’s column was too small to contain it):

It is a little statement, and the fact that Fermat casually noted that he had a proof (which was never published) combined to make this a tantalizing problem. Fermat wrote this:

It is impossible for a cube to be the sum of two cubes, a fourth power to be the sum of two fourth powers, or in general for any number that is a power greater than the second to be the sum of two like powers. I have discovered a truly marvelous demonstration of this proposition that this margin is too narrow to contain.

Fermat did not have a proof, we think, since he later gave proof for the more specific case of n=3 — which he would not need to do if he had a general proof for all n > 2.

When I found out about this theorem and Fermat’s claim, there still was no known proof, so I started wrestling with it myself, and I even went and got a math degree (partly inspired by the problem and others like it). Of course, I am an amateur (for sure), which may explain why an unsolved problem has so thoroughly drawn me in.

But then it was proved — rather recently in fact — yet the proof is so large that not only could it not fit in a margin, but the number of mathematicians who have studied and verified the proof is quite limited.

But my interest in the field of integer math and number theory and Fermat’s Last Theorem and Diophantine Equations was not cooled by the discovery of a proof. Rather, it has been the basis for looking at many related problems, and wondering still (and looking still) if a more intuitive proof is available. In my Diophante-Quest, if I may call it that, I have found many wonderful things about integers and prime numbers. One I will share with you now, and let you download for yourself.

I wrote a program that looks for patterns on the integers (download it here). I knew that two squares could be added into a third square on the integers — that’s the whole idea of Pythagorean’s theorem, as you may recall. Extending the pattern, could three cubes combine to make a cube? Fermat and Diophantus said that two cubes can’t make a cube, but can three cubes make a cube? So I wrote the above program to go hunting for me. The results were quite interesting. The first answer to roll in was this one:

That’s fantastic. And so I share the program with you (you need to go to Start -> run -> cmd and use the cmd window to use it — it is a windowless program). This program opened up the world of what I was later to find out was named Equal Sums of Like Powers, and I found that a certain Jean-Charles Meyrignac has done much research in this area, and his web site is full of findings.

The order behind these kinds of equations has captivated many. When Diophantus died, a riddle was written in his memory — can you solve it and calculate how old he was when he died?

‘Here lies Diophantus,’ the wonder behold. Through art algebraic, the stone tells how old: ‘God gave him his boyhood one-sixth of his life, One twelfth more as youth while whiskers grew rife; And then yet one-seventh ere marriage begun; In five years there came a bouncing new son. Alas, the dear child of master and sage after attaining half the measure of his father’s life chill fate took him. After consoling his fate by the science of numbers for four years, he ended his life.’

It seemed fitting to name my daughter after such a compelling and captivating subject. Diophante is her middle name, which gives a second twist, for it leaves her middle initial, D, and her last name to combine to be that which one does in Calculus (but that’s a different subject, and what I have to say about it won’t fit in the narrow margins of this post). More relevant to who she is, Diophante roughly means “from God, torch-lighter” or “fire starter from God”. All told, her name combines to speak of “Grace as fire from God”, or “Grace, fire-bearer from God.”

Difference of squares and cubes and anything else

Following on my last installment, I got to thinking about the difference of squares. First I noticed the relation: a2 = (a-1)(a+1) + 1. Which is not far off (a-1)(a+1) which is a2 -1 written as the difference of squares. And I happen to know that in Algebra II, factoring the difference of squares often throws off kids who don’t think of 1 as a square.

So, can I take my last formula and do the same thing for other squares (besides 1) and other powers. The answer is yes, and here it is:

Difference of Exponents

Difference of Squares, Cubes, etc.

This pattern is easier to remember than the formula for difference of cubes:

a3 – b3 = (a-b)(a2 + ab + b2)

But instead of that, think of this:

a3 – b3 = (a-b)(a2b0 + a1b1 + a0b2)

And there you see how easily I came to the above generalization.

Here is a little C++ program that runs this formula:



#include < stdio.h>
#include < math.h>
#include < stdlib.h>

void diff(int a, int b, int n)
{
	// Find a^n - b^n
	double sum = 0;
	for (int i = 0; i < n; i++)
	{
		double val = pow((double)a,i) * pow((double)b, (n-1)-i);
		sum += val;
	}
	sum = (a - b) * sum;
	printf("Answer: %1.0lf\n", sum);

}


void main(int argc, char *argv[])
{
	if (argc != 4)
	{
	  printf("Usage: Exponents A B N\n");
	  return;
	}

	int a = atoi(argv[1]);
	int b = atoi(argv[2]);
	int n = atoi(argv[3]);
	diff(a,b,n);
}


Exponent Math

The sum of the first n number is n * (n + 1 ) / 2 — which is half the area of a square plus half the diagonal added back in. I first noticed the relationship to a square when putting away my dominoes one day. But Gauss is famous for noticing that the sum of the first n numbers is like adding the first and the last one n/2 number of times.

The sum of

1 + 2 + 3 + … + 98 + 99 + 100

is found by adding the outer numbers (100 + 1) and then moving in (99 + 2) then moving in again (98 + 3), etc. Gauss noticed that 100+1 is the same as 99+2 which is the same as 98+3, etc. That’s how he came to his formula for the sum of the first n numbers: (n + 1) added n times, and half of that.

I just noticed (and should have noticed long before) that the sum of the first n binary numbers is one less than the nth binary number. My extension at work is 255, which most programmers will notice to be the binary number 1111111; and converting between binary and decimal, we know that 255 is the sum of the first 7 binary numbers (2^0 + 2^1 + 2^3 + 2^4 + 2^5 + 2^6 + 2^7).

And that got me to thinking of a general solution of the sum of the first n exponents for any number x (where x and n are > 0). By observation (doing this on powers of 3, 4 and 10), here is what I came up with:

Sum of the first n exponents of x

This is not new, of course, just worth restating.

Create XML from Excel

When working with MS-SketchFlow, you may want to use their Sketch Datagrid. And with version 4 of Expression Blend, you can associate that grid with an XML source. If your data is in a table format, put it in Excel, save it to XML, then load that XML into SketchFlow. This is the best video (i.e. shortest video) I found on getting XML out of Excel — it works for Excel 2010 as well as it does for the Excel 2003:

Note: In Excel 2010, you need to turn on the display of the main Developer tab so that you can see the XML options. To turn on the Developer tab in the ribbon bar, go to File, Options, Customize Ribbon, “Choose Commands From:” Popular Commands, then in the left column, click [x] Developer.

Build a dynamic newspaper site, quickly and free

A local paper needed a web site. After two calls to set up a face-to-face meeting (and we met today for just one hour), I got all the business requirements. The same day they had their site. Here is the story.

Business Requirements:
They needed a server, a user management system (able to add admin, editors, authors, subscribers and readers), a content management system — a newspaper is content based! — with the ability to create dynamic articles, posts, pages, images, menus and all the rest, and a way for ads to be sold (papers generally make their core income from ads). So there was the challenge, but with two important constraints:

Constraint 1. Cost:
Small-town papers are business with budgets. How much would such a thing cost? The newspaper owner had shopped around, contacted some developers, got bids, and the prices were unreasonablly high.

Constraint 2. Speed:
The site needs to be up pretty quickly. The sooner it goes up, the sooner ad space can be sold.

Solution:
Wordpress. I know this sounds like an add, but I was so pleased with the results, it seemed right to share with others the steps on how to do this.

1. Get space on GoDaddy (this is not free, so there is a little cost to this venture)
2. Use GoDaddy to get email address and a MySQL database (need that database to store the content)
3. Install WordPress as the root of the site
Note: I use Firefox’s FirtFTP to get the files up to the GoDaddy site
4. Get a Newspaper theme (installing WordPress themes is an enjoyable process, so do some shopping).

Done.

It was that easy. We then created some basic newspaper categories (WordPress runs off of Categories), and now the system is up and ready for the staff to add content, and they don’t need me–they can manage it on their own. So a bonus in all of this is that they are not tied to a development staff or a developer.

What is Capitalism Anyway?

Some people use the word ‘Capitalism’ so easily, that I wonder, Do we even have a good working definition? The reason I ask is because I have a good many friends who are sincerely suspicious of the idea (often pointing to greedy people getting more money for themselves to spend on themselves…). I am starting to think I have as many friends who question the principles of Capitalism as who prefer the idea of a pure democracy over and against a Republic. So, what is Capitalism? Check out this really old video to see some pretty relevant ideas:

Supreme Court narrowly rules that the Bill of Rights governs States

Does the right to bear arms amendment restrict Federal authority only, or does it also restrict States? One State argued that the 2nd amendment does not trump their local laws — the right to bear arms clause limits the Federal government, but it does not limit what they themselves can rule. I am sketching this information from reading the Supreme Court case itself. Read especially pages 1 – 2 for a sense of the case, but note pages 27-29 for some well rehearsed history facts.

What struck me was the narrow vote. The court ruling today was 5 to 4 in favor of the Federal amendments having the force of State law.
Continue reading

Use a 6-sided dice as a 4-sided or 5-sided dice

In my previous posts on this subject, I have show how to use a 6-sided dice to create a 2-sided, a 3-sided, an 8-sided or even create a 12-sided dice. Today I will show how to use a 6-sided dice to create a 4-sided or 5-sided dice.

Turn a 6-sided dice as a 5-sided dice:
Roll the 6-sided dice, and if you roll a 6, roll again. Do this till you roll a value between 1 and 5. Pretty simple.

Turn a 6-sided dice as a 4-sided dice:
Method 1:
Roll the 6-sided dice, and if you roll a 5 or 6, roll again. Do this till you roll a value between 1 and 4. Pretty simple.

Method 2:
Roll a 6-sided dice. The top of the dice will be ignored — we care about the four sides, not the top. On the four sides there are four values. The lowest value maps to 1, the second lowest value maps to 2, the next highest value is 3 and finally, the highest of the four values is 4. Whichever is facing you is the roll (just map it to the range 1..4). Rank the side facing you among the four sides, and you have created a four sided dice from a six-sided one. Note: If a side is not facing you squarely, turn the dice to the left so that the that side is facing you squarely.

For example, let’s say you roll a 6-sided dice, and the top face showing is the 5. That means that the four sides are { 1, 3, 4, 6 } — and the value of 2 is on the bottom. Of the four sides, one is most facing you. If it is the 6 most facing you, then your answer is 4 because 6 is the 4th of the four numbers on the four sides; it is the largest of the four side values, which are: {1, 3, 4, 6}.

Your spine wasn’t meant to stay for long periods in a seated position

When did humans start sitting down for 9 hours a day to work? For thousands of years humans were hunters, gathers, farmers, carpenters, and so forth. Then the industrial age hit, and then the advanced computer technology era came, and now many of us find out that we sit all day long. And we may sense that all is normal. So please ponder with me, were humans designed to sit all day at work? An April 29, 2010 article from Bloomberg Businessweek makes the case for standing at work.

Maybe this is true: the idea of “comfortable sitting has come from the chair industry.”

Many years ago, I found that I focused better if I stood to read a book. This seems to apply to all my activities. An early Egyptian scribe famously complained of the pain of writing and the bent over sitting position. Perhaps standing would have helped! The picture here shows how I stand while writing software. This is not an inexpensive desk — if I can call it a desk — but it pays for itself in various ways.

Axis and Allies Ti-83 Program

I bought the Axis and Allies starter kit (the exact one shown here).

I wanted to play with my younger kids, but I found that the dice rolling was too time consuming and cumbersome. So I wrote a Ti-83 / Ti-84 program to manage all the vehicles and soldiers and their damage, dice and speed. That is, I took everything about each tank and soldier (as defined on their corresponding cards) and I put them into the calculator. I then put all the attack / casualty and defensive fire rules into little programs that use the data. In this way, you can play the starter game with your youngest kids. They only need to think about the objective of the game, movement and what they want to fire upon during each phase.
Continue reading

Ti-84 Risk Game

I have some friends who play RISK regularly enough that they decided to write a C# program that speeds up the game for dice rolling. Just enter the number attacking and the number defending, and the laptop tells you who won. Great idea! So, I thought it would be great to write the same kind of app for a TI-84. That way, the calculator can be passed around to each player, and they can manage the dice.

I wrote this on the TI-84 Plus Silver edition, but it should work on the TI 83. I copied the code over to my computer through the USB link. I spent a few hours writing it, and I didn’t want my son to delete it as he is programming the same device — so I backed it up to my computer and I thought that other people may derive some pleasure from it. So here is the binary version. And following is the text version:

Continue reading

SQL Express Server 2008 and the Upgrade to Silverlight 4 RIA

In the past two articles, I explained deployment of a 2010 RIA application and my upgrade from Silverlight 3, VS 2008 to Silverlight 4 on VS 2010. Here is a gotcha: When you upgrade to VS 2010, you also get the latest free (Express) SQL Server 2008 — which will replace your earlier SQL Express Server 2005. In this case (in the case you had an earlier 2005 edition), you need to go back and uninstall SQL Express Server 2005 and download and reinstall SQL Express Server 2008 (that is, if you want to run the SQL Server Management Studio / Management Console — used to view your databases).

Now this all sounds very easy… but there are two steps you need to take:

1) Install Windows Power Shell (the Express SQL Server 2008 installation program requires it).

2. Manually do extra steps to uninstall SQL Express Server 2005. There is a trick you need to know about to fully uninstall the Express SQL Server 2005. And that is why I am writing. Namely, you need to remove the registry key at: HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\90

Hope this helps!

Convert Silverlight 3 (VS 2008) to Silverlight 4 (VS 2010) – RIA

This is my conversion experience. I hope it is of some assistance to you — and, I must say, the link to the DOCx file is essential for your efforts.

Scenario:
I have a Silverlight 3 RIA application built with VS 2008. A few weeks ago (I think it was April 14, 2010) Microsoft released the next official version of Visual Studio (2010) and with it, .NET 4 and Silverlight 4.
Continue reading

Siliverlight 4 .NET 4 RIA Deploy

Install Visual Studio 2010 and the Silverlight 4 Tool RC2. Create a new project (Silverlight Business Application). Build the application.

Buy space on an ASP.NET 4 enabled IIS7 server (I used two providers, and it was only through Discount ASP.NET that I had success getting my new Silverlight app installed and running).

So far so good. Right?

Well, not exactly. You will get an error complaining about LocalSqlServer (this is where Fiddler — see below — helped me the most, but more on that later). I won’t explain the error, I want to explore the solution.

Using everything out of the box (as I have described here) is not sufficient. And there are two reasons: 1) Software Problem: The Web.Config file you have (which was added to your project for you) won’t work; and, 2) Server Problem: Your IIS7 server is not properly configured.

Continue reading

DOS Batch Program to Parse Strings

A friend asked me to write a script that will tell how much space is used in a directory. Using the Microsoft CMD script (the batch program) the answer follows. This cmd script demonstrates three important ideas:

1) Recursive function calls in a MS-Windows OS batch file
Namely, we use the “for /D” command to walk the directory structure. A function is called with the “call” command, and it exits with “goto:eof”

2) The use of the “for” command to parse the output of a program
Namely, near the bottom of the file there is a :DIRECTORY function. DOS bat / cmd files don’t have access to GREP, but they can use FIND. We pipe the output of the dir command to the find command and then token-ize the output and store it in variables.

3) We use the SET /A command to do basic math.
As we determine the used space of each directory, we add it up.

Continue reading

Robot Wars

I have not played Robot Rally, but it looks fantastic. Each player programs a robot each turn, then all the robots execute the instructions at the same time. I was at the game store and the price of Robot Alley was $50. I did not buy it. Instead I invented my own free version that I give away here.

Here is what you need to play my version:
1. Download the single page PDF — again, it is free, it has the rules and movement cards
2. Find some cars, little people or action figures around your house — these are the robots
3. Locate a tiled floor or surface that has regions

I have play tested it with my kids. Pretty fun, and you can make up your own rules and pieces.

How to roll a 6-sided dice once and generate a number from 1 to 8

One roll of a six-sided die can be used to generate any number from 1 to 6 (with an equal chance for each of the six). Likewise, I found a way to randomly generate any number from 1 to 8 with one roll of a six sided die (with an equal chance for each of the eight). When you roll a six sided dice, you will be able to see three faces and three faces only — the top and two sides. That is, don’t move from where you sit, and you will be able to see three sides! Of course, if you move around, you can see the other sides. I am talking about you, the dice roller, keeping your head still.

From where you sit (and not moving your head), observe the three faces you can see. Add up the numbers from the three faces you see, and you will get one of the eight possible sum totals:

6
7
9
10
11
12
14
15

For example, if you see faces with the numbers 6, 5 and 3 then your total is 14. If you see 1, 4 and 2 then your total is 7. All that is needed is a way to map these eight possible sums to the numbers 1 through 8. For that, I have the following table:

1: 11
2: 12
3: 9
4: 14
5: 15
6: 6
7: 7
8: 10

If the sum of the sides is 10, the value you generated is 8. If the sum of the faces is 14, then the value you generated is 4. There is pattern here: generally, the last digit of the sum is the value generated. For example, 11 has 1 as the last digit, so 11 maps to 1. If your faces add up to an 11, you rolled a 1. Likewise, 14 has 4 as the last digit, and hence maps to 4. The only exceptions are 9 (which maps to 3) and the sum of 10 which maps to 8. All the other numbers map nicely to the last digit. Note that 3 squared is 9, so that may make it easy to remember. And 10 is the only number left with nothing to do, so corresponds to rolling an 8.

Edge Cases
What if you can only see two faces on a roll? This is a case where the dice lines up squarely in your vision. In this event, lean slightly to the right and pick up the third face — the key here is that you always lean to right as a rule. Because it is a rule, you are never preferring one face over the other.

Prove It
Each of the eight values are equally likely to show up because there are eight corners on a cube. Each of those corners has three faces touching it. Our random number generator — using a six-sided dice to generate values 1 to 8 — works because we are rolling in such a way as to access one of these eight corners. If we rolled so that the 2 is showing on top, we will see two more faces (to the left and right): either {1 and 3} as the two sides, or {3 and 6} or {6 and 4} or {4 and 1}. In this case, each corner has a unique sum, and each corner can turn up in one of three ways. Following this method, every possible combination for all possible corners was listed and shown that all eight are uniquely matched to a particular sum, and each is evenly distributed.

Your six sided dice is many sided! See my other post on how to roll a six-sided dice to get other random values. All told, a six sided dice can be used as a 6-sided, an 8-sided, or as a 12-sided dice, or as a 3-sided or a 2-sided dice. Can you discover more?

Steve

Playing Cards without a Deck of Cards

This is Part I of my Head Games system of card playing. It is a system for card games using a standard deck of cards, yet played without an actual deck.  I am developing the system, and decided to present it now and see what others are doing and if I can get ideas for expanding what can be done with this.

Stated Simply
Is it possible to play cards without cards?  The answer is yes! I will show you how to work with a random deck of 52 cards, and give a way of selecting cards from that deck with any number of people playing.

Continue reading

11 Ways to Make Your Brain Stronger

Our brains can be exercised and can improve through the right methods. We can change how we think, and we can improve our capacity to remember.  And there are definite techniques that can help. There are secrets you can learn that really do work (and I am not selling anything!).

Are you skeptical? Don’t believe me? Well, you may not be alone in your skepticism, but new tools, old tools and new studies all point to one wonderful reality: We can train our brain. We can work it out as in the fitness center, and come away with more strength.

Continue reading

Marxism, Part III: Flash Video Presentation

One of my professors, Dr. Freddy Cardoza, led part of a PhD colloquium where we discussed Marxism and the writings of a neo-Marxist, Stephen Brookfield.  I have been quite impacted by Dr. Cardoza’s assignments. He facilitated the synthesis of various realms and then pushed me to consider more deeply our government, educational reform and political theory.

Flowing out of those lectures is this three part series. In Part I, I analyzed Brookfield’s, Developing Critical Thinkers; there I was rather rough as I challenged lazy and unproductive pseudo-intellectualism. In Part II, I gave a somewhat tongue-in-cheek summary of the ten-points of Marx’s Communist Manifest.
Continue reading

Connections between Thought Realms

Computers can be programed to sift unstructured texts in order to find connections.  If you want to connect two realms of thought, you need data from both realms. You should also have a theory on how to connect the realms. With a fast computer, and the right software, there is a chance to find discoveries between realms of thought. I worked in the stock market trying to find relationships between one stock going up, and another following (tracking stocks). If I could show that Harley Davidson stock prices went up and then Wal Mart stocks followed, I could help investors make money.

Using similar techniques, I seek to find connections in literature, history, culture,… you name it, a link is valuable. With all the data available on the internet (electronic books especially), we are going to see a new era of data mining and connectionism. The book to the left is an invaluable introduction to the topic. I found it while doing research at Reuters on how to connect News Stories to stock movements.

I have been especially interested in applying these ideas to the ancient texts of Egypt, Israel, Assyria, Rome, etc. For example, in the Egyptian Amarna letters, unique phrases appear that also appear in Malachi and Isaiah. There is a connection (at least linguistically) between documents across languages. Finding such connections, and then pointing them out to a researcher, is the work of software.

That is the software I am proposing. The requirements are these: 1) large quantities of ancient texts that may relate at some abstract level; 2) fast computers and 3) advanced algorithms that find connections. The first two are easy to get and the third one is the trick. I will elaborate on all three and suggest a way forward:

1) Large quantities of ancient books stored electronically are readily available from Logos

I have been using Logos for years, and my collection of ancient texts has been growing (I have to purchase each book I unlock). In addition to the Logos collection, I have 1400 Ugaritic tablets along with software that I wrote to display and use them.

2) Fast computer chips and memory are ubiquitous
With the advent of personal computers, and now cloud computing, the ability to process large amounts of data is as close as the least expensive laptop. Computing power is at a point where this kind of project is feasible for the hobbyist. A modern laptop rivals the computing power of earlier super computers and older mainframes.

3) Logos has provided a programming interface to access their LARGE collection of books.
As a software programmer, I need an interface that allows me to access the above mentioned books. They are in a proprietary data format — one not easily accessible. The good news which prompts the writing of this article is this: The folks who provide the important e-books also wrote an interface for programmers. Their interface is freely available and documented on their web site. This means Windows software can be written to sieve, process, connect and collate realms of thought.

This post is the first installment of a series where I will chronicle the use of Logos’s programmer’s interface. I am talking about the start of an ambitious software project — software that gets into Logos’ massive collection of books. As with all of my software experiments, look for scaffolding-like tools to start appearing on my web site. I have written extensively on this subject of connectionism in the past. Specification documents have already been generated along with basic design.

The steps before me are these:

1) Learn the application interface for the Logos system. This will mean sample software; help exists.

2) Implement connectionism algorithms as per the above mentioned book.  Some of this has been written. Earlier excursions have yielded wildly different applications. One software tool connects the Hebrew Old Testament to the Greek Old Testament and finally to the Greek New Testament while another operates on the periodic table of elements.

Limitation: Time. I don’t have any free time to dedicate to this project. It will be slow going. Other software projects take priority (even as they are related).

Steve Rives
Kansas

The 10 Points of Marxism (Marxism: Part II)

Read Part III.
Read Part I.

Karl Marx and Friedrich Engels wrote a short work called The Communist Manifesto. It is a manual for Marxism. About half way through, there is a 10 point summary. I list those ten points below with comments related to their application in America.

First, however, I need to add a qualification: I am banking on God in Christ, and not America. I don’t analyze America and Marxism as if I think that the USA is somehow the center of God’s redemptive plan for a climactic future. I care about my country, but my affections are elsewhere.
Continue reading

All the gold in the world is not that much gold


“In all of history, only 161,000 tons of gold have been mined”, National Geographic, Jan 2009 (52).

At $950 an ounce, that puts the total value of all the gold in the world at a little less than $5 trillion dollars.

So, how much space does this $5 trillion take up? “Barely enough to fill two Olympic pools.”

All the mined gold in the world would fill up two swimming pools.

That’s it. And what does gold add to our lives? Well, it is used in electronics, dentistry and industrial processes. In 2007 such functional-usage only accounted for 12% of the gold used that year. The dominating use was for jewelry; the distant second-place use was investments — exchang-traded funds, coins, medals and bars.

I would think that in the technological age, we would have abandoned our unnatural passion for one metal, “Humankind’s feverish attachment to gold shouldn’t have survived the modern world” (42). Our parents have not recovered from their parent’s attachment to gold, and we likewise share in their affections. Gold grips the world. Two swimming pools filled up with jewelry are worth more than the budgets of entire countries.

How do we get more gold? From workers toiling in the mines. In some places, whole families — including children laborers — eek out their living from digging for gold. In economically depressed regions, illegal digging leaves miners poisoned from the mercury left over from the processing. The illogical cost of gold is punctuated by the illogical use of life to obtain it.

As the years pass, the price of gold will go up and we will pass along our understanding of gold to our children. The next generation will inherit from us a passion for gold and meaninglessness (despite the meaning we assign). Human life is easily identified with trivialities. The worth of a body is easily reduced to its ability to obtain more pliable metal for the rest of us.

Gold may be the emblem for the human inability to rightly value goods and men. If not, then diamonds are that emblem. But gold has something over diamonds; it is considered an official standard for money systems. And for that, we have the great mathematician, Sir Isaac Newton, to thank.

Newton, who invented Calculus, was also the Master of the Royal Mint. As warden of the nation’s money supply, he switched the British monetary system to have gold as its baseline or standard. America followed this move nearly a hundred years later. Newton’s choice was logical since gold was valued in all countries. His move expanded trade and promoted a new period of economic growth that spanned the globe. And he did this simply enough by tapping into a kind of religious sentiment: the cross-cultural devotion to gold.

It was Newton who wrote The Principia. In that book he taught the world to attribute movement and motion to inherent properties embedded within the objects that move. Lightning falls, he argued, because of processes that can be measured and explained. A natural event is explained by the nature of the objects involved in the event. Change, movement and motion became subjects for a new philosophy of observation and recording, and no longer belonged to the realm of religious institutions, clerics and priests. Mass, weight and size — not Zeus — explain the natural order. That is, if a scientist could understand that an object is influenced by other objects and that inherent mass affects gravitational phenomena, then that would explain why an apple falls or why planets orbit. Newton was helping us to step away from medieval darkness and into scientific enlightenment. Science, not superstition, was the basis for a new kind of rational thought.

And that takes us back to gold. It was Newton who conducted the frontal attack on the religious mythologies of his time, and ironically, it was the same Newton who tapped into the irrational power of gold. In the preface to his Principia, he lays out plainly that the union between the gods and mankind cannot be a standard for interpreting events. But later, he capitalized on the irrational human devotion to gold. Gold was the stuff of the gods — the substance of shrines, statues and sacred spaces — and under Newton it was to become the standard for the economy.

In this way, Newton helped us to keep our god, he just moved it to a more rational temple. The ancients may have worshiped golden calves or deities that lived along the Nile, but the Enlightenement unshackled us from such backwater superstition. If we do have statues, we are at least smart enough to have the bronze bull of Wall Street and not some impotent golden calf.

The Day the Universe Changed

When change happens — change that we adopt as a culture — it updates the features of our society. In fact, change itself is part of what defines us. New features become part of our lives and then refocus our view of the world.  For example, the discoveries of science shape how we think and interact with our environment. How would we understand life and society without the intimate experience of light bulbs, cell phones, glasses, jet planes, televisions, guns and laptops? To name just a few.

James Burke is the master of developing the ramifications of change, technology and the attending impact on our beliefs and actions.  When I was 15 he came out with a ten-part series of shows titled The Day the Universe Changed.  And I was changed.   I forgot how much his work impacted me.   I was reflecting on his presentation style and his ability to connect information and I realized that in my own PhD work I am mimicking him! Certainly not consciously, for it just occurred to me that such is the case, but the case none the less.

I have a high regard for Dr. Burke and want to direct you to the foundational series on You Tube:

That is only one of his videos. Many of his episodes are viewable on YouTube (search there for, “The Day the Universe Changed”). A research project he leads is Knowledge Web. Finally, I would be terribly remiss if I did not direct you to the excellent series that started it all: Connections.

I used to sit with great awe and soak in this material. Based on a fresh review, I assure you that it has not lost its power.

Steve Rives
Louisburg, Kansas

Is God a Mathematician?

Mario Livio may have written the book I wanted to write (if I had the ability and knowledge — which I do not), Is God a Mathematician? I have come at the subject as a student of math, a student of the scriptures, and a practitioner in the Christian School movement. I have lectured on this subject multiple times — primarily at the National Association of University Model Schools (NAUMS), but also as a math teacher. It happens to be one of the core topics that caused me to launch this blog (touching, as it does, simultaneously on math and theology), so I was amazed to see a book written directly to the subject has long held my attention.

While standing at the bookstall I read a few pages from the opening and concluding chapters. So I can’t say with any certainty that this is the book I wanted to write. It may end up being otherwise, but from first impressions, it is worth a serious read.

What I can tell is that Livio deals with a major question that the Christian school movement may want to discourse about (hence my lectures at NAUMS). Namely: Is mathematics discovered or invented? That question, I believe, relates to how a person thinks about humans and about divinity. To ascribe to God the things that humans invent is not to be lauded. However, the tendency is precisely that — to say that God invented math, and then we discover it. Of course, God may have invented math — but that is the question being explored. If he did not invent math, we may be making a mistake by ascribing to him what rightly should be ascribed to us.

Continue reading

A Free OpenSSL Visual C++ Object: Part 2

This is Part 2 in a series about integrating OpenSSL into an existing C++ project.  In Part 1 I presented a scenario that would necessitate such integration and I outlined the contours of the problem.  

In essence, the goal of adding OpenSSL to a project is to add the “S” to your C++ based HTTP server — thus getting you an HTTPS server.  I wanted to use this second post to give source code, but before that I need to step you through the install and build process of OpenSSL.  In a future installment, I will present the C++ object which will be downloadable.  

This seris is made possible because of the graciousness of Power Admin; the final project will be available on their web site.  Included in that release are the scripts for Certificate use and generation via a Certificate Authority.  

Continue reading

Adding OpenSSL to an existing Visual C++ Socket Program in C++

Your boss comes into your office and says she wants to support encrypted communications over your HTTP server. She wants your company web site to use HTTPS instead of HTTP. Among other things, they need to handle credit card transactions and the encrypted transmission of user information across the internet. And she wants it written in-house and integrated into the current C++ code base.

If you have been assigned such a task, I am writing for you.

In the next series of articles, I am going to show you how I started with scant knowledge of OpenSSL and wrote a C++ object that allows one to slap SSL (a Secure Sockets Layer) on top of any existing Visual C++ socket code. By the end of this series, I am going to give you the source code.

Continue reading