<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Wunderkammer</title>
	<atom:link href="http://www.nunoalves.com/open_source/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://www.nunoalves.com/open_source</link>
	<description>Embedded systems, coding and electrical circuits</description>
	<lastBuildDate>Wed, 22 May 2013 16:31:34 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Interviewing for an entry-level embedded systems engineering position</title>
		<link>http://www.nunoalves.com/open_source/?p=486</link>
		<comments>http://www.nunoalves.com/open_source/?p=486#comments</comments>
		<pubDate>Wed, 22 May 2013 16:31:34 +0000</pubDate>
		<dc:creator>Nuno Alves</dc:creator>
				<category><![CDATA[Embedded Systems]]></category>
		<category><![CDATA[C/C++]]></category>
		<category><![CDATA[Schematic Capture]]></category>

		<guid isPermaLink="false">http://www.nunoalves.com/open_source/?p=486</guid>
		<description><![CDATA[In my current position, I am often tasked to interview recent college graduates for our internships and also for our entry-level embedded systems positions. Since we are a relatively small company, we are looking for well rounded engineers with some general understanding of embedded software as well as circuit design. We need our new-hires to [...]]]></description>
				<content:encoded><![CDATA[<p>In my current position, I am often tasked to interview recent college graduates for our internships and also for our entry-level embedded systems positions. Since we are a relatively small company, we are looking for well rounded engineers with some general understanding of embedded software as well as circuit design. We need our new-hires to help designing new circuits at the schematic level, develop software for various micro-controllers and debug faulty circuit boards returned from the field.<br />
Over the last couple of months I have interviewed dozens of candidates and I was shocked to see that the vast majority of these engineers, many coming out of prestigious universities, are unable to answer the most basic questions. I understand that job interviews can be a stressful event, but some of the most basic concepts should be second nature to anyone with an electrical/ computer engineering degree. In this post I will outline our technical interview routine, which does not differ much from other embedded systems engineering entry-level interviews. While the human-resources department is mainly interested in personality fit, the role of the technical portion of the interview, is to assess the candidate skills.</p>
<p><strong>Unsolicited advice from the other side</strong><br />
For the young engineers out there interviewing, I have 4 general suggestions:<br />
<em>1-</em> During the interview, do not drop industry-buzzwords that you don’t fully understand what they mean. For example, don’t say that you love chips manufactured by ARM. ARM does not make chips.<br />
<em>2-</em> Come prepared with a portfolio with some of your work (e.g. source code, circuits, layouts, relevant blog posts) and leave a copy with the interviewers.This makes you look professional and organized.<br />
<em>3-</em> In a technical engineering position no one is interested how cool the candidate was in college or how smart the candidate is for wanting to go to graduate school to learn more. In most companies there is a need for dedicated engineers to design, implement and maintain a project in its entire life-cycle. We simply have no time to train someone for a couple of months, so that they can jump-ship in six months to go to graduate school.<br />
<em>4-</em> Go to interviews dressed business casual. I have noticed that the strongest candidates are usually the ones who don’t over-or-underdress.</p>
<p><strong>Resume skill check</strong><br />
When we start the interview process, the first thing we do is re-read the skills section. If the candidate lists a particular skill, we will inevitably ask some very basic questions about it. For example, if C/C++ is listed as a skill, we generally ask the candidate to tell us the difference between C and C++. Unfortunately, only about 25% of the candidates know this.The simplest answer, as defined by the creator of C++ himself (Bjarne Stroustrup), is that C++ is C with classes.This would be the perfect time to talk about how C++ is an object oriented language and that objects allow the programer to secure (hide) data inside classes.The diligent engineer could also talk about how in C++, two functions can have the same name but different arguments (function overloading) and how variables in standard versions of C need to be declared at the start of each function. Similarly, if you do not understand the difference between Linux and Unix, do not put both on your resume.</p>
<p>Here are some of the commonly listed skills and some possible simple questions about them:<br />
<em>Matlab or Mathematica</em> &#8211; Can you put 10 numbers in a 1D Matrix (orTable) and compute their average?<br />
<em>Linux</em> &#8211; What is your Linux distribution? What command do you use to create and change a directory?<br />
<em>ASM</em> &#8211; What does the command JMP do? What about MOV?<br />
<em>Python or Perl</em> &#8211; Can you create a for loop that prints “hello world” 10 times?<br />
<em>HTML</em> What does the <HTML> and </HTML> tag to?<br />
<em>Spice</em> &#8211; Can you write a spice file with a circuit with a power supply and a single resistor?<br />
<em>Labview </em> &#8211; Who makes Labview?</p>
<p>Finally, my recommendation is to avoid listing skills that you don’t fully understand what they mean. One of our candidates listed Xilinx as a software skill.This particular candidate not only did not know that Xilinx was a company, but he also could not remember the purpose of that particular piece of software (“I think it was to program some sort of chip.”).</p>
<p><strong>Assessing the candidate interest in embedded systems</strong><br />
We are always interested in candidates with a passion for anything related to embedded systems, as these tend to be the strongest engineers. We often ask them where they buy their components, what electronics magazines they read and which websites they frequent. We also like to know what is their favorite prototyping system (e.g. arduino, raspi, beagleboard) and favorite programming language.We also like candidates to tell us about how they normally go about testing and implementing their prototypes. For example, how would they go about etching a PCB in their basement? While the answers to these questions are far from being deal-breakers, they do give us an insight about how passionate the candidate is about the field.<br />
We also like our entry-level candidates to know a bit of whats out there. For example, what are the names of some companies that manufacture micro-controllers and the names of their products (e.g. Atmel manufactures ATmega328P which is used in the Arduino prototyping system).</p>
<p><strong>The deal breakers</strong><br />
We have, what we like to call the “five deal breaker questions”. If candidate misses one of them, we cannot in good conscience hire them.<br />
<em>Question #1</em> &#8211; The most fundamental question regarding electrical circuit theory is how to measure current and voltage in a simple circuit. In the interview room we have a very simple circuit with a single resistor in a prototype board. After we power the circuit we give the candidate a digital multimeter and ask them to measure the voltage across, and the current through, the resistor; Voltage levels are measured by connecting the two probes across the resistor, while current is measured by opening the circuit and completing it with the multi-meter connected in series. Surprisingly about 10% of the candidates miss this question.</p>
<p><em>Question #2</em> &#8211; We need to know how confident the candidate is with basic circuit analysis. We draw on the board a schematic very similar to the one shown on Figure 1 and ask the candidate to determine the measured voltage across R2.</p>
<div id="attachment_498" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.nunoalves.com/open_source/wp-content/uploads/2013/05/Figure1.jpg"><img src="http://www.nunoalves.com/open_source/wp-content/uploads/2013/05/Figure1.jpg" alt="Figure 1 - Interview question: Determine the voltage across R2." width="300" height="250" class="size-full wp-image-498" /></a><p class="wp-caption-text">Figure 1 &#8211; Interview question: Determine the voltage across R2.</p></div>
<p>A confident engineer does not have to make any calculations.Two equal resistors in series with 10V across them, means that the voltage across just one of these resistors is 5V. The candidate can also determine this voltage by “hand”:<br />
<div id='stb-box-8989' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; ">Ohms law implies that,<br />
V1 = i (R1 + R2)<br />
10 V = i (100 + 100)<br />
So the current through R1 and R2 is 10 / 200 Amps or 20 mAmps.<br />
VM = i (R2) = 10 / 200 * 100 = 10 / 2 = 5 Volts<br />
</div></p>
<p>One quarter of our candidates, most with degrees in electrical engineering had trouble with this question.</p>
<p><em>Question #3</em> &#8211; We also ask very simple practical design questions. For example, when should you use a transistor instead of a relay in a design? There are many possible answers here, and we are just looking for the basic ones. For example, you can mention that the relay, since it is an electromechanical switch, is much slower than a transistor, but it can usually carry a lot more current. Relays in general are also much bigger than transistors.</p>
<p><em>Question #4</em> &#8211; It is fundamental that our new hires know the purpose of basic circuit concepts. Here are the three short-answer questions we always ask:</p>
<p>Q:What is a servo motor?<br />
<div id='stb-box-606' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; ">I￼￼t is a motor in which you can control the precise position of its shaft through a well-defined pulse.</div></p>
<p>Q:What is a potentiometer?<br />
<div id='stb-box-7390' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; ">It is a resistor whose resistance can be changed by adjusting a knob, usually with a small screwdriver.</div></p>
<p>Q:What is does it mean for a signal to have 30% duty cycle?<br />
<div id='stb-box-568' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; ">It means the signal is in its high-state 30% of the time.</div></p>
<p><em>Question #5</em> &#8211; Finally, we always ask the candidate to explain what are the defining characteristics of an OP-AMP. Most candidates are able to tell us that the V+ and V- inputs have high impedance and they are often able to write out the (usually memorized) equations for OP- AMP circuits with a feedback loop. Unfortunately they can’t do much more than this, and the concept of the OP-AMP rail is often not understood.</p>
<p>We then ask the candidate to determine the output voltage of an ideal OP-AMP with a “comparator” configuration, exemplified in Figure 2.<br />
<div id='stb-box-8210' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; ">The voltage across R1 is 15V. The two inputs V1 and V2 are compared and the output voltage will be set by the appropriate rail supply, which in this example is the one associated with the negative input (V3).</div></p>
<div id="attachment_513" class="wp-caption aligncenter" style="width: 410px"><a href="http://www.nunoalves.com/open_source/wp-content/uploads/2013/05/Figure2.jpg"><img src="http://www.nunoalves.com/open_source/wp-content/uploads/2013/05/Figure2.jpg" alt="Figure 2 - Interview question: Determine the voltage across R1." width="400" class="size-full wp-image-513" /></a><p class="wp-caption-text">Figure 2 &#8211; Interview question: Determine the voltage across R1.</p></div>
<p>Alternatively we also ask about the purpose of the voltage follower configuration, shown in Figure 3.</p>
<div id="attachment_519" class="wp-caption aligncenter" style="width: 410px"><a href="http://www.nunoalves.com/open_source/wp-content/uploads/2013/05/Figure3.jpg"><img src="http://www.nunoalves.com/open_source/wp-content/uploads/2013/05/Figure3.jpg" alt="Figure 3 - Voltage follower op-amp configuration: If the voltage V1 is both at the V- and VM1, what is the purpose of this configuration?" width="400" class="size-full wp-image-519" /></a><p class="wp-caption-text">Figure 3 &#8211; Voltage follower op-amp configuration: If the voltage V1 is both at the V- and VM1, what is the purpose of this configuration?</p></div>
<div id='stb-box-8187' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; ">The voltage follower with an ideal OP-AMP gives simply V1 = VM1. However, because the high input impedance, the OP-AMP output (VM1) is isolated from the OP-AMP input (V1). In essence the current drawn from the circuitry connected to the output is not drawn from the signal source at the OP-AMP input, but from the OP-AMP rails.</div>
<p><strong>Basic Embedded-C</strong><br />
We need our candidate to know how to program in C.There is no work around this one; the embedded systems engineer must know how to handle the most basic programming tasks.<br />
<em>Question #6</em> &#8211; The first programming question is always about distinguishing between the ‘=’ and ‘==’ operator (‘=’ is assignment, while ‘==’ is a comparator).<br />
<em>Question #7</em> &#8211; We then ask the candidate to write out the C-code that solves the commonly used fizzbuzz problem.The assignment is as follows:<br />
<em>&#8220;Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.&#8221;</em></p>
<p>While this is not a particularly hard, most of our candidates were unable to solve this assignment. Here is a possible solution:</p><pre class="crayon-plain-tag">int main() {
	for( int i=1; i&lt;=100; i++)
	{
		if(i%3==0)
		  printf(&quot;Fizz&quot;);
		if(i%5==0)
		  printf(&quot;Buzz&quot;);
		if(i%3!=0 &amp;&amp; i%5!=0)
		  printf(&quot;%d&quot;,i);

		printf(&quot;\n&quot;);
	}

	return 0;
}</pre><p></p>
<p>We always ask something related to C-pointers. We understand that pointers can be a bit confusing to engineers, but the candidate must have at least a very general concept about what a pointer is.</p>
<p><em>Question #8</em> &#8211; Consider an integer k. How do you change its value through a pointer?</p><pre class="crayon-plain-tag">int a=6;
int *ptr=&amp;a;
*ptr=10;</pre><p></p>
<p>If the candidate shows confidence with pointers we normally ask slightly more advanced questions. For example,<br />
<em>Question #9</em> &#8211; What is the benefit of passing elements to a function by reference instead of by value? Can you write a small piece of code that demonstrates passing by reference?</p>
<div id='stb-box-8497' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; ">Every time something is passed into a function by value, it is pushed down into the stack. If we are sending a structure with 10,000 members, all those members will be pushed down, needlessly using a lot of memory space.</div>
<p></p><pre class="crayon-plain-tag">int main(void) { 
    int a,b;
    a=10; b=20;
    swap_by_reference(&amp;a, &amp;b);  
}
 
 void swap_by_reference(int *val_1, int *val_2)
 {
    int temp;
    temp=*val_1;
    *val_1 = *val_2;
    *val_2 = temp;
 }</pre><p></p>
<p><strong>Intermediate Embedded Systems topics</strong><br />
At this point we have a pretty good idea about the candidate and his abilities. If time allows we ask slightly more complex questions, allowing us to differentiate between the strongest candidates. </p>
<p><em>Question #10</em> &#8211; Consider the generic schematic on Figure 4. In this circuit, the solenoid L1 has been energized for a long time and suddenly we open the switch SW1. Can you foresee any problem? What can be done to fix it?</p>
<p><div id="attachment_529" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.nunoalves.com/open_source/wp-content/uploads/2013/05/Figure4.jpg"><img src="http://www.nunoalves.com/open_source/wp-content/uploads/2013/05/Figure4.jpg" alt="Figure 4 - Interview question: What might happens when we suddenly open SW1?" width="300" class="size-full wp-image-529" /></a><p class="wp-caption-text">Figure 4 &#8211; Interview question: What might happens when we suddenly open SW1?</p></div><br />
<div id='stb-box-7232' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; "> When the solenoid L1 has been energized for a long time, it behaves as if it were a short with current flowing from the positive terminal of the voltage source to its negative terminal. When the switch is opened, the inductor will attempt to resist the sudden drop of current. A large negative potential is created where there once was positive potential, and a positive potential is created where there was once negative potential. This large potential difference can cause the electrons to &#8220;arc&#8221; across the switch.</p>
<p>A flyback diode solves this arc problem by allowing the inductor to draw current from itself in a continuous loop until the energy is dissipated through losses in the wire and across the diode. This is shown in Figure 5.</div></p>
<div id="attachment_530" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.nunoalves.com/open_source/wp-content/uploads/2013/05/Figure5.jpg"><img src="http://www.nunoalves.com/open_source/wp-content/uploads/2013/05/Figure5.jpg" alt="Figure 5 - Correct location and orientation of a flyback diode." width="300" class="size-full wp-image-530" /></a><p class="wp-caption-text">Figure 5 &#8211; Correct location and orientation of a flyback diode.</p></div>
<p><em>Question #11</em> &#8211; What is the purpose of an H-Bridge? Can you draw a generic H-bridge schematic?<br />
<div id='stb-box-4486' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; ">An H-Bridge is a circuit that allows us to control the direction of current flowing through a solenoid (e.g. a DC motor). Figure 6 shows how to control the direction of the current through L1 with the state of the switch SW1.</div><br />
<div id="attachment_531" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.nunoalves.com/open_source/wp-content/uploads/2013/05/Figure6.jpg"><img src="http://www.nunoalves.com/open_source/wp-content/uploads/2013/05/Figure6.jpg" alt="Figure 6 - Generic implementation of an H-Bridge using npn-transistors. " width="300" class="size-full wp-image-531" /></a><p class="wp-caption-text">Figure 6 &#8211; Generic implementation of an H-Bridge using npn-transistors.<br /></p></div></p>
<p><em>Question #12</em> &#8211; Consider the very generic circuit on Figure 7. What happens when SW1 changes states?<br />
<div id='stb-box-4115' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; "> Whenever SW1 is open, no current will flow into the base of the Q1 npn transistor, so the bjt will be OFF. This means both inputs of the NAND gate will be pulled to ground (which is a zero binary sate). Two logic-zeros at the input of a NAND gate imply a logic-one at the output. Since the output of the NAND gate is at the same potential as V1, no current will flow through R2 and D1, which means the LED will be off.<br />
If SW1 is closed, the Q1 bjt will be ON, and the inputs of the NAND gate will be set at logic-ones. This implies a logic-zero at the output of the NAND gate, which in turn enables current to flow through R2 and D1.</div><br />
<div id="attachment_532" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.nunoalves.com/open_source/wp-content/uploads/2013/05/Figure7.jpg"><img src="http://www.nunoalves.com/open_source/wp-content/uploads/2013/05/Figure7.jpg" alt="Figure 7 - Interview question: What happens to D1 whenever SW1 is pressed?" width="300" class="size-full wp-image-532" /></a><p class="wp-caption-text">Figure 7 &#8211; Interview question: What happens to D1 whenever SW1 is pressed?</p></div></p>
<p><em>Question #13</em> &#8211; What is an interrupt?<br />
<div id='stb-box-1782' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; "> An interrupt is the result of an event that tells the microprocessor to stop executing the current task, when appropriate, and execute another piece of code, called the interrupt service routine (ISR).</div></p>
<p><em>Question #14</em> &#8211; What is RS232?<br />
<div id='stb-box-3923' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; ">  RS-232 is a communication standard for a series of standards for serial binary signals. This standard defines the electrical characteristics and timing of signals, the meaning of signals, and the physical size and pin out of connectors.<br />
* In RS-232, user data is sent as a time-series of bits.<br />
* Both synchronous and asynchronous transmissions are supported.<br />
* The RS-232 standard defines the voltage levels that correspond to logical one and logical zero levels for the signal: valid signals are plus or minus 3 to 15 volts; the ±3 V range near zero volts is not a valid RS-232 level.<br />
* The devices at both ends of a RS-232 compatible cable agree on the bit transmission rate (e.g. 9600 baud, which corresponds to 9600 bits transferred per second). </div></p>
<p><strong>Conclusion</strong><br />
Even with a relatively straight forward interview process, with a strong emphasis on the basics, we have had a difficult time recruiting skilled recent graduates. For those looking for a entry-level position, I strongly recommend to come prepared to the interviews. Spend a couple of days solving  technical exercises straight from inexpensive books such as: </p>
<li> <a href="http://www.amazon.com/gp/product/0071362703/ref=as_li_qf_sp_asin_tl?ie=UTF8&#038;camp=1789&#038;creative=9325&#038;creativeASIN=0071362703&#038;linkCode=as2&#038;tag=nunoalvescom-20" target="_blank">Schaum&#8217;s Outline of Electronic Devices and Circuits, by Cathey</a></li>
<li><a href="http://www.amazon.com/gp/product/0071635289/ref=as_li_tf_tl?ie=UTF8&#038;camp=1789&#038;creative=9325&#038;creativeASIN=0071635289&#038;linkCode=as2&#038;tag=nunoalvescom-20" target="_blank">Schaum&#8217;s Outline of Basic Electricity, by Gussow</a></li>
<li><a href="http://www.amazon.com/gp/product/0071771336/ref=as_li_tf_tl?ie=UTF8&#038;camp=1789&#038;creative=9325&#038;creativeASIN=0071771336&#038;linkCode=as2&#038;tag=nunoalvescom-20" target="_blank">Practical Electronics for Inventors, by Scherz and Monk</a></li>
<p>In addition keep reading and subscribing to magazines such as Elektor,  Make, Circuit Cellar and, of course, Nuts And Volts.</p>
<p><center><br />
<script type="text/javascript"><!--
google_ad_client = "ca-pub-4338952704608042";
/* Wunderkammer */
google_ad_slot = "8709913020";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
</center> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.nunoalves.com/open_source/?feed=rss2&#038;p=486</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sending J1939 CAN-BUS messages with Sparkfun CAN-BUS Shield</title>
		<link>http://www.nunoalves.com/open_source/?p=475</link>
		<comments>http://www.nunoalves.com/open_source/?p=475#comments</comments>
		<pubDate>Wed, 26 Sep 2012 19:05:51 +0000</pubDate>
		<dc:creator>Nuno Alves</dc:creator>
				<category><![CDATA[Embedded Systems]]></category>
		<category><![CDATA[Arduino]]></category>
		<category><![CDATA[C/C++]]></category>
		<category><![CDATA[CAN]]></category>

		<guid isPermaLink="false">http://www.nunoalves.com/open_source/?p=475</guid>
		<description><![CDATA[Keeping in the spirit of open-source, I have modified the libraries of the Sparkfun CAN-BUS shield. With these updated libraries we are now able to send messages using the standard identifier (11 bits) and also send messages with the extended identifier (29 bits). I am running the following code in Arduino UNO. This particular CAN-BUS [...]]]></description>
				<content:encoded><![CDATA[<p>Keeping in the spirit of open-source, I have modified the libraries of the <a href="https://www.sparkfun.com/products/10039">Sparkfun CAN-BUS shield</a>. With these updated libraries we are now able to send messages using the standard identifier (11 bits) and also send messages with the extended identifier (29 bits).</p>
<p>I am running the following code in Arduino UNO. This particular CAN-BUS shield does not work with the latest Arduino board (Leonardo). Anyway, here is a simple Arduino program that continuously sends J1939 messages through the CAN network. </p>
<p></p><pre class="crayon-plain-tag">#include &lt;Canbus.h&gt;
#include &lt;defaults.h&gt;
#include &lt;global.h&gt;
#include &lt;mcp2515.h&gt;
#include &lt;mcp2515_defs.h&gt;

void setup()
{  
  Serial.begin(9600);
  
  //Initialise MCP2515 CAN controller at the specified speed
  if(Canbus.init(CANSPEED_250)) 
    Serial.println("CAN Init ok");
  else 
    Serial.println("Can't init CAN");

  delay(1000); 
}
 

void loop()
{
  static char counter=0;
  
  tCAN message;

  message.id = 0x00FF50FF;
  message.header.rtr = 0;
  message.header.length = 8;
  message.data[0] = 0x02;
  message.data[1] = 0x01;
  message.data[2] = 0xFF;
  message.data[3] = counter;
  message.data[4] = 0x00;
  message.data[5] = 0x00;
  message.data[6] = 0x00;
  message.data[7] = 0x00;						

  mcp2515_bit_modify(CANCTRL, (1&lt;&lt;REQOP2)|(1&lt;&lt;REQOP1)|(1&lt;&lt;REQOP0), 0);
  mcp2515_send_message_J1939(&amp;message);
  counter++;  

  delay(1000);
}</pre><p> </p>
<p><a href="http://www.nunoalves.com/open_source/wp-content/uploads/2012/09/Screen-Shot-2012-09-26-at-2.39.00-PM.png"><img src="http://www.nunoalves.com/open_source/wp-content/uploads/2012/09/Screen-Shot-2012-09-26-at-2.39.00-PM-300x198.png" alt="" title="Screenshot of the sample arduino CAN messages captured with the program CANviaUSB" width="300" height="198" class="aligncenter size-medium wp-image-476" /></a></p>
<p>The updated MCP2515 libraries can be found at <a href="http://www.nunoalves.com/source/canbus_nca26_09_2012.zip">http://www.nunoalves.com/source/canbus_nca26_09_2012.zip</a>. To install this library and use it with your Arduino projects just drop it in the appropriate sub-directory (e.g. ~/Documents/Arduino/libraries in macosx). For reference <a href="http://www.nunoalves.com/source/21801d.pdf">here is the data sheet for the MCP2515 SPI CAN transceiver</a>. I found all the information in there.</p>
<p>Finally&#8230; a big thank you to Fabian Greif and his initial efforts on the MCP2515 library.</p>
<p><center><br />
<script type="text/javascript"><!--
google_ad_client = "ca-pub-4338952704608042";
/* Wunderkammer */
google_ad_slot = "8709913020";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
</center> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.nunoalves.com/open_source/?feed=rss2&#038;p=475</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Converting base-16 roman numbers to arabic numbers (and vice-versa)</title>
		<link>http://www.nunoalves.com/open_source/?p=458</link>
		<comments>http://www.nunoalves.com/open_source/?p=458#comments</comments>
		<pubDate>Mon, 02 Jul 2012 23:48:45 +0000</pubDate>
		<dc:creator>Nuno Alves</dc:creator>
				<category><![CDATA[Programming Languages]]></category>
		<category><![CDATA[Mac OS X]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Unittest]]></category>

		<guid isPermaLink="false">http://www.nunoalves.com/open_source/?p=458</guid>
		<description><![CDATA[Here is neat python programming challenge. A hex roman numeral is very much like the standard roman numeral, except with different values. In normal roman numerals, I = 1, V = 5, X = 10 and so on. In hex roman numerals, I = 1, V = 8, X = 16, L = 128, C [...]]]></description>
				<content:encoded><![CDATA[<p>Here is neat python programming challenge. </p>
<p>A hex roman numeral is very much like the standard roman numeral, except  with different values. In normal roman numerals, I = 1, V = 5, X = 10  and so on. In hex roman numerals, I = 1, V = 8, X = 16, L = 128, C = 256, D = 2048 and M = 4096. So for example: </p>
<p>VIIII = 8 + 1 + 1 + 1 + 1 = 12<br />
IX = 16 &#8211; 1 = 15<br />
XV = 16 + 8 = 24<br />
XL = 128 &#8211; 16 = 112 </p>
<p>The goal is to write a program in python that converts it in either direction. If given a decimal number, it should return the hex roman numeral version of the  number and if given a hex roman numeral, it should return the decimal version of the number.</p>
<p>I started this by creating a program that performs a normal roman to arabic conversion. This wasn&#8217;t too hard, especially since python has a ton of neat features such as as dictionaries and solid string parsing methods. Since I am using <b>unittest</b> to test my code,  I&#8217;ve named this file <i>roman_numerals.py</i>.</p>
<p></p><pre class="crayon-plain-tag">import sys, re

def roman_to_arabic(number):
	"""return the roman numeral string representation of integer number"""
	roman_dict={"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
	lst = [ roman_dict[i] for i in list(number) ]
	
	for n in xrange(len(lst)-1):
  		if (lst[n]&lt;lst[n+1]): lst[n]=-lst[n]
  		
	return(sum(lst))

def arabic_to_roman(number):
	"""return the arabic numeral integer representation of roman string number"""
	units     = ("I","II","III","IV","V","VI","VII","VIII","IX","")
	tens      = ("X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC", "")
	hundreds  = ("C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM", "")
	thousands = ("M", "MM", "MMM", "MMMM","MMMMM","MMMMM","MMMMMM","MMMMMMM","MMMMMMMM","")

	#not quite sure how the romans dealt with very small or very large
	#numbers... also not quite sure how they worked with floating points
	assert(number&lt;=7000)		
	assert(number&gt;0)
		
	a=list(str(number))		#string-ify numbers
	b=a[-1::-1] 			#reverse order of list

	conversion=""
	
	if (len(b)&gt;0): conversion=units[eval(b[0])-1]+conversion
	if (len(b)&gt;1): conversion=tens[eval(b[1])-1]+conversion
	if (len(b)&gt;2): conversion=hundreds[eval(b[2])-1]+conversion
	if (len(b)&gt;3): conversion=thousands[eval(b[3])-1]+conversion
	return(conversion)		

if __name__== '__main__': 
	try:
		if (re.match("I|V|X|L|D|C|M", sys.argv[1])):
			print roman_to_arabic(sys.argv[1])
		else:
			print arabic_to_roman(eval(sys.argv[1]))
	except:
		print "Error: You either specified an: \n\t-invalid number \n\t-out of [1 to 7000] range \n\t-inexistent number"</pre><p> </p>
<p>The package <i>unittest</i> provides a great way to test your programs. I love it. You can pretty much run a another script and it will perform all the necessary assertions as it tests the proper package. Here is my unittest code, which I named <i>test_roman_numerals.py</i>.</p>
<p></p><pre class="crayon-plain-tag">import unittest, roman_numerals

class ProductTestCase(unittest.TestCase):
	def test_arabic_to_roman(self):
		self.failUnless("I"==roman_numerals.arabic_to_roman(1))
		self.failUnless("III"==roman_numerals.arabic_to_roman(3))
		self.failUnless("V"==roman_numerals.arabic_to_roman(5))
		self.failUnless("X"==roman_numerals.arabic_to_roman(10))
		self.failUnless("XI"==roman_numerals.arabic_to_roman(11))
		self.failUnless("VIII"==roman_numerals.arabic_to_roman(8))
		self.failUnless("IX"==roman_numerals.arabic_to_roman(9))
		self.failUnless("XV"==roman_numerals.arabic_to_roman(15))
		self.failUnless("XL"==roman_numerals.arabic_to_roman(40))
		self.failUnless("CXV"==roman_numerals.arabic_to_roman(115))
		self.failUnless("XLVI"==roman_numerals.arabic_to_roman(46))
		self.failUnless("MMXII"==roman_numerals.arabic_to_roman(2012))
		
	def test_roman_to_arabic(self):
		self.failUnless(1==roman_numerals.roman_to_arabic("I"))
		self.failUnless(3==roman_numerals.roman_to_arabic("III"))
		self.failUnless(5==roman_numerals.roman_to_arabic("V"))
		self.failUnless(10==roman_numerals.roman_to_arabic("X"))
		self.failUnless(11==roman_numerals.roman_to_arabic("XI"))
		self.failUnless(8==roman_numerals.roman_to_arabic("VIII"))
		self.failUnless(9==roman_numerals.roman_to_arabic("IX"))
		self.failUnless(15==roman_numerals.roman_to_arabic("XV"))
		self.failUnless(40==roman_numerals.roman_to_arabic("XL"))
		self.failUnless(115==roman_numerals.roman_to_arabic("CXV"))
		self.failUnless(46==roman_numerals.roman_to_arabic("XLVI"))
		self.failUnless(2012==roman_numerals.roman_to_arabic("MMXII"))

if __name__== '__main__': unittest.main()</pre><p> </p>
<p>Here are some screenshots of the program in action: first testing through the command line, and then testing it with <b>unittest</b>.<br />
<a href="http://www.nunoalves.com/open_source/wp-content/uploads/2012/07/Screen-Shot-2012-07-02-at-7.37.17-PM.png"><img src="http://www.nunoalves.com/open_source/wp-content/uploads/2012/07/Screen-Shot-2012-07-02-at-7.37.17-PM-300x116.png" alt="" title="Screen Shot 2012-07-02 at 7.37.17 PM" width="300" height="116" class="aligncenter size-medium wp-image-460" /></a></p>
<p>Taking this base code and making it compatible with base-16 numerals was trivial. All that I needed to do was make a minor modification to the dictionary roman_dict and adding extra elements to the lists units, tens, hundreds and thousands. Of course I had to perform a base conversion with the hex2dec function each time I wanted to access a position in the list.<br />
Here is the code that converts base-16 roman numbers to arabic numbers. I saved this file as <i>roman_numerals_base16.py</i>.</p>
<p></p><pre class="crayon-plain-tag">import sys, re

def roman_to_hex_arabic(number):
	"""return the roman numeral string representation of integer number"""
	roman_dict={"I":1,"V":8,"X":16,"L":128,"C":256,"D":2048,"M":4096}
	lst = [ roman_dict[i] for i in list(number) ]
	
	for n in xrange(len(lst)-1):
  		if (lst[n]&lt;lst[n+1]): lst[n]=-lst[n]
  		
	return(sum(lst))

def arabic_to_hex_roman(number):
	"""return the arabic numeral integer representation of roman string number"""
	units     = ("I", "II", "III", "IIII", "IIIII", "IIIIII", "IV", "V", "VI", "VII", "VIII", "VIIII", "VIIIII", "VIIIIII", "IX", "")
	tens      = ("X", "XX", "XXX", "XXXX", "XXXXX", "XXXXXX", "XL", "L", "LX", "LXX", "LXXX", "LXXXX", "LXXXXX", "LXXXXXX", "XC", "")
	hundreds  = ("C", "CC", "CCC", "CCCC", "CCCCC", "CCCCCC", "CD", "D", "DC", "DCC", "DCCC", "DCCCC", "DCCCCC", "DCCCCCC", "CM", "")
	thousands = ("M", "MM", "MMM", "MMMM","MMMMM","MMMMM","MMMMMM","MMMMMMM","MMMMMMMM","")

	#not quite sure how the romans dealt with very small or very large
	#numbers... also not quite sure how they worked with floating points
	assert(number&lt;=7000)		
	assert(number&gt;0)
		
	a=list(str(dec2hex(number)))	#string-ify numbers
	b=a[-1::-1] 					#reverse order of list

	conversion=""
	
	if (len(b)&gt;0): conversion=units[hex2dec(b[0])-1]+conversion
	if (len(b)&gt;1): conversion=tens[hex2dec(b[1])-1]+conversion
	if (len(b)&gt;2): conversion=hundreds[hex2dec(b[2])-1]+conversion
	if (len(b)&gt;3): conversion=thousands[hex2dec(b[3])-1]+conversion
	return(conversion)		

def dec2hex(n):
    """return the hexadecimal string representation of integer n"""
    return "%X" % n

def hex2dec(s):
    """return the integer value of a hexadecimal string s"""
    return int(s, 16)
        		

if __name__== '__main__': 
	try:
		if (re.match("I|V|X|L|D|C|M", sys.argv[1])):
			print roman_to_hex_arabic(sys.argv[1])
		else:
			print arabic_to_hex_roman(eval(sys.argv[1]))
	except:
		print "Error: You either specified an: \n\t-invalid number \n\t-out of [1 to 7000] range \n\t-inexistent number"</pre><p> </p>
<p>And here are my test cases, taken directly from the problem statement and saved as <i>test_roman_numerals_base16.py</i>.</p>
<p></p><pre class="crayon-plain-tag">import unittest, roman_numerals_base16

class ProductTestCase(unittest.TestCase):
	def test_arabic_to_hex_roman(self):
		self.failUnless("VIIII"==roman_numerals_base16.arabic_to_hex_roman(12))
		self.failUnless("IX"==roman_numerals_base16.arabic_to_hex_roman(15))
		self.failUnless("XV"==roman_numerals_base16.arabic_to_hex_roman(24))
		self.failUnless("XL"==roman_numerals_base16.arabic_to_hex_roman(112))		
		self.failUnless("XI"==roman_numerals_base16.arabic_to_hex_roman(17))		

	def test_roman_to_hex_arabic(self):
		self.failUnless(12==roman_numerals_base16.roman_to_hex_arabic("VIIII"))
		self.failUnless(15==roman_numerals_base16.roman_to_hex_arabic("IX"))
		self.failUnless(24==roman_numerals_base16.roman_to_hex_arabic("XV"))
		self.failUnless(112==roman_numerals_base16.roman_to_hex_arabic("XL"))
		self.failUnless(17==roman_numerals_base16.roman_to_hex_arabic("XI"))
		
if __name__== '__main__': unittest.main()</pre><p> </p>
<p>Finally, here is a screenshot of the program in action.</p>
<p><a href="http://www.nunoalves.com/open_source/wp-content/uploads/2012/07/Screen-Shot-2012-07-02-at-7.45.47-PM.png"><img src="http://www.nunoalves.com/open_source/wp-content/uploads/2012/07/Screen-Shot-2012-07-02-at-7.45.47-PM-300x107.png" alt="" title="Screen Shot 2012-07-02 at 7.45.47 PM" width="300" height="107" class="aligncenter size-medium wp-image-461" /></a></p>
<p><center><br />
<script type="text/javascript"><!--
google_ad_client = "ca-pub-4338952704608042";
/* Wunderkammer */
google_ad_slot = "8709913020";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
</center> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.nunoalves.com/open_source/?feed=rss2&#038;p=458</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Password protecting entire directories in MacOSX</title>
		<link>http://www.nunoalves.com/open_source/?p=427</link>
		<comments>http://www.nunoalves.com/open_source/?p=427#comments</comments>
		<pubDate>Tue, 26 Jun 2012 23:53:37 +0000</pubDate>
		<dc:creator>Nuno Alves</dc:creator>
				<category><![CDATA[Operating Systems]]></category>
		<category><![CDATA[Programming Languages]]></category>
		<category><![CDATA[Expect]]></category>
		<category><![CDATA[Mac OS X]]></category>

		<guid isPermaLink="false">http://www.nunoalves.com/open_source/?p=427</guid>
		<description><![CDATA[Every once in a while I have some files in a directory that need a password. I am not looking for a fancy encryption mechanism like PGP&#8230; I just want to compress the entire directory, put in a strong password and forget about it. Anyway, there are several applications that do this on the mac [...]]]></description>
				<content:encoded><![CDATA[<p>Every once in a while I have some files in a directory that need a password. I am not looking for a fancy encryption mechanism like PGP&#8230; I just want to compress the entire directory, put in a strong password and forget about it. Anyway, there are several applications that do this on the mac store&#8230; but none provide the flexibility that I was looking for. Plus, I realized this can be done in a couple of lines in the terminal.</p>
<p>Lets say you have a directory tmp with a bunch of files you want to compress and password protect it. You can go the standard route using the <i>zip</i> utility. Just type the following:<br />
<div id='stb-box-4298' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; ">zip storage.zip -R tmp/* -e</div><br />
This will compress the directory tmp/ and store all the files in the storage.zip. It will also ask you for the password you would like to use. Unfortunately you cannot give the password as an argument. So, you are stuck typing the password every time you want to compress a new directory.</p>
<p><a href="http://www.nunoalves.com/open_source/wp-content/uploads/2012/06/Screen-Shot-2012-06-26-at-7.40.00-PM.png"><img src="http://www.nunoalves.com/open_source/wp-content/uploads/2012/06/Screen-Shot-2012-06-26-at-7.40.00-PM-300x100.png" alt="" title="Compressing a directory and adding a password (manually)" width="300" height="100" class="aligncenter size-medium wp-image-428" /></a></p>
<p>There is a hack you can use to bypass the manually password submission&#8230; It involves using <i>expect</i>. This program is a really neat utility. It basically allows you to create interactive dialogues with your terminal programs, which makes task automation a walk in the park. You can check its manual pages <a href="https://developer.apple.com/library/mac/#documentation/Darwin/Reference/Manpages/man1/expect.1.html">here</a>.</p>
<p><b>Step #1</b>: Go into the mac terminal and find out where the <i>expect</i> utility is located. This is done using the <i>whereais</i> command. Type the following on your terminal window.<br />
<div id='stb-box-8715' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; ">whereis expect</div></p>
<p>In my macosx version, the program <i>expect</i> is located at <i>/usr/bin/expect</i>.<br />
<b>Step #2</b>: Create a file (e.g. protect_directory.sh) with the following lines. Make sure you modify the location of the expect program in the first line of the script.</p>
<p></p><pre class="crayon-plain-tag">#!/usr/bin/expect -f
eval spawn zip [lindex $argv 0].zip -R [lindex $argv 1]/* -e
expect "password:"
send "[lindex $argv 2]\r"
expect "password:"
send "[lindex $argv 2]\r"
interact</pre><p> </p>
<p><b>Step #3</b>: Make sure your script is executable and run it.<br />
<div id='stb-box-2011' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; ">chmod u=+rwx protect_directory.sh<br />
./protect_directory.sh file.zip tmp hello</div><br />
 The first argument will be the output filename (file.zip), the second argument is the directory you wish to compress (tmp) and the last argument is the password you wish to use (hello). Neat no? Here is a screenshot of all the steps.</p>
<p><a href="http://www.nunoalves.com/open_source/wp-content/uploads/2012/06/Screen-Shot-2012-06-26-at-7.48.16-PM.png"><img src="http://www.nunoalves.com/open_source/wp-content/uploads/2012/06/Screen-Shot-2012-06-26-at-7.48.16-PM-300x157.png" alt="" title="Screen Shot 2012-06-26 at 7.48.16 PM" width="300" height="157" class="aligncenter size-medium wp-image-432" /></a></p>
<p><center><br />
<script type="text/javascript"><!--
google_ad_client = "ca-pub-4338952704608042";
/* Wunderkammer */
google_ad_slot = "8709913020";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
</center> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.nunoalves.com/open_source/?feed=rss2&#038;p=427</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automatically leveling your Castlevania character with an Arduino</title>
		<link>http://www.nunoalves.com/open_source/?p=394</link>
		<comments>http://www.nunoalves.com/open_source/?p=394#comments</comments>
		<pubDate>Sat, 16 Jun 2012 22:13:36 +0000</pubDate>
		<dc:creator>Nuno Alves</dc:creator>
				<category><![CDATA[Embedded Systems]]></category>
		<category><![CDATA[Programming Languages]]></category>
		<category><![CDATA[Arduino]]></category>
		<category><![CDATA[C/C++]]></category>

		<guid isPermaLink="false">http://www.nunoalves.com/open_source/?p=394</guid>
		<description><![CDATA[I love playing video-games. Rarely play more than 1 hour a week these days&#8230; but when possible I put some time into old school PSone games&#8230; in particular Castlevania: Symphony of the Night. Phenomenal game! The only problem&#8230; is that there is some annoying grinding component to it. Anyway, on the weekends I also love [...]]]></description>
				<content:encoded><![CDATA[<p>I love playing video-games. Rarely play more than 1 hour a week these days&#8230; but when possible I put some time into old school PSone games&#8230; in particular <a href="http://en.wikipedia.org/wiki/Castlevania:_Symphony_of_the_Night">Castlevania: Symphony of the Night</a>. Phenomenal game! The only problem&#8230; is that there is some annoying <a href="http://en.wikipedia.org/wiki/Grinding_(video_gaming)">grinding</a> component to it.</p>
<p>Anyway, on the weekends I also love spending time with my son. Unfortunately, my son is 1.3 years old which means i can&#8217;t play with both at the same time. Time to optimize! I created a very simple system that repeatedly presses the same button over an over again. When the character is in an adequate location, it will repeatedly kill any enemies that are walking in his direction.</p>
<p><a href="http://www.nunoalves.com/open_source/wp-content/uploads/2012/06/ef162bd2b7fc11e192e91231381b3d7a_7.jpg"><img src="http://www.nunoalves.com/open_source/wp-content/uploads/2012/06/ef162bd2b7fc11e192e91231381b3d7a_7-300x300.jpg" alt="" title="A servo motor, a potentiometer, some wood and an Arduino" width="300" height="300" class="aligncenter size-medium wp-image-395" /></a></p>
<p>The point? I want to play the <i>hard</i> bosses and skip all the grinding. This simple contraption does the job. It is not pretty (all materials used were scavenged from here and there) but it works.</p>
<p>Here are two videos showing the machine in action&#8230;<br /><iframe class='youtube-player youtuber' type='text/html' width='425' height='355' src='http://www.youtube.com/embed/1NDvGS_n5W4?rel=0&amp;fs=1' webkitAllowFullScreen mozallowfullscreen allowFullScreen frameborder='0'></iframe></p>
<p><iframe class='youtube-player youtuber' type='text/html' width='425' height='355' src='http://www.youtube.com/embed/D2aaLdIl5Vk?rel=0&amp;fs=1' webkitAllowFullScreen mozallowfullscreen allowFullScreen frameborder='0'></iframe></p>
<p>And of course the Arduino source code&#8230; Everything was made, assembled and implemented in about 15 minutes. Automation FTW!</p>
<p></p><pre class="crayon-plain-tag">#include &lt;Servo.h&gt; 
 
Servo myservo; 
int potinput=0;
int delayvalue=0;

void setup() 
{ 
   myservo.attach(9); 
   pinMode(10, OUTPUT);
   digitalWrite(10,HIGH);
} 
 
void loop() 
{ 
   myservo.write(170);
   delay(delayvalue); 
   myservo.write(120);
   delay(delayvalue); 
   potinput=analogRead(0); 
   delayvalue = map(potinput, 0, 1022, 100, 2000);
}</pre><p> </p>
<p><center><br />
<script type="text/javascript"><!--
google_ad_client = "ca-pub-4338952704608042";
/* Wunderkammer */
google_ad_slot = "8709913020";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
</center> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.nunoalves.com/open_source/?feed=rss2&#038;p=394</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python and duck curses</title>
		<link>http://www.nunoalves.com/open_source/?p=384</link>
		<comments>http://www.nunoalves.com/open_source/?p=384#comments</comments>
		<pubDate>Fri, 18 May 2012 20:04:28 +0000</pubDate>
		<dc:creator>Nuno Alves</dc:creator>
				<category><![CDATA[Programming Languages]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.nunoalves.com/open_source/?p=384</guid>
		<description><![CDATA[Today at lunch I realized that life would be much easier if I could check the status of my simulations in some sort of interactive menu over ssh. When I got up to my office, someone told me about Python and curses. Curses is pretty much a module that allows you to deal with terminal-independent [...]]]></description>
				<content:encoded><![CDATA[<p>Today at lunch I realized that life would be much easier if I could check the status of my simulations in some sort of interactive menu over ssh. When I got up to my office, someone told me about Python and <a href="http://readthedocs.org/docs/cpython_sandbox/en/latest/howto/curses.html">curses</a>. Curses is pretty much a module that allows you to deal with terminal-independent screen-painting and keyboard-handling over text-based terminals.<br />
So&#8230; 10 minutes after reading <a href="http://www.dev-explorer.com/articles/python-with-curses">this neat tutorial</a>, and inspired by the craziness happening at <a href="http://en.wikipedia.org/wiki/38_Studios">38 studios</a>, I wrote my first game playable via ssh. You control a duck that collects worms&#8230; yes, how vapid.<br />
 <div id="attachment_385" class="wp-caption aligncenter" style="width: 281px"><a href="http://www.nunoalves.com/open_source/wp-content/uploads/2012/05/Screen-Shot-2012-05-18-at-2.59.32-PM.png"><img src="http://www.nunoalves.com/open_source/wp-content/uploads/2012/05/Screen-Shot-2012-05-18-at-2.59.32-PM-271x300.png" alt="" title="Screen Shot 2012-05-18 at 2.59.32 PM" width="271" height="300" class="size-medium wp-image-385" /></a><p class="wp-caption-text">Moving a duck with Python and curses</p></div><br />
<pre class="crayon-plain-tag">import curses, random
	
def draw_duck(top_pos,left_pos):
	duck=(
 		"    _      ",
 		"   =')_//  ",
 		"   (___/   ")
	screen.clear() 

	for iterator in duck:
		screen.addstr(top_pos, left_pos, iterator)
		top_pos+=1

def update_screen(top_pos,left_pos,worm_location,worms_eaten):
	draw_duck(top_pos,left_pos)
	if (top_pos+1==worm_location[0]) and (left_pos+1==worm_location[1]):
		worms_eaten+=1
		worm_location=[
			random.randrange(1, screen_dimensions[0]),
			random.randrange(1, screen_dimensions[1])
			]
	screen.addstr(worm_location[0], worm_location[1],"~")
	say_this="Score=%d duck=(%d,%d) worm=(%d,%d)" % (worms_eaten, top_pos , left_pos,  worm_location[0], worm_location[1])
	screen.addstr(21,0,say_this)
	return (worm_location,worms_eaten)

screen = curses.initscr() 
curses.noecho() 
curses.curs_set(0) 
screen.keypad(1)

worm_location=[
	random.randrange(1, screen_dimensions[0]),
	random.randrange(1, screen_dimensions[1])
	]
worms_eaten=0

screen.addstr("Use the cursor keys to move the duck!\n") 
top_pos  = 1
left_pos = 1 
while True: 
	event = screen.getch() 

	if event == ord("q"): break 
	elif event == curses.KEY_UP: 
		top_pos-=1
		if (top_pos&lt;=0): top_pos=0
		if (top_pos&gt;=20): top_pos=20
		worm_location, worms_eaten = update_screen(top_pos,left_pos,worm_location,worms_eaten)
		
	elif event == curses.KEY_DOWN: 
		top_pos+=1
		if (top_pos&lt;=0): top_pos=0
		if (top_pos&gt;=20): top_pos=20
		worm_location, worms_eaten = update_screen(top_pos,left_pos,worm_location,worms_eaten)
		
	elif event == curses.KEY_LEFT: 
		left_pos-=1
		if (left_pos&lt;=0): left_pos=0
		if (left_pos&gt;=20): left_pos=20
		worm_location, worms_eaten = update_screen(top_pos,left_pos,worm_location,worms_eaten)

	elif event == curses.KEY_RIGHT: 
		left_pos+=1
		if (left_pos&lt;=0): left_pos=0
		if (left_pos&gt;=20): left_pos=20
		worm_location, worms_eaten = update_screen(top_pos,left_pos,worm_location,worms_eaten)
     
	elif event == ord(" "): 
		screen.clear() 
		screen.addstr("Press 'q' to exit")
      		
curses.endwin()</pre> </p>
<p><center><br />
<script type="text/javascript"><!--
google_ad_client = "ca-pub-4338952704608042";
/* Wunderkammer */
google_ad_slot = "8709913020";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
</center> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.nunoalves.com/open_source/?feed=rss2&#038;p=384</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Choose your own adventure&#8230; in audio</title>
		<link>http://www.nunoalves.com/open_source/?p=371</link>
		<comments>http://www.nunoalves.com/open_source/?p=371#comments</comments>
		<pubDate>Thu, 17 May 2012 13:27:59 +0000</pubDate>
		<dc:creator>Nuno Alves</dc:creator>
				<category><![CDATA[Programming Languages]]></category>
		<category><![CDATA[Mac OS X]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.nunoalves.com/open_source/?p=371</guid>
		<description><![CDATA[One of the things that bores me the most is driving. Ten minutes into my daily commute and I am checking out my email and reading my twitter feed. Anyway, the other day when I was coming from Boston I had this interesting idea; why not create a choose your own adventure game, which could [...]]]></description>
				<content:encoded><![CDATA[<p>One of the things that bores me the most is driving. Ten minutes into my daily commute and I am checking out my email and reading my twitter feed. Anyway, the other day when I was coming from Boston I had this interesting idea; why not create a <a href="http://en.wikipedia.org/wiki/Choose_Your_Own_Adventure">choose your own adventure game</a>, which could be played while driving. Instead of reading a book, the book would be read to us by a speech synthesizer. The choices would be done by pressing buttons instead of manually flipping pages. The idea was so neat that I proceeded to create a prototype, so I could send it to a magazine, but the outcome was so bad that I pushed it aside until I find a better technology. For my failed prototype I used the linux open-source <a href="http://www.speech.cs.cmu.edu/flite/doc/">flite speech synthesizer</a> and a beagleboard XM. As the driving engine I created a simple script in python that read a particular story and used buttons to control the flow of the adventure. The first problem is that beagleboard requires a pretty clean 5V power supply which is a mess to get in a car. Also, the beagleboard is fairly expensive ($120) to use as a dedicated game engine. Finally, creating a customized OS that is fast enough to launch the a particular application on the beagleboard is not trivial. </p>
<p>Anyway, I still think that audio based interactive entertainment systems have potential, but my technical solution I chose was not the best. Most definitely I will revisit this idea soon with Android phones and tablets. Implementing this in android seems to be very easy, thanks to the <a href="http://ytai-mer.blogspot.com/2011/04/meet-ioio-io-for-android.html">IOIO connectors</a>. For those interested, this connector is available for purchase through <a href="http://www.sparkfun.com/products/10748">sparkfun</a>. Regardless, here is a very simple code for my choose your own adventure. It is done in python and if you have a macosx it will read out the entries and choices using the built in speech synthesizer.</p>
<p></p><pre class="crayon-plain-tag">import os 

#reads the current entry
def read_entry(entry_number, filename):
	f=open(filename,'r')
	found=False	
	for line in f.readlines():
		line=line.strip('\n')
		if line == '&lt;'+str(entry_number)+'&gt;':
			found=True	
		if (line == '[choices]') or line == '[end]':
			found=False	
		if (found==True) and (line!='&lt;'+str(entry_number)+'&gt;'):
			print line
			saythis="say %s" % line
			os.system(saythis) 
			
#creates a dictionary with the choices at each entry
def read_choices(entry_number, filename):
	f=open(filename,'r')
	entry_found=False
	choice_section=False	
	items={}
	for line in f.readlines():
		line=line.strip('\n')
		if line == '&lt;'+str(entry_number)+'&gt;':
			entry_found=True	
		if (entry_found==True) and (choice_section==True) and (line!='[end choices]'):			
			#remove "&gt;" from line 
			line=line.replace('&gt;','')
			#remove "-" from line 
			line=line.replace('-','')
			
			line=line.split('&lt;')
			x={line[0] : line[1]}
			items.update(x)
	
		if (entry_found==True) and (line=='[choices]'):
			choice_section=True		
		if (entry_found==True) and (line=='[end choices]'):			
			choice_section=False		
			entry_found=False	
		if (line=='[end]'):
			entry_found=False			
	return items

def ask_choices(choices):	
	saythis="What do you want to do?"
	print saythis
	saythis="say %s" % saythis
	os.system(saythis) 
	i=1
	for current_choice in list(choices):
		saythis='Choice number %d:' % i + '%s' %current_choice
		print saythis
		saythis="say %s" % saythis
		os.system(saythis) 
		i+=1
	saythis="What is your choice?"
	print saythis
	saythis="say %s" % saythis
	os.system(saythis) 
	user_choice=input('')
	key=list(choices)[user_choice-1]
	#the function return value is next story page
	return choices.get(key)
	
story_page=1
terminate=False
while terminate==False:		
	read_entry(story_page,'test_story.txt')
	choices=read_choices(story_page,'test_story.txt')
	#if there are no choices, then we reached the end
	if len(list(choices))==0:
		terminate=True 
	else:
		story_page=ask_choices(choices)</pre><p> </p>
<p>The story itself (hardwired on the previous file as <i>test_story.txt</i>) is pretty self-explanatory.<br />
<div id='stb-box-9922' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; "><1><br />
You are in the top of a very tall building.<br />
[choices]<br />
- Jump <2><br />
- Yell <3><br />
- Do nothing <1><br />
[end choices]<br />
<2><br />
You decided to jump&#8230; thats too bad.<br />
[end]<br />
<3><br />
You yell something. No one replies.<br />
[choices]<br />
- Jump <2><br />
- Do nothing <1><br />
[end choices]<br />
</div><br />
Finally, here is a screenshot of the program in action.<br />
<div id="attachment_376" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.nunoalves.com/open_source/wp-content/uploads/2012/05/Screen-Shot-2012-05-17-at-9.22.22-AM.png"><img src="http://www.nunoalves.com/open_source/wp-content/uploads/2012/05/Screen-Shot-2012-05-17-at-9.22.22-AM-300x178.png" alt="" title="Screen Shot 2012-05-17 at 9.22.22 AM" width="300" height="178" class="size-medium wp-image-376" /></a><p class="wp-caption-text">Running the python script...</p></div></p>
<p>Enjoy.</p>
<p><center><br />
<script type="text/javascript"><!--
google_ad_client = "ca-pub-4338952704608042";
/* Wunderkammer */
google_ad_slot = "8709913020";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
</center> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.nunoalves.com/open_source/?feed=rss2&#038;p=371</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Autonomously crawling through DICE job postings</title>
		<link>http://www.nunoalves.com/open_source/?p=276</link>
		<comments>http://www.nunoalves.com/open_source/?p=276#comments</comments>
		<pubDate>Fri, 13 Apr 2012 14:01:53 +0000</pubDate>
		<dc:creator>Nuno Alves</dc:creator>
				<category><![CDATA[Operating Systems]]></category>
		<category><![CDATA[Programming Languages]]></category>
		<category><![CDATA[Bash]]></category>
		<category><![CDATA[Mac OS X]]></category>
		<category><![CDATA[Mathematica]]></category>
		<category><![CDATA[Perl]]></category>

		<guid isPermaLink="false">http://www.nunoalves.com/open_source/?p=276</guid>
		<description><![CDATA[I am currently working on a book that requires me to search through thousands of job advertisements. For the last couple of days I have been looking at the various websites, collecting data and looking for patterns in employment listings. Even if you are not working on a book, I am sure at some point [...]]]></description>
				<content:encoded><![CDATA[<p>I am currently working on a book that requires me to search through thousands of job advertisements. For the last couple of days I have been looking at the various websites, collecting data and looking for patterns in employment listings. Even if you are not working on a book, I am sure at some point in time you will be looking for a new job online. I love searching for jobs, and if you don&#8217;t love it too&#8230; you are probably doing it wrong.<br />
First of all don&#8217;t manually search for jobs! It is a waste of time and it will drive you insane. Instead use a scripting language, such as PERL, that mines website databases and outlines the best matches. In fact I wrote a <a href="http://www.nunoalves.com/open_source/?p=252" title="Automated craigslist job search with Perl and Bash">post </a> a few days ago about mining employment postings on craigslist. If you are new to this entire field of data-mining, I recommend the book &#8220;mining the social web&#8221; by Russell&#8230; Nice chap&#8230;. Met him at Harvard Square a couple of years ago.<br />
<center><br />
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=nunoalvescom-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;ref=qf_sp_asin_til&#038;asins=1449388345" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe><br />
</center></p>
<p>Here I outline the steps I took to extract all job postings from <a href="http://www.dice.com">DICE</a>. First of all you have to know how everything is stored in the database. Make any random search on the initial screen (e.g. embedded).<br />
<div id="attachment_287" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.nunoalves.com/open_source/wp-content/uploads/2012/04/Screen-Shot-2012-04-09-at-10.39.09-AM.png"><img src="http://www.nunoalves.com/open_source/wp-content/uploads/2012/04/Screen-Shot-2012-04-09-at-10.39.09-AM-300x101.png" alt="" title="Screen Shot 2012-04-09 at 10.39.09 AM" width="300" height="101" class="size-medium wp-image-287" /></a><p class="wp-caption-text">&quot;Embedded&quot; search on dice.com</p></div></p>
<p>This particular search generated the following very-long URL&#8230; so long that I had to include spaces:<br />
<div id='stb-box-9092' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; ">http://seeker.dice.com/jobsearch/servlet/JobSearch?op=300&#038;N=0&#038;Hf=0&#038;NUM_PER_PAGE=30&#038;Ntk=JobSearchRanking&#038;Ntx=mode+matchall &#038;AREA_CODES=&#038;AC_COUNTRY=1525&#038;QUICK=1&#038;ZIPCODE=&#038;RADIUS=64.37376 &#038;ZC_COUNTRY=0&#038;COUNTRY=1525&#038;STAT_PROV=0&#038;METRO_AREA=33.78715899%2C-84.39164034&#038;TRAVEL=0&#038;TAXTERM=0&#038;SORTSPEC=0&#038;FRMT=0 &#038;DAYSBACK=30&#038;LOCATION_OPTION=2&#038;FREE_TEXT=embedded&#038;WHERE=</div></p>
<p>Since this particular search detected 1689 job postings, we just have to change <b>NUM_PER_PAGE=30</b> from 30 to 1689, in order to see every single job post on a single page. Save that file into your hard-disk in the HTML format. For completeness, <a href='http://www.nunoalves.com/open_source/wp-content/uploads/2012/04/embedded_Jobs_at_Dice.html'>here is the file</a> with all 1689 postings I just downloaded. The following PERL script parses the contents of this file and looks for the associated URL for each job posting. </p>
<p></p><pre class="crayon-plain-tag">#neat function that helps catching scripting errors like undefined variables...
use strict;

#use the generated HTML as an input argument
my $input_file=$ARGV[0];

#parse through every single line in the file
open (MYFILE, &quot;&lt;$input_file&quot;) or die $!;
 while (&lt;MYFILE&gt;) {
 	chomp;
 	#each job posting starts with a well defined pattern...
	#search for &lt;div&gt;&lt;a href=&quot;/jobsearch/servlet/Jo
	if (/&lt;div&gt;&lt;a href=\&quot;\/jobsearch\/servlet\/Jo/)
	{
		#...the following line:
		#print &quot;$_\n&quot;;
		#...will print for example:
		#&lt;div&gt;&lt;a href=&quot;/jobsearch/servlet/JobSearch?op=302&amp;amp;dockey=xml/7/0/70b58be12a872e8268939a525389b927@endecaindex&amp;amp;source=19&amp;amp;FREE_TEXT=embedded&amp;amp;rating=99&quot;&gt;ASIC/FPGA Verification Engineer&lt;/a&gt;&lt;/div&gt;

		#get the job title
		my $job_title;
		my @tmp_data;

		@tmp_data=split(/&quot;&gt;|&lt;\/a&gt;&lt;\/div&gt;/,$_);		
		$job_title=$tmp_data[1];
		#...the following line:
		#print $job_title . &quot;\n&quot;;
		#...will print for example:
		#ASIC/FPGA Verification Engineer


		@tmp_data=split(/&quot;&gt;|div&gt;&lt;a href=&quot;\//,$_);
		#...the following line:
		#print $tmp_data[1] . &quot;\n&quot;;	
		#...will print for example:	#jobsearch/servlet/JobSearch?op=302&amp;amp;dockey=xml/7/0/70b58be12a872e8268939a525389b927@endecaindex&amp;amp;source=19&amp;amp;FREE_TEXT=embedded&amp;amp;rating=99

		#but that is not the correct URL... instead we want something like:	#http://seeker.dice.com/jobsearch/servlet/JobSearch?op=302&amp;dockey=xml/b/4/b4ba4b9ed60baf2cf7a3397f336e451e@endecaindex&amp;source=19&amp;FREE_TEXT=embedded&amp;rating=0

		#in essence, we must replace all &amp;amp; with &amp;
		$tmp_data[1] =~ s/\&amp;amp;/\&amp;/g;
		$tmp_data[1] =~ s/\/jobsearch\/servlet//g;
		print &quot;http://seeker.dice.com/&quot; . $tmp_data[1] . &quot;\n&quot;;
	}
 }
 close (MYFILE);</pre><p></p>
<p>Save the file (e.g. dice.pl) and  execute it with the following command:<br />
<div id='stb-box-1375' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; ">perl dice.pl embedded_Jobs_at_Dice.html > embedded_url.txt</div><br />
This will store every single URL, one per line, in the file embedded_url.txt. Once again&#8230; for completeness, <a href='http://www.nunoalves.com/open_source/wp-content/uploads/2012/04/embedded_url.txt'>here is my generated file</a>.</p>
<p>The next step is to download every single job posting onto a separate file. Since, I am a macsox user, I need to download a the contents of each of the URLs from the web via the OS X command line. This is easy accomplished with the following bash script:</p>
<p></p><pre class="crayon-plain-tag">FILENAME=embedded_url.txt

NUMBERLINES=&#96;wc -l &lt;  ${FILENAME}&#96;
echo ${NUMBERLINES} &gt; xxx.tmp
PNUMBERLINES=&#96;perl -n -e '@splitline=split(/ /,$_); $splitline[1]=~s/ //g; print $splitline[0] ."\n"; ' xxx.tmp&#96;
rm -f xxx.tmp
echo ${PNUMBERLINES}

RUN=0
until [ ${RUN} -eq ${PNUMBERLINES} ]
do
    RUN=$(( $RUN + 1 ))
    LCONTENTS=&#96;sed -n $RUN'p' ${FILENAME}&#96;
    #echo "line # ${RUN} with contents : ${LCONTENTS}"
    wget "${LCONTENTS}"
done</pre><p> </p>
<p>On the same directory as the output of the previous PERL script (e.g. embedded_url.txt), save this bash scrip (e.g. download_all_jobs.sh) and execute it with the following commands:<br />
<div id='stb-box-1587' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; ">chmod u=+rwx download_all_jobs.sh<br />
./download_all_jobs.sh embedded_url.txt</div></p>
<p>The compressed outcome of this last step is a <a href="http://www.nunoalves.com/source/dice_jobs.zip">file of 27 MBs</a>.</p>
<p>Now that I have all this data, I need to extract the skills required for each advertised position. So, I placed all the compressed files in the sub-directory dice_jobs and ran the following script:</p><pre class="crayon-plain-tag">#!/bin/bash
JOBS_DIRECTORY=dice_jobs

ls ${JOBS_DIRECTORY}/* > all_jobs.txt

#count the number of lines on each file
impcount=&#96;wc -l <  all_jobs.txt&#96;
echo ${impcount} > xxx.tmp
NIMPS=&#96;perl -n -e '@splitline=split(/ /,$_); $splitline[1]=~s/ //g; print $splitline[0] ."\n"; ' xxx.tmp&#96;;
rm -f xxx.tmp

#rename jobs postings into something more readable
RUN=1
until [ $RUN -gt ${NIMPS} ]
do
	FNAME=`sed -n $RUN'p' all_jobs.txt`	
	mv ${FNAME} ${JOBS_DIRECTORY}/${RUN}.txt
	RUN=$(( $RUN + 1 ))
done

#extract the job title and necessary skills
rm -f parsed_job_data.txt
RUN=1
until [ $RUN -gt ${NIMPS} ]
do
	FNAME=`sed -n $RUN'p' all_jobs.txt`	
	perl extract_data.pl ${JOBS_DIRECTORY}/${RUN}.txt >> parsed_job_data.txt
	RUN=$(( $RUN + 1 ))
done

rm -f all_jobs.txt
echo "...parsed job data is @ parsed_job_data.txt"</pre><p> </p>
<p>The skill extraction is actually done on the following PERL script (<i>extract_data.pl</i>).</p>
<p></p><pre class="crayon-plain-tag">use strict;

#use the generated HTML as an input argument
my $input_file=$ARGV[0];

my $next_line_is_job_title=0;
my $jobTitle=&quot;&quot;;

my $next_line_is_area_code=0;
my $areaCode=&quot;&quot;;

my $next_line_is_skills=0;
my $skills=&quot;&quot;;

my $next_line_is_company_name=0;
my $companyName=&quot;&quot;;

#parse through every single line in the file
open (MYFILE, &quot;&lt;$input_file&quot;) or die $!;
 while (&lt;MYFILE&gt;) {
 	#chomp;
	
	if ($next_line_is_skills==1)
	{
		$skills=$_;
		$skills =~ s/&lt;dd&gt;|&lt;dt&gt;|&lt;\/dt&gt;|&lt;\/dd&gt;|&amp;nbsp;|\t|\n//g;
		$skills =~ s/\/assets\/images\/detail\/default\/highlite.gif//g;
		$skills =~ s/&lt;b style=&quot;background:url\(//g;
		$skills =~ s/\); font-weight: bold;&quot;&gt;|&lt;\/b&gt;//g;
		#print &quot;skills=&quot; . $skills . &quot;\n&quot;;
		$next_line_is_skills=0;
	}
	
	if ($next_line_is_company_name==1)
	{
		$companyName=$_;
		$companyName =~ s/&lt;dd&gt;|&lt;dt&gt;|&lt;\/dt&gt;|&lt;\/dd&gt;|&amp;nbsp;|\t|\n//g;
		my @splitString=split(/&gt;|&lt;/,$companyName);
		$companyName = $splitString[2];
		$next_line_is_company_name=0;

		#print &quot;companyName = &quot; . $companyName . &quot;\n&quot;;
	}

	if ($next_line_is_area_code==1)
	{
		$areaCode=$_;
		$areaCode =~ s/&lt;dd&gt;|&lt;\/dd&gt;|&lt;dt&gt;|&lt;\/dt&gt;|&amp;nbsp;|\t|\n//g;
		$next_line_is_area_code=0;

		#print &quot;areaCode=&quot; . $areaCode . &quot;\n&quot;;
	}

	if (/&lt;h1 id=&quot;jobTitle&quot;&gt;/)
	{
		my @split_tmp=split(/&gt;|&lt;/,$_);
		$jobTitle=@split_tmp[2];

		#print &quot;jobTitle=&quot; . $jobTitle . &quot;\n&quot;;
	}
	
	if (/&lt;dt&gt;Skills:&lt;\/dt&gt;|&lt;dd&gt;Skills&lt;\/dd&gt;/) { $next_line_is_skills=1; }
	
	if (/&lt;dt&gt;Company:|&lt;dd&gt;Company/) { $next_line_is_company_name=1; }
	
	if (/&lt;dt&gt;Area Code:|&lt;dd&gt;Area Code/) { $next_line_is_area_code=1; }
	
 }
 close (MYFILE); 
 
 print &quot;$input_file\t$companyName\t$jobTitle\t$areaCode\t$skills\n&quot;;</pre><p></p>
<p>I then feed the extracted data into a mathematica script; a (readable) pdf version of the Mathematica script is <a href='http://www.nunoalves.com/open_source/wp-content/uploads/2012/04/visual_display1.pdf'>here</a>, and the source is <a href='http://www.nunoalves.com/source/visual_display.nb'>here</a>. In this script,  I combined all found skills, ignored skills that were required in less than 30 distinct advertisement (e.g. COBOL and Pascal). Below is the resulting piechart.</p>
<div id="attachment_350" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.nunoalves.com/open_source/wp-content/uploads/2012/04/Screen-Shot-2012-04-13-at-9.24.48-AM.png"><img src="http://www.nunoalves.com/open_source/wp-content/uploads/2012/04/Screen-Shot-2012-04-13-at-9.24.48-AM-300x296.png" alt="" title="Screen Shot 2012-04-13 at 9.24.48 AM" width="300" height="296" class="size-medium wp-image-350" /></a><p class="wp-caption-text">Most requested skills in embedded computing jobs.</p></div>
<p>As expected the most sought after skills in &#8220;embedded computing&#8221; jobs are C,C++ and Linux. Java, mysql and kernel development is also very strong in demand these days.  Surprisingly I saw lots of mobile computing and networking skill requests. However the most surprisingly requested skills is databases (mysql)! </p>
<p>Finally, I am aware that I could have done everything on this post on a single PERL script. However, writing a post about a single script would get tedious very quickly. I also wanted to save the outcome of every single step in my hard-disk so I could perform some additional data tests, without having to connect to dice.com each time.</p>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-4338952704608042";
/* Wunderkammer */
google_ad_slot = "8709913020";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.nunoalves.com/open_source/?feed=rss2&#038;p=276</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Start a C program when BeagleBone boots</title>
		<link>http://www.nunoalves.com/open_source/?p=308</link>
		<comments>http://www.nunoalves.com/open_source/?p=308#comments</comments>
		<pubDate>Wed, 11 Apr 2012 02:04:14 +0000</pubDate>
		<dc:creator>Nuno Alves</dc:creator>
				<category><![CDATA[Embedded Systems]]></category>
		<category><![CDATA[Programming Languages]]></category>
		<category><![CDATA[Beagle Bone]]></category>
		<category><![CDATA[C/C++]]></category>

		<guid isPermaLink="false">http://www.nunoalves.com/open_source/?p=308</guid>
		<description><![CDATA[I&#8217;ve been spending some time lately trying to turn the BeagleBone into a &#8220;single-serving&#8221; system for my prototypes. Most of these prototypes require running some program whenever the system gets power. Before you continue, I strongly recommend you read my previous BeagleBone posts, if you start feeling a bit lost. So here I have a [...]]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ve been spending some time lately trying to turn the BeagleBone into a &#8220;single-serving&#8221; system for my prototypes. Most of these prototypes require running some program whenever the system gets power. Before you continue, I strongly recommend you read my previous BeagleBone posts, if you start feeling a bit lost.</p>
<p>So here I have a very simple circuit&#8230; 5 LEDs connected to 5 different pins (P8_3,P8_4,P8_5,P8_11,P8_12). I would like these LEDs to display a perform a simple pattern whenever the BeagleBone is turned ON. Something like the following video.<br />
<center><iframe class='youtube-player youtuber' type='text/html' width='425' height='355' src='http://www.youtube.com/embed/cFHpJ-VIvlU?rel=0&amp;fs=1' webkitAllowFullScreen mozallowfullscreen allowFullScreen frameborder='0'></iframe></center></p>
<p>The code for this circuit is pretty straight forward and looks like this:</p>
<p></p><pre class="crayon-plain-tag">#include &quot;BeagleBone_gpio.h&quot;
#include &lt;signal.h&gt;

#define TRUE 1
#define FALSE 0

int forever = TRUE;

void sighandler(int sig)
{
	printf(&quot;CONTROL+C was caught... terminating in a friendly manner\n&quot;);
	forever = FALSE;
}

int main()
{
	int i=0;
	int pinID[]={P8_3,P8_4,P8_5,P8_11,P8_12};

	int nbr_selectedPins=sizeof(pinID)/sizeof(*pinID);
	struct gpioID selectedPins[nbr_selectedPins]; 
	pinMode_multiple(selectedPins,pinID,nbr_selectedPins,&quot;out&quot;);
	
	unsigned int data_to_write;

    signal(SIGABRT, &amp;sighandler);
	signal(SIGTERM, &amp;sighandler);
	signal(SIGINT,  &amp;sighandler);

	data_to_write=1;	

	while(forever==TRUE)
	{
		for (i=0;i&lt;4;i++)
		{
			digitalWrite_multiple(selectedPins,nbr_selectedPins,data_to_write);
			data_to_write=data_to_write&lt;&lt;1;
			delayms(500);
		}

		for (i=4;i&gt;0;i--)
		{
			digitalWrite_multiple(selectedPins,nbr_selectedPins,data_to_write);
			data_to_write=data_to_write&gt;&gt;1;
			delayms(500);
		}
	}

	cleanup_multiple(selectedPins,nbr_selectedPins);
	
	return 1;
}</pre><p></p>
<p>To compile and run this code, download my <a href="https://github.com/nunoalves/BeagleBone_IO_lib">BeagleBone_IO library</a>, save the above code as <i>main.c</i> and type the following commands:</p>
<div id='stb-box-3162' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; ">gcc -c BeagleBone_gpio.c<br />
gcc BeagleBone_gpio.o main.c -o main<br />
./main</div>
<p>What is neat about my code, is that it is able to trap a signal whenever the user types CONTROL+C and ends the program normally&#8230;  after performing some generic BeagleBone GPIO cleanup.</p>
<p>Anyway, I would like this program to run whenever my BeagleBone starts up. BeagleBone&#8217;s default OS is Angstrom Linux which uses systemd as the initialization scheduler. I am still learning about this, but according to the <a href="http://en.wikipedia.org/wiki/Systemd">wikipedia entry</a> and also to <a href="http://kezhong.wordpress.com/2011/11/19/creating-my-own-systemd-service-files-on-fedora-16x86_64/">Kezhong&#8217;s Weblog</a>, this daemon is meant to efficiently express services dependencies, by allowing more services to be launched in parallel at system startup while reducing the need to mess around with many scripts. I used to do this on ubuntu&#8230; and it was a mess.</p>
<p>Anyway, I would like to declare my LED blinking program as a service. So I need to execute the following steps:<br />
<br />
<b>Step #1: Create a script that will call the program that you wish you launch at boot time</b><br />
This means we need to create a file in the <i>/usr/bin/</i> directory with any name. For example, assuming that our compiled LED program is in <i>/home/root/main</i> we can create an executable simple script called <i>myScript.sh</i> with the following lines of code. </p>
<div id='stb-box-172' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; ">echo &#8220;#!/bin/bash&#8221; > /usr/bin/myScript.sh<br />
echo &#8220;/home/root/main&#8221; >> /usr/bin/myScript.sh<br />
chmod u+x /usr/bin/myScript.sh</div>
<p>
<b>Step #2: Create the service file </b><br />
Create the file <i>/lib/systemd/myScript.service</i> . Actually your service name can be anything you want&#8230; not  restrained to <i>myScript.service</i>.<br />
<div id='stb-box-8641' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; ">nano /lib/systemd/myScript.service</div></p>
<p><b>Step #3: Write the appropriate service settings</b><br />
Your </i>/lib/systemd/myScript.service</i> can be for example:<br />
<div id='stb-box-8267' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; ">[Unit]<br />
Description=Run the LED pattern script<br />
After=syslog.target network.target</p>
<p>[Service]<br />
Type=simple<br />
ExecStart=/usr/bin/myScript.sh</p>
<p>[Install]<br />
WantedBy=multi-user.target<br />
</div></p>
<p><b>Step #4: Make a symbolic link</b><br />
<div id='stb-box-5506' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; ">cd /etc/systemd/system/<br />
ln /lib/systemd/myScript.service myScript.service</div></p>
<p><b>Step #5: Make systemd take notice of it, activate the service immediately and enable the service to be started on boot-up</b><br />
<div id='stb-box-9921' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; ">systemctl daemon-reload<br />
systemctl start myScript.service<br />
systemctl enable myScript.service</div></p>
<p>After executing all commands on step 5, the LED program should immediately start. Try switching the BeagleBone power OFF &#038; ON&#8230; and you will see the LED program.</p>
<p><b>How to terminate the script that is constantly running in the background?</b><br />
If everything went okay, your script in constantly running in the background. To terminate it, you need to kill it. Use the <i>top</i> command and find out the process id (pid) of your looping program. As shown on the screenshot, my <i>main</i> pid is 13.<br />
<div id="attachment_323" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.nunoalves.com/open_source/wp-content/uploads/2012/04/Screen-Shot-2012-04-10-at-9.47.32-PM.png"><img src="http://www.nunoalves.com/open_source/wp-content/uploads/2012/04/Screen-Shot-2012-04-10-at-9.47.32-PM-300x204.png" alt="" title="Screen Shot 2012-04-10 at 9.47.32 PM" width="300" height="204" class="size-medium wp-image-323" /></a><p class="wp-caption-text">Listing all jobs using the command &quot;top&quot;.</p></div><br />
The following command will take care of terminating the job.<br />
<div id='stb-box-2266' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; ">kill 113</div></p>
<p><b>How disable the script from starting up at the boot time?</b><br />
Just type:<br />
<div id='stb-box-8648' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; ">systemctl disable myScript.service</div></p>
<p>Thanks to Piranha at the <a href="http://groups.google.com/group/beagleboard">official BeagleBoard forum</a> for guidance.</p>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-4338952704608042";
/* Wunderkammer */
google_ad_slot = "8709913020";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.nunoalves.com/open_source/?feed=rss2&#038;p=308</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Automated craigslist job search with Perl and Bash</title>
		<link>http://www.nunoalves.com/open_source/?p=252</link>
		<comments>http://www.nunoalves.com/open_source/?p=252#comments</comments>
		<pubDate>Fri, 30 Mar 2012 13:36:16 +0000</pubDate>
		<dc:creator>Nuno Alves</dc:creator>
				<category><![CDATA[Operating Systems]]></category>
		<category><![CDATA[Programming Languages]]></category>
		<category><![CDATA[Bash]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Mac OS X]]></category>
		<category><![CDATA[Perl]]></category>

		<guid isPermaLink="false">http://www.nunoalves.com/open_source/?p=252</guid>
		<description><![CDATA[Most of my students are in the job market and after suggesting them websites where they could look for jobs, I took a peak at craigslist. I like craigslist; its a simple, bare-bones website with pure text. However, the search functionality is a bit awkward, and it is hard to find a good match between [...]]]></description>
				<content:encoded><![CDATA[<p>Most of my students are in the job market and after suggesting them websites where they could look for jobs, I took a peak at <a href="http://www.craigslist.org">craigslist</a>. I like craigslist; its a simple, bare-bones website with pure text. However, the search functionality is a bit awkward, and it is hard to find a good match between the candidate skills and a particular job posting. If you are seriously looking at every single &#8220;filtered&#8221; post, it may still take you over an hour to look for the best skill-to-job matches. So I created two scripts, one in Perl and the other one in Bash, that scavenge all the job postings for skill matches, and create a new webpage with all the appropriate positions and matched skills in a ready to click link. Data mining at its best!<br />
<br />
There are some &#8220;limitations&#8221; of these scripts. First of all they were only tested in macOSX and Linux, however I am sure you can convert them quite easily to Windows. Secondly, I&#8217;ve focused all the craigslist searches around New England. You may add other craigslist locations quite easily by following the instructions on the perl script.<br />
<br />
This automated job search requires two files: <i>search_jobs.sh</i> and <i>craigslist.pl</i>. Both can be found below, or at <a href="https://github.com/nunoalves/craigSearch">my github repository</a>. To run the code place both files in the same directory, and edit the <i>search_jobs.sh</i>, shown below, with a text editor (after emacs, my second favorite text editor is <a href="http://www.barebones.com/products/textwrangler/">TextWrangler</a>). In this file modify the appropriate keywords that are being assigned to the variable <i>SEARCH_SKILLS</i>. Currently the search skills are the standard qualifications for an engineering graduate.</p>
<p></p><pre class="crayon-plain-tag">#!/bin/bash
#################################################################################
#Functions (do not modify anything here)
#################################################################################
SEARCH_SKILLS=&quot;&quot;

function search_jobs
{
	SEARCH_NAME=${1}
	perl craigslist.pl ${SEARCH_SKILLS}&gt; raw_data.txt

	#create the header of an html file
	echo &quot;&lt;html&gt;&lt;title&gt;Job Search Results&lt;/title&gt;&lt;body&gt;&quot; &gt; job_data.html

	#sort the entire file contents and make sure the best matches are on top
	sort -t! -n -r -k3 raw_data.txt &gt;&gt; job_data.html

	#clean up the file
	perl -p -i -e &quot;s/!/\&amp;nbsp;\&amp;nbsp;\&amp;nbsp;\&amp;nbsp;\&amp;nbsp;\&amp;nbsp;/g&quot; job_data.html

	#terminate the html file
	echo &quot;&lt;/body&gt;&lt;/html&gt;&quot; &gt;&gt; job_data.html
	
	mv job_data.html ${SEARCH_NAME}.html
	rm -f raw_data.txt	
}

#################################################################################
#You may modify your skills below
#################################################################################
SEARCH_SKILLS=&quot;embedded, circuit, transistor, VLSI, firmware, RTOS, kernel, MacOSX, JTAG, oscilloscope, HDL, FPGA, Arduino, MSP430, OMAP3540, micro-controllers, microcontrollers, SVN, programmer, Perl, linux, Mathematica, LabVIEW, schematics, Verilog, VHDL&quot;
SEARCH_NAME=&quot;engineering&quot;
search_jobs ${SEARCH_NAME}

SEARCH_SKILLS=&quot;quantitative, mathematica, finance, programmer, developer, high-frequency, fpga, microcontroller&quot;
SEARCH_NAME=&quot;finance&quot;
search_jobs ${SEARCH_NAME}</pre><p></p>
<p>This script runs with the following command line:<br />
<div id='stb-box-5571' class='stb-grey_box' style="background-image: url(none); min-height: 20px; padding-left: 5px; ">chmod u=+rwx search_jobs.sh<br />
./search_jobs.sh</div></p>
<div id="attachment_259" class="wp-caption aligncenter" style="width: 610px"><a href="http://www.nunoalves.com/open_source/wp-content/uploads/2012/03/Screen-Shot-2012-03-30-at-9.30.43-AM.png"><img src="http://www.nunoalves.com/open_source/wp-content/uploads/2012/03/Screen-Shot-2012-03-30-at-9.30.43-AM.png" alt="" title="Running the scripts on a macosx terminal window." width="600" height="115" class="size-full wp-image-259" /></a><p class="wp-caption-text">Running the scripts on a macosx terminal window.</p></div>
<p>After it is done executing it will create two files <i>engineering.html</i> and <i>finance.html</i>, where the candidate can see his best job matches.</p>
<div id="attachment_260" class="wp-caption aligncenter" style="width: 605px"><a href="http://www.nunoalves.com/open_source/wp-content/uploads/2012/03/Screen-Shot-2012-03-30-at-9.31.20-AM.png"><img src="http://www.nunoalves.com/open_source/wp-content/uploads/2012/03/Screen-Shot-2012-03-30-at-9.31.20-AM.png" alt="" title="Two html files are created with the best job matches" width="595" height="421" class="size-full wp-image-260" /></a><p class="wp-caption-text">Two html files are created with the best job matches</p></div>
<p><div id="attachment_261" class="wp-caption aligncenter" style="width: 474px"><a href="http://www.nunoalves.com/open_source/wp-content/uploads/2012/03/Screen-Shot-2012-03-30-at-9.32.08-AM.png"><img src="http://www.nunoalves.com/open_source/wp-content/uploads/2012/03/Screen-Shot-2012-03-30-at-9.32.08-AM.png" alt="" title="Generated HTML file with the best job matches" width="464" height="233" class="size-full wp-image-261" /></a><p class="wp-caption-text">Generated HTML file with the best job matches</p></div><br />
Below is the Perl script that parses the craigslist job postings.<br />
<pre class="crayon-plain-tag">#This script fetches the last 2 days new job postings from craigslist that match  
#a specific criteria and reports the URLs that correspond to that match.
#The search criteria comes from the input arguments. The cragislist sites
#are hardwired to the New England area. You may change them by manually 
#altering the variables in Section #3.
#
#Version 0.2 30/march/2012
#Author: Nuno Alves
#
#############################################################################
#Section #1 - load libraries
#############################################################################
use strict;
use POSIX;
use LWP::Simple;

#############################################################################
#Section #2 - input arguments are your skillsets
#############################################################################
my $num_args = $#ARGV + 1;
if ($num_args == 1) { print &quot;You must add some skills as arguments\n&quot;; exit; }

#############################################################################
#Section #3 - defining variables
#############################################################################
#what cragislist sites 
my @search_site=(&quot;http://boston.craigslist.org&quot;,&quot;http://nh.craigslist.org&quot;,&quot;http://maine.craigslist.org&quot;,&quot;http://burlington.craigslist.org&quot;,&quot;http://westernmass.craigslist.org&quot;,&quot;http://worcester.craigslist.org&quot;);

#type what positions you are looking for (egr = engineering, sof = software)
my @positions=(&quot;egr&quot;,&quot;sof&quot;,&quot;bus&quot;,&quot;acc&quot;);

#this array contains the arguments which are your resume skills
my @skills=@ARGV ;

#############################################################################
#Section #4 - debug code
#############################################################################
#instead of work on every single URL, setting $debug=1, will just scan
#two webpages
my $debug=0; 
my @debug_urls=(&quot;http://boston.craigslist.org/gbs/egr/2902012136.html&quot;,&quot;http://boston.craigslist.org/bmw/egr/2929181526.html&quot;,&quot;http://boston.craigslist.org/gbs/egr/2926742528.html&quot;);

#############################################################################
#Section #5 - subroutines for collecting craigslist data
#############################################################################
sub collect_job_posting_http
{
	my $url=$_[0];
	my $content = get $url;
	
	#print $content . &quot;\n&quot;;
	my @splitcontents=split(/&lt;h4 class=\&quot;ban\&quot;/,$content);
	my $size_splitcontents=@splitcontents;
	
	my @url_data=();
	for (my $i=1 ; $i&lt;$size_splitcontents ; $i++)
	{
		#just want the last 2 days of postings
		if ($i&lt;3) 
		{
			#print &quot;============\n\n\n&quot;;
			#print $splitcontents[$i] . &quot;\n&quot;;
		
			#get all the posting urls for this particular day
			my @postingdata=split(/&lt;p&gt;&lt;a href=\&quot;|\&quot;&gt;/,$splitcontents[$i]);
	
			for (my $j=0; $j&lt;@postingdata ; $j++)
			{	
				#print &quot;&gt;&gt;[$j]&gt;&gt;&quot; . $postingdata[$j] . &quot;&lt;&lt;&lt;\n&quot;;
				if ($postingdata[$j]=~m/^http/) 
				{
					push(@url_data,$postingdata[$j]);
				}
			}
		}
	}

return(@url_data);	
}


sub extract_date
{	
	my @url_data=$_[0];
	my @date_data=split(/Date: 2012-|EDT&lt;br&gt;/,$url_data[0]);	

	return(&quot;2012-&quot; . $date_data[1]);
}

#############################################################################
#Section #6 - main program: collecting http data for each job posting
#############################################################################
my @urls=();


if ($debug == 0)
{
	for (my $k=0;$k&lt;@search_site;$k++)
	{
		for (my $z=0;$z&lt;@positions;$z++)
		{
			my $base_url=$search_site[$k].&quot;/&quot;.$positions[$z];
			my @tmp_data=collect_job_posting_http $base_url;
			push(@urls,@tmp_data);
		}
	}
}
else
{
	@urls=@debug_urls;
}

#foreach (@urls)
#{
#	print $_ . &quot;\n&quot;;
#}


#############################################################################
#Section #7 - check if each posting matches at least one skill
#############################################################################
my @matched_skills=();
my @skill_type=();
my @post_date=();

for (my $i=0 ; $i&lt;@urls ; $i++)
{
	my $url=$urls[$i];
	my $content = get $url;
	my $counter=0;
	my $date;
	
#	print $url . &quot;\n&quot;;
#	print $content . &quot;\n&quot;;
	
	my $skill_type_desc=&quot;&quot;;

	for (my $k=0; $k&lt;@skills ; $k++)
	{
		if ($content =~ m/$skills[$k]/i) 
		{ 
			$counter++; 
			$skill_type_desc = $skill_type_desc . $skills[$k] . &quot; &quot;;
		}	
	}
	push(@matched_skills,$counter);
	push(@skill_type,$skill_type_desc);
	push(@post_date,extract_date($content));
}

#############################################################################
#Section #8 - print results to the screen
#############################################################################
for (my $i=0; $i &lt; @matched_skills ; $i++)
{
	if ($matched_skills[$i]&gt;0)
	{ 
		print &quot;&lt;li&gt;&lt;a href=\&quot;$urls[$i]\&quot;&gt;site #$i\&lt;\/a\&gt;&quot; . &quot;!&quot; . $post_date[$i] . &quot;!&quot; . $matched_skills[$i] . &quot;!&quot; . $skill_type[$i] . &quot;\n&quot;; 
	}
}</pre></p>
]]></content:encoded>
			<wfw:commentRss>http://www.nunoalves.com/open_source/?feed=rss2&#038;p=252</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
