Tuesday, December 25, 2012

Fish, etc!

This fisherman's blog: http://blog.goo.ne.jp/heiun is rather interesting. It's an advert for the fishers, but still enjoyable.

Saturday, December 22, 2012

Three groups that you've never heard

Have you ever been listening to random CDs and have some things just come and mesh together? Try these:
The Free Design -- Kites are Fun
Sweet Trip -- You will never know why
Spiritualized -- Ladies and Gentlemen We Are Floating in Space

I hear "The Free Design" in Stereolab and Koop. Excellent, it is all excellent music.

Wednesday, December 19, 2012

People are crazy.

Remember law school? I do not. I do remember my classes on US constitutionality.

I have never heard a good argument against weapons. I mainly believe that it is a question of personal responsibility. I have the ability to make explosives, but I chose not too. I have the ability to make nerve gas, but I chose not to. I just do not believe that a few murderous outliers represent the American populous as whole.
I had to dig in the back of my closet for my essay on this, but I found it. Marguerite Anne Bowers was killed with a blade by Thomas Vanda who was a "schizophrenic in remission". A subset of the ruling follows:

Bowers v. Devito
UNITED STATES COURT OF APPEALS FOR THE SEVENTH CIRCUIT

But there is no constitutional right to be protected by the state against being murdered by criminals or madmen. It is monstrous if the state fails to protect its residents against such predators but it does not violate the due process clause of the Fourteenth Amendment or, we suppose, any other provision of the Constitution. The Constitution is a charter of negative liberties; it tells the state to let people alone; it does not require the federal government or the state to provide services, even so elementary a service as maintaining law and order. Discrimination in providing protection against private violence could of course violate the equal protection clause of the Fourteenth Amendment. But that is not alleged here. All that is alleged is a failure to protect Miss Bowers and others like her from a dangerous madman, and as the State of Illinois has no federal constitutional duty to provide such protection its failure to do so is not actionable under section 1983.

In summary, Americans are required to protect themselves because the US government is not required to do so.
I believe that you cannot take the behavior of crazy individuals to account, because they are crazy. If someone hits a school bus while drunk, should we ban all cars? How about kitchen knives?
If one is feeling criminal, by definition, they will not follow the law. I'm just glad that most crazy people are not well enough to get interested in chemistry.

Tuesday, December 18, 2012

GDB 7.1 doesn't compile!

In order to get the armsupp.c file to compile in gdb-7.1, I had to make the return actually return something. Just a note for those of you who use arm-elf-gdb on macports, it will not compile out of the box. I've included the function in question, the change needs to be at the "here" note.
/* This function does the Busy-Waiting for an MRC instruction.  */

ARMword
ARMul_MRC (ARMul_State * state, ARMword instr)
{
  unsigned cpab;
  ARMword result = 0;

  if (! CP_ACCESS_ALLOWED (state, CPNum))
    {
      ARMul_UndefInstr (state, instr);
      return(0); // <-- here
    }

  cpab = (state->MRC[CPNum]) (state, ARMul_FIRST, instr, &result);
  while (cpab == ARMul_BUSY)
    {
      ARMul_Icycles (state, 1, 0);
      if (IntPending (state))
 {
   cpab = (state->MRC[CPNum]) (state, ARMul_INTERRUPT, instr, 0);
   return (0);
 }
      else
 cpab = (state->MRC[CPNum]) (state, ARMul_BUSY, instr, &result);
    }
  if (cpab == ARMul_CANT)
    {
      ARMul_Abort (state, ARMul_UndefinedInstrV);
      /* Parent will destroy the flags otherwise.  */
      result = ECC;
    }
  else
    {
      BUSUSEDINCPCN;
      ARMul_Ccycles (state, 1, 0);
      ARMul_Icycles (state, 1, 0);
    }

  return result;
}

Sunday, December 16, 2012

Matlab does not print whole numbers!

Actually, it does, but it decides what is an "integer". For example:
sprintf('%i',dac_start(4))
This returned 3.317660e+004 even though I told Matlab to print with %i. The solution is to round the number, resulting:
sprintf('%i',round(dac_start(4)))
ans =
33177
Until I realized that my number 33176.6, I was going batty. round() solved the problem.

Saturday, December 8, 2012

macports php5 iconv

I was surprised to find that on macports, php5 does not have iconv included by default.
To get started, I removed all of the versions of PHP that I had, and then did:

sudo port install php5 +apache2 +mysql5 +pear +postgresql +pear php5-curl php5-gd php5-iconv php5-imagick php5-imap php5-mbstring php5-mcrypt php5-mysql php5-pcntl php5-posix php5-soap php5-sockets php5-sqlite php5-xmlrpc php5-xsl php53-apache2handler

After doing that, I still didn't have iconv loading even though apache was loading php. I had to update php.ini with the extensions explicitly. I had to also specify the path:
extension=/opt/local/lib/php/extensions/no-debug-non-zts-20090626/iconv.so

(remember to check phpinfo(); to see which php.ini file is being used!)

Thursday, December 6, 2012

wheretobreakaword

You have to be careful in English of where you break a domain name:
http://www.hawaiinewsnow.com/ Hawaii New Snow or Hawaii News Now?
This consignment store:
http://kidsexchange.net/
...might not have thought their domain name through.

Sunday, December 2, 2012

In this article, the following is stated:
The line of code seems basic, even for BASIC. There aren’t any variables. It uses a GOTO instead of a more elegant loop.  How could something so short and simple generate such a complex result? What can this one line—“10 PRINT,” to use the authors’ shorthand—teach us about software, and culture at large?

I find Computer Scientists to be a fickle bunch because they are told that they are mathematicians; however, they fancy themselves as artists. The line "It uses a GOTO instead of a more elegant loop" is an excellent example of how removed most people are from hardware. A "while()" is just conditional branches, which are just "GOTO".
The x86 assembly for:
void main()
{
   while(1){;;}
}
results in:
_main:
Leh_func_begin1:
        pushq   %rbp
Ltmp0:
        movq    %rsp, %rbp
Ltmp1:
LBB1_1:
        jmp     LBB1_1      //<--jmp is a GOTO
Leh_func_end1:
...which just proves that hardware is "inelegant". I would say that it is very efficient with a single instruction jump, and simplicity is elegant.

24 hour party people

As a huge fan of music, I have a lot of respect for Factory Records and Tony Wilson (RIP). I finally got around to watching 24 Hour Party People. If you are music fan, it's a must-see.

While on the topic of music, Human Traffic is a fine movie based on music and counter culture as well. Stick to the UK version. You too can have Mr. Floppy:

...for just under 13 quid.

Saturday, December 1, 2012

一角獣?

North Korea has found the tomb of the Unicorns. Just remember, it is not the news unless it is the official news, even if it has unicorns.

Monday, November 26, 2012

DC Metro Transit Alarm

When in Washington DC, this is the must-have application: DC Metro Transit Alarm

As everyone who rides the bus or train knows, the metro schedules are more like guidelines reminding you that the train will come eventually. The DC Metro Transit Alarm for android tells you when the train will actually arrive, so that you aren't waiting around on the platform in the cold.
Also, it is only 150k, and very functional. Very few clicks to use, and you do not have click over and over to get the alarms set.

Friday, November 16, 2012

Incentives in Medicine.

First off, I do not believe in any type of socialism due to the incentive structure. Morals and ethics are not quantifiable, so mathematically, it is completely about incentives. Everyone has a bias, especially if they say that they do not. Now, with my bias out of the way...

Reason has this on medicine:
http://reason.com/archives/2012/11/15/the-obamacare-revolt-oklahoma-doctors-fi

I know first-hand that this is completely true. My daughter arrives sometime at the end of Q1, and the OGBYN told me that the total cost would be $22k. I responded that I do not have insurance, but I could pay for all services up front. Not including ultrasounds, the total cost was:
$2800 USD
That's not including ultrasounds, that went from $300 under insurance to $125. This means that I get more than 70% off one service, and more than 50% off another.

Another thing is that even if you have health insurance, there's not a reason for a doctor to take it. I say fire all of the government compliance and paper pushers.

Friday, October 26, 2012

Satire, Inc..

One of the things that I like about Americans is that they have the ability to laugh at themselves. "The Onion" is truly America's finest news source. "China Daily Show" is truly China's finest news source, because remember, it's not the news unless it's the official news.

Saturday, October 20, 2012

There is an ape with a red bottom...

There is an ape with a red bottom, but I cannot seem to find what it is. I thought that youtube would be a good way to find something from description. Well, I found the monkey, but it ended there. Consider the following picture:

That is the last screen from a mis-click actually, but it did have the red-bottom monkey. Apparently, other popular links are ape fornication, which apparently google thinks is a good time to advertise:
Chinese dating sites
Ukrainian women
Filipino dating

So boys, just remember when you are looking at that cute Chinese girl in the back of the class, from the perspective of google, she's the banner child for the Chimpy Chinky Clinky.

Edit: I still want to know what that monkey is called. :(

Friday, October 5, 2012

Steve Jobs Memorial (easter egg?) from Safari

A message from Tim Cook, Apple’s CEO.

Steve’s passing one year ago today was a sad and difficult time for all of us. I hope that today everyone will reflect on his extraordinary life and the many ways he made the world a better place.

One of the greatest gifts Steve gave to the world is Apple. No company has ever inspired such creativity or set such high standards for itself. Our values originated from Steve and his spirit will forever be the foundation of Apple. We share the great privilege and responsibility of carrying his legacy into the future.

I’m incredibly proud of the work we are doing, delivering products that our customers love and dreaming up new ones that will delight them down the road. It’s a wonderful tribute to Steve’s memory and everything he stood for. - Tim

Making lines thick (or thicker) in MATLAB plots

The default line size for MATLAB is 0.5pt, which is a bit annoying when integrating graphs into LaTeX. Consider the following graph made by:
x=1:10;
plot(x,'o-');

You can thicken a line by finding the elements of the line property. Let's say that you wanted to make the line width 4pt, you would do the following:
ch = get(gca,'children'); 
ln = ch(strmatch('line',get(ch,'Type')));
set(ln,'Linewidth',4);

As you can see, the line is much thicker. Play around with getting the 'children', as there's a lot of cool stuff that you can do to help you make your graphs prettier. You can basically do everything in 'edit plots' without changing into edit mode. :)

Wednesday, October 3, 2012

xcode and it's damnable license!

It's not building; it's not building!
So, I installed 10.8 from scratch on my mac, and I was trying to get my code working again. Things just weren't building... Well it seems that I needed to agree to the license, and the command line license is different from the GUI XCode license. Also, if you agree to the license as a user, that doesn't mean that root agreed. :/
sudo xcodebuild -license
Solved my issues.

Tuesday, September 25, 2012

Tracking down USB errors on MacOS 10.6.8

I have been buried in logs.:/
How do you supposed that one figures out what this actually means?
[5] AppleUSBOHCI[0x554c000]::ControlPacketHandler(FN: 0, EP:0): Error: 0xe00002ed, 
    stage: 0x15, todo: 0x40
[3] AppleUSBOHCI[0x554c000]:ControlPacketHandler error 0xe00002ed
    occured on endpoint (0). todo = 0x0 (Clearing stall)
[5] +AppleUSBOHCI[0x554c000]: clearing endpoint 0:0 stall
Well, I found the error codes in IOReturn.h.
#define kIOReturnNotResponding  iokit_common_err(0x2ed) // device not responding
Oh no...

Saturday, September 22, 2012

MacOS USBProber script to clean logs.

MacOS' USBProber is a great tool to debug USB transactions; however, it's just full of information. The logs that it generates just have too much! I created a bash script that I use to remove timestamps and other key words.
Consider the following three entries:
 4733.082 [7] AppleUSBOHCI[0x425d800]::ControlPacketHandler(0:0): still more to come: todo=0x40
 4733.098 [7] IOUSBControllerV3(AppleUSBOHCI)[0x425d800]::RootHubTimerFired - PolicyMaker[0x45be400] powerState[4] _powerStateChangingTo[-1]
 4736.585 [7] IOUSBHIDDriver[0x474a800]::powerChangeDone from state (4) to state (4) _device name(Apple Internal Keyboard / Trackpad)

I wanted to remove anything that had "PolicyMaker" or "Trackpad", along with the timestamp. This resulted in the following script:
#!/bin/sh

#sui's script to clean out MacOS USB prober information
#densui.blogspot.com

#change this list to include more filters
removelist="PolicyMaker Trackpad"

#function that looks for things in the last
function listcontains() {
  line=$2
  a_list=( $1 )
  #echo ${#a_list[@]}
  a_length=${#a_list[@]};
 for (( i = 0; i < $a_length; ++i ))
 do
     a_word=${a_list[$i]}
     if [[ $2 == *"$a_word"* ]]
  then
   return 0
  fi
 done
  return 1
}

#remove the old file if it exists
rm -f $2
# the main loop
cat $1 | while read line; do 
    if listcontains "$removelist" "$line"; 
    then 
     #echo Y;
     HOLDER=1
    else 
     echo ${line#*.*' '} >> $2
     #echo N;
     #echo ""
    fi    
done
Running the script on a file with the lines from the top of the page, I will get a filtered output of:
[7] AppleUSBOHCI[0x425d800]::ControlPacketHandler(0:0): still more to come: todo=0x40
So, no timestamp, no trackpad and no hub information! :)

Saturday, September 15, 2012

NeXTStep

NeXTStep was an amazingly good GUI implementation on top of unix. I still prefer it to MacOS so I use the look/feel when I use BSD. It has even made its way to anime.

Saturday, September 1, 2012

j-link with Mac OS

I was excited to get SAM-ICE up and running on Mac OS so I could use GDB without windows. Before you start though, you should download the latest version of the JLINK software for Windows from SEGGER so that you can update the flash on your JTAG debugger. This was a huge holdup for me because my firmware was older.

I installed the tools into /Applications/JLink.

The SAM-ICE tools require "libusb", so you will need to get this. I used macports, and SEGGER used macports, so I suggest this in case things change in the future. Once you install macports, type:
sudo port install libusb
I ran JLinkGDBServer from the command line, but go this:
suinomakuea:~ suigin$ /Applications/JLink/JLinkGDBServer ; exit;
dyld: Library not loaded: Output/Release/x86_64/JLinkARMDLL/libjlinkarm.4.50.9.dylib
  Referenced from: /Applications/JLink/JLinkGDBServer
  Reason: image not found
Trace/BPT trap
JLinkGDBServer.command is the command that should be run. It would have been better to have named it JLinkGDBServer.sh or something that would be better for people who know the command line. You will still get a library error because you need to copy the libraries to the location specified in the file JLinkGDBServer.command.
sudo cp /Applications/JLink/libjlinkarm.4.* /opt/local/lib/.
And now, when I run ./JLinkGDBServer.command I get a debugger connection!

Thursday, August 30, 2012

Cookies, Cross-site Scripting, etc..

This blog:
http://lcamtuf.blogspot.com/2010/10/http-cookies-or-how-not-to-design.html
has the most succinct description of cookies and the problems with web browsers that I have ever seen.

makefile:10: *** missing separator. Stop.

I almost always use spaces instead of tabs because everyone's text editor interprets a TAB differently, so I map TAB to be a number of SPACEs. I spent about 20 minutes trying to figure out why "make" was generating an error of "missing separator". The answer is here:
 CC = $(CROSS_COMPILE)gcc-4.6.1
 LD = $(CROSS_COMPILE)ld
make requires TABS, and I had tabs converted to spaces.
<--tab-->CC = $(CROSS_COMPILE)gcc-4.6.1
<--tab-->LD = $(CROSS_COMPILE)ld
Sheesh...

Saturday, August 25, 2012

XMLHttpRequest doesn't work on IE, and the fix.

I was working on a website that needed content from another site using AJAX. The site worked fine in chrome, safari, but not IE 9. IE just threw errors without any real information. The issue was a cross-site exception. In this case, the content was JSON information from graph.facebook.com. Even if you have your application inside a facebook iframe, Internet Explorers XMLHttpRequest implementation will not allow calls to graph.facebook.com because it is a cross-site call.

Here's the short list of what you need to keep in mind to get it working:
  • 1. No mixed content
    If your website is https, all calls must be https. Even though it is faster to use http://graph.facebook.com, the fact that facebook enforces https means that you must makes calls to https://graph.facebook.com if you want the information from it. I fixed this by having Javascript check to see if the browser was IE, and then did a passthrough from the hosting server via PHP.
  • 2. No Callback for Null Returns!
    If you do an AJAX callback, the callback will not run if request.responseText is "". So, you cannot use a null response a trigger for a function, even if the status is good.
  • 3. You need to use ActiveX
    You need to check to see if you are using IE, and if you are, you need to explicitly load XMLHttpRequest from ActiveX because the build-in one does not work the same! (on IE 9)
  • 4. IE caches everything
    What I mean by this is that it aggressively caches everything. As an example, if you have a file called test.php?id=10 that returns data that is changing, IE will only get it once unless you explicitly have expiry assignments in the headers.

The following is what worked for Javascript:
function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
// http://msdn.microsoft.com/en-us/library/ms537509(v=vs.85).aspx
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

function ajax(url, callbackFunction, p_targetid) {
    "use strict";
    var str_err, request, errorcode, isIE, newurl, done, ok, url_alt, a_url, fbid, tmp; 
    request = false;
    if(getInternetExplorerVersion() === -1)
    {
      request=new XMLHttpRequest();
    } else {     
       if(!request)
       {
         try{
         request=new ActiveXObject("Msxml2.XMLHTTP.6.0"); 
        try { 
        request=new ActiveXObject("Msxml2.XMLHTTP.3.0"); 
        } catch(e) { request=false;
        }
         }catch(e) { request=false;
    } 
       //here we need to change our forwarding options to go off site.
    if (url.indexOf("https://graph") == 0) {
         a_url = url.split("/")      
         tmp = a_url.length;
         tmp = tmp - 1;
         fbid = a_url[tmp];
         url_alt = '/forwardrequest.php';
         url_alt = url_alt.concat('?fbid=',fbid);
         url = url_alt;
       }
     } 
     }

  request.open("GET", url, true);
  request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  request.onreadystatechange = function () {
    done = 4;
    ok = 200;
    if (request.readyState === done && request.status === ok) {
      if (request.responseText) { callbackFunction(request.responseText, p_targetid); }
    }
  };
  request.send();
}

Notice where forwardrequest.php is the fix for IE calls offsite, in this case, JSON information. Most of the sites users are non-IE, so the burden is then completely on the browser, but you need to be mindful of hitting forwardrequest.php so much, so implemented a caching scheme for my calls to it in Javascript. That is not included here.

The forwardrequest.php that worked for me:
<?php
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

function getFBPublicInfo($p_userid)
{
  $url  = "http://graph.facebook.com/$p_userid";
  $array_json = json_decode(file_get_contents($url),true); //true is important to make it an array
  return($array_json);
}
if($_GET["fbid"])
{
  $p_userid = $_GET["fbid"];
  $url  = "http://graph.facebook.com/$p_userid";
  $result = file_get_contents($url);
  $result = getFBPublicInfo($p_userid);
    $i = count($result);
    $i = $i -1;
    $j = 0;
    echo "{\n";
    while (list($key, $value) = each($result)) {
        echo "  \"$key\": \"$value\"";
        if($j==$i)
        {
            echo"\n";
        }else
        {
            echo",\n";
        }
        $j++;
    }
echo "}\n";
}
?>
I have to explicitly build a JSON structure because the special characters were being stripped, so I just did a JSON decode and then rebuilt it.
I am just happy to be finished, and this is a reminder why I do not do web programming unless a friend asks. It's only worth it if you aren't billing because these silly things can take forever.

Tuesday, August 21, 2012

The relationship funciton.

I just had a relationship described in chat as:
function Settling(personA, personB) 
{ 
if(personA.loves(personB) && personB.loves(personA) && 
personA.willingto(SACRIFICE|COMPROMISE|LISTEN|FORGIVE) == true &&
personB.willingto(SACRIFICE|COMPROMISE|LISTEN|FORGIVE) == true && 
personA.wants(personB.happy()) && personB.wants(personA.happy()))
{ return(false);} else {return(true);} 
}
This is why women do not like to date computer scientists...

Thursday, August 16, 2012

Working the system...

Academics love to work the system, particularly when they already know the answer.
I read http://www.tgdaily.com/space-features/65458-helium-found-in-moons-atmosphere and this quote:

"The question now becomes, does the helium originate from inside the moon, for example, due to radioactive decay in rocks, or from an exterior source, such as the solar wind?" says Dr Alan Stern, LAMP principal investigator.

...pretty much sums it up. The only viable reason to go to the moon economically is to retrieve He-3, and we know that the moon has abundant supplies of helium. Here's to you for answering the answered questions Dr. Alan Stern.
(shrug)

Wednesday, August 15, 2012

Javascript Loops

Something that I have been doing recently looks very much like a run loop for a video game. I load things in a sequence to give the illusion of speed on a webpage. This blog had a nice writeup. In the same way as having a redraw in a game, you can have a loop to check user input and get local updates. Mine were on the order of seconds, but it worked really well.

Saturday, August 11, 2012

101 ways to start a fight

I now know the the author of: A Hundred and One Ways to Start a Fight by "an Irish gentleman whose name eludes me for the moment".
It is a Mr. Taylor. Way to go Katie!

If one must be internationally famous for fighting, you might as well be from Ireland.

Wednesday, July 25, 2012

At one point, this was my .plan file. I think that it was my fortune from the AIX machine.
  The Guy on the Right Doesn't Stand a Chance

The guy on the right has the Osborne 1, a fully functional computer 
system in a portable package the size of a briefcase.  The guy on the
left has an Uzi submachine gun concealed in his attache case.  Also in
the case are four fully loaded, 32-round clips of 125-grain 9mm 
ammunition.  The owner of the Uzi is going to get more tactical firepower
delivered -- and delivered on target -- in less time, and with less 
effort.  All for $795. It's inevitable. If you're going up against some
guy with an Osborne 1 -- or any personal computer -- he's the one who's
in trouble.  One round from an Uzi can zip through ten inches of solid
pine wood, so you can imagine what it will do to structural foam acrylic
and sheet aluminum.  In fact, detachable magazines for the Uzi are 
available in 25-, 32-, and 40-round capacities, so you can take out an 
entire office full of Apple II or IBM Personal Computers tied
into Ethernet or other local-area networks.  What about the new 16-bit
computers, like the Lisa and Fortune?  Even with the Winchester backup, 
they're no match for the Uzi.  One quick burst and they'll find out what 
Unix means.  Make your commanding officer proud.  Get an Uzi -- and come 
home a winner in the fight for office automatic weapons.

  -- "InfoWorld", June, 1984

edit:
So, apparently, "the guy on the left" as the marketing campaign for the Osborne 1, http://en.wikipedia.org/wiki/Osborne_1#Early_production, which was where this satire came from.

Friday, July 13, 2012

The Great Happiness Space

昨日、 http://www.thegreathappinessspace.com/が見てた。日本人以内にはこんの映画をすごっくおもろいと思う。

Thursday, July 12, 2012

aclocal and ./configure

If you ever have a ./configure file, you need to be sure that you have automake and autoconf installed; however, that does not mean that it will work. Today I received this error:
aclocal.m4:14: error: this file was generated for autoconf 2.61.
You have another version of autoconf.  If you want to use that,
you should regenerate the build system entirely.
aclocal.m4:14: the top level
The solution is to do the following to rebuild the autoconf dependencies:
autoreconf && ./configure

Wednesday, July 4, 2012

MacOS 10.6 and building libjpeg


I had a terribly time getting jpeg-lib to compile under MacOS X, but I figured it out.   
uname -a gives me:
Darwin suiginnomaku.local 10.8.0 Darwin Kernel Version 10.8.0: Tue Jun  7 16:33:36 PDT 2011; root:xnu-1504.15.3~1/RELEASE_I386 i386
The simple instructions would be to download the tar.gz from http://sourceforge.net/projects/libjpeg/files/libjpeg/6b/ and untar the file.
You then change into the jpeg-6b directory. You must now copy configuration files for libtool into the directory and configure:
cp /usr/share/libtool/config/config.sub .
cp /usr/share/libtool/config/config.guess .
./configure --enable-shared --enable-static
You then need to edit the Makefile and change ./libtool to be:
LIBTOOL = glibtool
This is because of the fact that libtool that ships with the libjpeg source is outdated for MacOS, and glibtool is the version that is built-in.

You then type:
make
to build the files.

You then do a:
sudo make install

Thursday, June 28, 2012

46 things that foreigners find surprising in Japan.

Actually, the title of the article is 外国人が日本に来て驚くこと46個. The highlights for me were:

1. The trains run on time. (I've never understood why they don't in other places)

8. Tabacco and SAKE vending machines. (I don't know why these aren't in other places)

22. Japanese like using Yahoo. (I was speaking once to a Google employee, and I told him why Yahoo, and why it was better and he called me stupid. You might have a good search engine, but your other service offerings are terrible Mr. Google. Also, したい should not always default to 死体! Your input methods and autocomplete are disgusting!)

46. The cutest Japanese girls are always dating the ugliest foreigners (カッコ悪い just doesn't translate well, but yes, they are that.)

Monday, June 25, 2012

Google's take on the Post.

This is the best summary of the Beech Daly Post Office, and sadly, it is true.

Tuesday, June 19, 2012

SerialPort and C#

The SerialPort class in C# has some interesting behavior when combined with a GUI.  The GUI threads seem to fight with the SerialPort IO.  I found the solution to be to use the BackgroundWorker class.


private void backgroundThread_read(object sender, DoWorkEventArgs e)
{
  BackgroundWorker worker = sender as BackgroundWorker;
  try
  {
     while ((worker.CancellationPending!=true))
     {
                       //serial IO
     }
     //when the shutdown occurs
     if (worker.CancellationPending == true)  
     {
        backgroundThread.CancelAsync();
      }
   }
   catch (Exception exc)
   {
      backgroundThread.CancelAsync();  //cancel the thread due to error
   }
}
I wrapped this with a messaging class that I made.

Tuesday, June 12, 2012

I need a Java preprocessor.

I like to have line numbers with my exceptions. Currently, I put them in statically.
try{
...
}catch(Exception e)
{  System.out.println("Exception at line LINENUMBER: "+e);  }
Or I will put it into my custom logger class that has the same format.
The best way that I have found to do this so far is:
String linenumber = new Exception().getStackTrace()[0].getLineNumber();
System.out.println("The line number is " + linenumber);
The problem with StackTrace is that it brings things to a halt.

Sunday, June 10, 2012

Haircut in North Conway?

I needed a haircut, and I happened to be in North Conway, NH.
The "Old Village Barbershop" is behind the Met Coffee shop downtown.  It was very interesting as I got a haircut, and got to look at schematics of weapons.   Tim Martineau was very interesting to speak with.  


View Larger Map

Tuesday, May 22, 2012

Alberto the dragon!

This evening when I skimmed google news, I saw Alberto the dragon!

I do not understand the "moral argument" concept.

I do not understand the concept of a "moral argument" because morality is relative.  If I were in Afganistan, there could be a moral argument for Islamic law because morality is based upon culture and concepts.  What is "fair" seems to be relative as well.

I see world yelling "why cannot I have nice things?", but I would guess that "nice" changes.  I am sure that a can of beans would be nice to a North Korean.

I think that the only true moral, moral argument, is to not have morality that forces behavior on others.

Sunday, May 20, 2012

C Preprocessor Directives

I had a bug, and I knew it was syntax.  I compile my C code so that all warnings are errors to try to mitigate this class of problem, but it never works.  I decided that I would change how I behave using preprocessor directives.  Firstly, I must say that IBM has great preprocessor documentation in every language that one could speak, but that's not necessary.
Let's start with my problem and my line of code:
if((variable && 0x40000000)!=0){;;}
Variable was not supposed to have a comparison && in it.  It was supposed to be:
if((variable & 0x40000000)!=0){;;}
The problem is that my fingers have habits and I do '&&' more than '&'.  That line of code took about 4 hours to track down. :(  I now have changed my behavior so that it never happens again. The new line is uses C preprocessor directives.
I define my logical AND through a MACRO:
#define _LAND(arg1,arg2) (arg1 & arg2)
I now use it as I would a function in my IF statement:
if(_LAND(variable,0x40000000)!=0){;;}
that results in this code upon compile:
if((variable & 0x40000000)!=0){;;}
so that I never have that mistake again.

Friday, May 18, 2012

Americans and their funny laws.

I have never understood why Americans want to govern the world.  As far as law, and American can be prosecuted for a crime overseas where it may not be a crime.  I find this the same as the Taliban having a trial for a woman back in Afganistan who recently went to New York and walked the streets alone.

I saw this about giving up citizenship due to tax liabilities and I completely understand.  The answer is simplicity.  If you want  people to follow the law, remove complexity.  "Fair" is relative, because what is fair for one is not fair for others.  How about firing 95% of the IRS and having a 15% flat tax?  No reason to flee if everyone is the same.

Here is the US Constitution and the Amendments, which I have read.  I see no provisions for anything that would not treat citizens equally.

Perhaps it is time to completely through out every law and start over.   The Japanese did it at WWII and it seems to have worked, but the Japanese were completely defeated.

Perhaps with debt, complexity, and some skewed desire for "fairness", the USA should declare defeat and  start from scratch with the laws.

One note about the US Constitution is that I believe it to be a superior document due to flexibility; whereas, the EU Constitution is just...confusing.

Thursday, May 17, 2012

Makefile and defines with a value.


Have you ever wanted to change some code without changing the code?  I did this in the Makefile.  I did this with a define from the compiler command line.  A subset of the Makefiles follows:

<makefile>
# this is the top of the Makefile. I put switches here.
# comment out PRODVER if you want the original
PRODVER := MODIFIED
#MODIFIED Threshold for lower bounds
MODIFIED_THRESHOLD :=30000

#...

CFLAGS = -Wall -mlong-calls -ffunction-sections
ifeq ($(PRODVER),MODIFIED)
 CFLAGS += -DMODIFIED=$(MODIFIED_THRESHOLD)
endif
CFLAGS += $(OPTIMIZATION) $(INCLUDES)

</makefile>

The Makefile makes the same thing as:
#define MODIFIED 30000
but it does it as -DMODIFIED=30000 when the line is passed to gcc.

I want to set the minimum value of bounds
The C code looks like this:
<main.c>
 /*This is the modification the code based on code from the makefile*/
 #ifdef MODIFIED   //this is defined in the Makefile
 if(bounds &lt; MODIFIED)  //for our current Makefile, this will become (bounds&lt;30000)
 {
    bounds=MODIFIED;  //this sets the minimum value to be whatever is in the makefile.
 }                    //this line turns into bounds=30000;
 #endif

</main.c>

Thursday, May 10, 2012

Entropy

Entropy is the energy in a system. If you want to add energy to an existing system, you must increase it from an external source. I modeled employment as entropy at one point, which I liked. This audio link is basically about entropy and employment. If you cannot add external energy, you cannot increase the entropy of the system. http://itunes.apple.com/us/podcast/job-killers-03.29.12/id330304186?i=112448960 I just wish someone would call it entropy. :/

Saturday, April 28, 2012

Sunday, April 15, 2012

KiCad has requirements before having a pick and place output file.

In order to export pad position in Kicad, you supposedly use the export footprint locations to the "modules position file". There is a catch. I exported my modules and the file was empty! I figured out later that one needs to include the "Normal+Insert" option in the KiCad libraries files. I had to go back later and edit every single one by hand on my board, but it was faster than redoing the board.

So, if you find that your module file is empty, edit the part to include "normal+insert", and retry the manufacturing export for pick 'n place and see if it helps you.


(PS: notice the "attributs" tag, hehe.)

Friday, March 16, 2012

AT91SAM7S and 24 bit SPI transfer.

Most 16-bit DACs take a 24-bit word. After fighting with the PDC to get DMA working, I settled on a simpler solution. The following is an example of writing 24-bits to the SPI bus with an AT91SAM7S256.

unsigned int spi_24bit(unsigned int dacval)
{
 AT91PS_SPI     pSPI = AT91C_BASE_SPI;
 
 //set SPI pins 
 static unsigned int perphA=
  ((unsigned int) AT91C_PA11_NPCS0   ) |
  ((unsigned int) AT91C_PA13_MOSI    ) |
  ((unsigned int) AT91C_PA31_NPCS1   ) |
  ((unsigned int) AT91C_PA12_MISO    ) |
  ((unsigned int) AT91C_PA14_SPCK    ); // Peripheral A
 static unsigned int perphB= (unsigned int) AT91C_PA30_NPCS2 ;

 AT91C_BASE_PIOA->PIO_ASR = perphA;  //set the SPI pins to the peripheral functions
 AT91C_BASE_PIOA->PIO_BSR = perphB;  //set SPI port B pins.
 AT91C_BASE_PIOA->PIO_PDR = (perphA|perphB);  //disable GPIO from changing SPI pins.
 AT91C_BASE_PMC->PMC_PCER = ((unsigned int) 1 << AT91C_ID_SPI);  //enable SPI clock
 AT91C_BASE_SPI -> SPI_CR  = AT91C_SPI_SWRST;//Reset the SPI
 
 /*THIS IS A BIGGIE
 The SWRST bit clears the MR register to defaults!  
 This means that you need to re-enable master mode after you use the CR reset.
 */
 AT91C_BASE_SPI -> SPI_MR  = 0x00000003; //master and variable select
 AT91C_BASE_SPI -> SPI_CR  = AT91C_SPI_LASTXFER|AT91C_SPI_SPIEN;//enable SPI
 AT91C_BASE_SPI -> SPI_CSR[1]=0x00000808;  //keep CS low until new xfer.

 unsigned int databyte1=0;
 unsigned int databyte2=0;
 unsigned int databyte3=0;

 databyte1 = databyte1 | 0x000D0000;  // 0D selects CS1
 databyte2 = (dacval & 0x0000ff00);
 databyte2 = databyte2 >>8;
 databyte2 = databyte2 | 0x000D0000;
 databyte3 = dacval & 0x000000ff;
 databyte3 = databyte3 | 0x010D0000;  //toggle last transfer line.
 
 pSPI -> SPI_TDR = databyte1;
 while(!((pSPI -> SPI_SR)&0x00000002))
 { ;;  //wait for the data to be sent out}
 pSPI -> SPI_TDR = databyte2;
 while(!((pSPI -> SPI_SR)&0x00000002))
 { ;;  //wait for the data to be sent out}
 pSPI -> SPI_TDR = databyte3;
 while(!((pSPI -> SPI_SR)&0x00000002))
 {;;  //wait for the data to be sent out}
 return(dacval);
}

Saturday, February 25, 2012

Making a DVD for Windows in MacOS X.

Windows, it seems, is not very file system savvy. I wanted to back up my MacOS files to a DVD, but then I decided that I wanted a copy on my Windows machine. The thing that you must understand is that there is a great physical distance between the machines. It was easiest to just make blank DVD image in Mac OS by using Disk Utility, and then fill it. The CDR format that MacOS used did not work when I copied that file to Windows to burn because it was not an ISO. It seems that windows still does not use UDF on DVDs, so you need to put in the old ISO extensions.

sudo hdiutil makehybrid -joliet -iso dvdimage.cdr -o dvdimage.iso

The only issue is that the extensions require disk space, so 100MiB on the DVD was taken by the conversion, so leave a little bit of empty space on the disk.

Friday, February 17, 2012

System.DllNotFoundException: Unable to load DLL, figured it out.

In my previous post, I was trying to make a DLL that would load from C#, and in one case, had the exception:

System.BadImageFormatException: An attempt was made to load a program with an in
correct format. (Exception from HRESULT: 0x8007000B)

Interestingly, I found that I could also generate this one by solving the problem above:

System.DllNotFoundException: Unable to load DLL 'simpleDLL.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)

If one has .NET 2.0, the C# binds as 32-bit, so an explicit 64-bit DLL might try to call a 32-bit DLL. I used Microsoft's sysinterals to understand what was happening and Dependency Walker to check my DLLs.

In closing, if you get a System.DllNotFoundException even when you DLL is in the same directory as your executable, it is a binding issue and change from .NET 2.0 to something higher (I used 3.5). If you get a BadImageFormatException, it is due to the binary format, so be sure that the DLL matches your machine bit width.

Sunday, February 12, 2012

DLLs and C#

Hardware is not a mystery to me. C is not a mystery to me. UNIX is not a mystery to me.
Windows is a mystery to me. I had to modify a C# application to use a DLL written in C++.

I started by reading all of the documentation, which took about 3 days. Creating Reusable Code seemed to be a good place to start; however, it's terribly. I have created the demo program and documented the problems along the way which is what Microsoft should have done in the first place.

I have created a sample project that has a DLL which is called from C#. I looked for a long time for a functional example. This is a functional example by someone who does not know the Windows lingo or assumptions. The source code is available at the bottom of the page as zip files. In summary, I started on VS2005, but ended up in VS2010.

In VS2005, I created a solution (this is MS term for a tome of projects) called "DLLExampleWithCSharp". I then created a project called "simpleDLL" that is a Win32API project that is a DLL through the project wizard and exported the functions. This is the first part of where I went wrong. The wizard only partially completes the requirements for a DLL. If you will be including the DLL through headers, it is a fine method, but for "unmanaged DLL" code, it will not work for you. I will return to this topic later.

Using the wizard's format, I changed my function to be
(simpleDLL.h)
SIMPLEDLL_API size_t simpleDLL_message(char *stringio, size_t ui_length);
(/simpleDLL.h)
(simpleDLL.c)
SIMPLEDLL_API size_t simpleDLL_message(char *stringio, size_t ui_length)
{
 char *cp_message = "suigin spars with windows.\n";
 size_t i_message_length = strlen(cp_message);
 if(ui_length < i_message_length)
 {
  i_message_length = ui_length;
 }
 strncpy(stringio,cp_message, i_message_length);
 return(i_message_length);
}
(/simpleDLL.c)
I now have a function that will take a string pointer and allocation length, and copy the cp_message into it. I now make my C# application to call the DLL. (CSharpCallsDLL.cs)
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;  //required to call the DLL
namespace CSharpCallsDLL
{
 class Program
 {
  [DllImport("simpleDLL.dll")]
  public static extern UInt32 simpleDLL_message(StringBuilder stringio, UInt32 ui_length);
  static void Main(string[] args)
  {
   StringBuilder s_str = new StringBuilder("000000000");
   UInt32 ui_len = (UInt32)s_str.Length;
   try
   {
    UInt32 ui_result = simpleDLL_message(s_str, ui_len);
    Console.Out.WriteLine("The result:");
    Console.Out.WriteLine("ui_result=" + ui_result + ", stringio=" + s_str);
   }
   catch (Exception e)
   {
    Console.Out.WriteLine(e);
   }
  }
 }
}
(/CSharpCallsDLL.cs) I then start up my Visual Studio 2005 Command Prompt and run the program, CSharpCallsDLL.exe.
C:\Users\suigin\Documents\Visual Studio 2005\Projects\DLLExampleWithCSharp\CSharpC
allsDLL\bin\Release>CSharpCallsDLL.exe
System.DllNotFoundException: Unable to load DLL 'simpleDLL.dll': The specified m
odule could not be found. (Exception from HRESULT: 0x8007007E)
   at CSharpCallsDLL.Program.simpleDLL_message(String stringio, UInt32 ui_length
)
   at CSharpCallsDLL.Program.Main(String[] args) in C:\Users\suigin\Documents\Visu
al Studio 2005\Projects\DLLExampleWithCSharp\CSharpCallsDLL\Program.cs:line 30
And, it dies with "System.DllNotFoundException". The DLL is not found, so I either have to add it to my path, but I will just copy the DLL. "copy simpleDLL.dll ..\CSharpCallsDLL\bin\Release\.", so simpleDLL.dll is not in the same directory as CSharpCallsDLL.exe. It is also worth noting that C# projects and C++ projects have a different directory layout, which I found to just be a quirk, so be sure that you are in the correct "Release" directory. The next error that I encountered was "System.BadImageFormatException".
C:\Users\suigin\Documents\Visual Studio 2005\Projects\DLLExampleWithCSharp\CSharpC
allsDLL\bin\Release>CSharpCallsDLL.exe
System.BadImageFormatException: An attempt was made to load a program with an in
correct format. (Exception from HRESULT: 0x8007000B)
   at CSharpCallsDLL.CSharpCallsDLL.simpleDLL_message(String stringio, UInt32 ui
_length)
   at CSharpCallsDLL.CSharpCallsDLL.Main(String[] args) in C:\Users\suigin\Documen
ts\Visual Studio 2005\Projects\DLLExampleWithCSharp\CSharpCallsDLL\CSharpCallsDL
L.cs:line 30
The official Microsoft documentation for System.BadImageFormatException is rather worthless, and I could guess what the problem was. Basically, my version of .NET is too old for what I was trying to do. Visual Studio 2005 is .NET 2.0, and I have 64-bit Windows7 machine. I generally develop for the lowest possible machine; however, in this case, I'll have to upgrade. Here enters Visual Studio 2010. (In other news, I would really love to know how to fix that error, but I the best I could find was here, but I couldn't understand it.) I redid everything that I did above, and it magically got past that exception, and went on to the next one.
C:\Users\suigin\Documents\Visual Studio 2010\Projects\DLLExampleWithCSharp\CSharpC
allsDLL\bin\Release>CSharpCallsDLL.exe
System.EntryPointNotFoundException: Unable to find an entry point named 'simpleD
LL_message' in DLL 'simpleDLL.dll'.
   at CSharpCallsDLL.CallDLL.simpleDLL_message(String stringio, UInt32 ui_length
)
   at CSharpCallsDLL.CallDLL.Main(String[] args) in C:\Users\suigin\Documents\Visu
al Studio 2010\Projects\DLLExampleWithCSharp\CSharpCallsDLL\CallDLL.cs:line 33
The entry to the DLL is the most important thing, and System.EntryPointNotFoundException says that I did not call the correct function name. There should be a method to recall a method manifest, but there does not seem to be. This is where Microsoft should have example code. The issue is that C# cannot see the entry point into the DLL even though I know it is there. I found that there was a tool which I could use to see the entries from the VS2010 shell, called dumpbin (I note that other pages for dumpbin are terrible).
C:\Users\suigin\Documents\Visual Studio 2010\Projects\DLLExampleWithCSharp\CSharpC
allsDLL\bin\Release>dumpbin /exports simpleDLL.dll
Microsoft (R) COFF/PE Dumper Version 10.00.40219.01
Copyright (C) Microsoft Corporation.  All rights reserved.


Dump of file simpleDLL.dll

File Type: DLL

  Section contains the following exports for simpleDLL.dll

    00000000 characteristics
    4F368F07 time date stamp Sat Feb 11 10:53:43 2012
        0.00 version
           1 ordinal base
           1 number of functions
           1 number of names

    ordinal hint RVA      name

          1    0 00001010 ?simpleDLL_message@@YAIPADI@Z = ?simpleDLL_message@@YA
IPADI@Z (unsigned int __cdecl simpleDLL_message(char *,unsigned int))

  Summary

        1000 .data
        1000 .rdata
        1000 .reloc
        1000 .rsrc
        1000 .text
Wow, what a function name. I found that I could use that awful thing to call my function, but I knew there must be a better way. I seems that it did not know how to make nice names by default. I found an obscure note in a linker how-to regarding a possibility from the days of Win 3.11, which I can no longer find the link. If you include 'extern "C"', it will solve some problems that were not specific. My new function declaration is:
extern "C" SIMPLEDLL_API size_t simpleDLL_message(char *stringio, size_t ui_length);
Upon compilation, the DLL entry makes much more sense.
C:\Users\suigin\Documents\Visual Studio 2010\Projects\DLLExampleWithCSharp\CSharpC
allsDLL\bin\Release>dumpbin /exports simpleDLL.dll
Microsoft (R) COFF/PE Dumper Version 10.00.40219.01
Copyright (C) Microsoft Corporation.  All rights reserved.


Dump of file simpleDLL.dll

File Type: DLL

  Section contains the following exports for simpleDLL.dll

    00000000 characteristics
    4F3693CF time date stamp Sat Feb 11 11:14:07 2012
        0.00 version
           1 ordinal base
           1 number of functions
           1 number of names

    ordinal hint RVA      name

          1    0 00001010 simpleDLL_message = _simpleDLL_message

  Summary

        1000 .data
        1000 .rdata
        1000 .reloc
        1000 .rsrc
        1000 .text
The addition of 'extern "C"' has made all of the difference in the entry point definition. The program now runs and gives the following output:
C:\Users\suigin\Documents\Visual Studio 2010\Projects\DLLExampleWithCSharp\CSharpC
allsDLL\bin\Release>CSharpCallsDLL.exe
The result:
ui_result=9, stringio=suigin sp
In summary, I now know the syntax for C++ DLL calls from C#. The project files are the working Visual Studio 2010 project and the broken Visual Stuidio 2005 project.

Wednesday, February 8, 2012

Virtual CDROM and Windows 7

I probably should update this more often, but I only seem to do it when something gets me in a ruckus, and today is Windows and mounting ISOs.

I have never understood why Microsoft has never included inherent loopback mounting functionality in Windows, particularly when they release just about everything as an .iso. Interestingly, it's not just me: http://connect.microsoft.com/WindowsServerFeedback/feedback/details/351231/mount-iso-files

To mount a CDROM/DVD in Windows 7/Vista, I have used:
http://www.slysoft.com/en/virtual-clonedrive.html
http://www.magiciso.com/tutorials/miso-magicdisc-history.htm
I seem to prefer MagicDisc though.

On Windows XP, Microsoft supplies a tool:
http://download.microsoft.com/download/7/b/6/7b6abd84-7841-4978-96f5-bd58df02efa2/winxpvirtualcdcontrolpanel_21.exe

And with those tools, I now have the same functionality that I had with System 6 on a Mac IIsi.