<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Muro on Medium]]></title>
        <description><![CDATA[Stories by Muro on Medium]]></description>
        <link>https://medium.com/@codingcamel?source=rss-cfbab30c8a1a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*JNGqpfzJUETMz9gE.</url>
            <title>Stories by Muro on Medium</title>
            <link>https://medium.com/@codingcamel?source=rss-cfbab30c8a1a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 18:17:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@codingcamel/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Instala y configura PostgreSQL en Archlinux (y sin lágrimas)]]></title>
            <link>https://medium.com/@codingcamel/instala-y-configura-postgresql-en-archlinux-y-sin-l%C3%A1grimas-c9c113897677?source=rss-cfbab30c8a1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9c113897677</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[postgresql-tutorials]]></category>
            <category><![CDATA[configuration]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Muro]]></dc:creator>
            <pubDate>Sun, 29 Dec 2024 17:30:47 GMT</pubDate>
            <atom:updated>2024-12-29T17:30:47.741Z</atom:updated>
            <content:encoded><![CDATA[<p>Cada vez que tengo que usar una base de datos de PostgreSQL me entra una suerte de pánico ya que nunca me acuerdo cómo configurarla correctamente. Incluso hoy, me he pasado varios minutos buscando en internet tratando de entender qué hacer. Como sé que en el futuro tendré que configurar más bases de datos, decidí escribir esta guía para usarla como referencia (y espero que de paso te sirva).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7zdJKpPLDaSXdsOy" /><figcaption>Photo by <a href="https://unsplash.com/@steve_j?utm_source=medium&amp;utm_medium=referral">Steve Johnson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Lo primero, la instalación</strong></h3><p>La más simple (y la que uso el 99% de las veces) es la siguiente. (Recuerda que estamos usando ArchLinux, en Ubuntu es diferente)</p><pre>sudo pacman -S postgresql</pre><h3>Comprobando que todo está en su lugar</h3><p>Antes de seguir, me gusta verificar que PostgreSQL se instaló correctamente:</p><pre>postgres --version</pre><p>También asegúrate de que no está corriendo (a veces las instalaciones anteriores dejan rastros):</p><pre>sudo systemctl status postgresql</pre><h3>Preparando la base de datos</h3><p>Aquí viene la parte que siempre se me olvidaba: hay que inicializar la base de datos antes de poder usarla.</p><p>Primero, necesitas ser el usuario <strong>postgres</strong>. Este es un paso que SIEMPRE tienes que hacer cuando vayas a hacer tareas administrativas (lo digo por experiencia 😅.</p><pre>sudo su - postgres</pre><p>Ahora sí, inicializamos el directorio de datos. Por defecto está en <strong>/var/lib/postgres/data</strong> y, a menos que tengas una razón muy específica, déjalo ahí:</p><pre>initdb --locale en_US.UTF-8 -D /var/lib/postgres/data</pre><p>Ya puedes salir del usuario postgres:</p><pre>exit</pre><h3>Arrancando PostgreSQL</h3><p>Hora de la verdad. Vamos a arrancar PostgreSQL:</p><pre>sudo systemctl start postgresql</pre><p>Para verificar que todo está funcionando:</p><pre>sudo systemctl status postgresql</pre><h3>Creando tu usuario</h3><p>Este es otro paso que solía olvidar: necesitas un usuario para poder usar la base de datos.</p><p>Otra vez necesitamos ser el usuario postgres (te dije que esto pasa mucho):</p><pre>sudo su - postgres</pre><p>Aquí viene un truco que me hubiera gustado saber desde el principio: crea un usuario de PostgreSQL con el mismo nombre que tu usuario de Linux. Así no tendrás que especificar el usuario cada vez que quieras conectarte a la base de datos:</p><pre>createuser --interactive</pre><p>Te va a preguntar dos cosas:</p><ul><li><em>Enter name of role to add: </em>pon aquí tu nombre de usuario de Linux</li><li><em>Shall the new role be a superuser?: </em>yo siempre pongo que sí (en mi máquina de desarrollo.)</li></ul><p>Sal del usuario postgres:</p><pre>exit</pre><h3>Últimos pasos</h3><p>Reinicia PostgreSQL para que tome todos los cambios:</p><pre>sudo systemctl restart postgresql</pre><p>Y verifica una última vez:</p><pre>sudo systemctl status postgresql</pre><h3>¿Y ahora qué?</h3><p>¡Listo! Ya tienes PostgreSQL funcionando. Guarda esta guía para la próxima vez que necesites configurar una base de datos (yo sé que la voy a necesitar 😉).</p><p>Un último consejo: si en algún momento las cosas no funcionan como esperas, lo primero que debes revisar es si estás usando el usuario postgres para las tareas administrativas. El 90% de las veces que algo me ha fallado ha sido por olvidar este detalle.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9c113897677" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning in Public: Generating random numbers in C using GSL]]></title>
            <link>https://medium.com/@codingcamel/learning-in-public-generating-random-numbers-in-c-using-gsl-77f5ea77c8e2?source=rss-cfbab30c8a1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/77f5ea77c8e2</guid>
            <category><![CDATA[random-number-generator]]></category>
            <category><![CDATA[learning-in-public]]></category>
            <category><![CDATA[gsl]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[c]]></category>
            <dc:creator><![CDATA[Muro]]></dc:creator>
            <pubDate>Fri, 21 Jun 2024 18:46:27 GMT</pubDate>
            <atom:updated>2024-06-22T05:26:52.360Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey everyone! Welcome back to another installment of my journey in learning C. This time, we will learn see how can we use an external library to generate random numbers.</p><p>Random numbers are crucial in various fields like simulations, statistical sampling, cryptography and even games. So let’s get started!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ga_am20COp-52U0V" /><figcaption>Photo by <a href="https://unsplash.com/@edge2edgemedia?utm_source=medium&amp;utm_medium=referral">Edge2Edge Media</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the C standard library, you might have come across the rand and srand functions for generating random numbers. However, their use is often discouraged because they have several limitations, such as predictable sequences and limited randomness quality. In fact, there is a section in <em>Numerical Recipes in C </em>where they strongly caution against relying on system-supplied Random Number Generators:</p><blockquote>Now our first, and perhaps most important, lesson in this chapter is: be very, very suspicious of a system-supplied rand() that resembles the one just described. If all scientific papers whose results are in doubt because of bad rand()s were to disappear from library shelves, there would be a gap on each shelf about as big as your fist. (Chapter 7, pg 276. Numerical Recipes in C)</blockquote><p>If <em>Numerical Recipes</em> say so, we better obey! Instead, we will use the GNU Scientific Library (GSL), which offers a more robust and reliable way to generate random numbers.</p><h3>Installing GSL</h3><p>First, let’s install GSL on our system. I am using Arch Linux, but I’ll also include the installation steps for Ubuntu for those of you using that distribution.</p><p>Installing GSL on Arch Linux is straightforward; just open your terminal and run:</p><pre>sudo pacman -S gsl  </pre><p>For those of you on Ubuntu, you can install GSL using the apt package manager. Open your terminal and run:</p><pre>sudo apt-get install libgsl-dev</pre><p>Once you have GSL installed, we’re ready to dive into the documentation to see how can we use this library to generate random numbers.</p><h3>Exploring the GSL documentation</h3><p>The GNU Scientific Library (GSL) provides a comprehensive set of routines for scientific computing, including a powerful suite for random number generation. You can find the documentation about Random Number Generation here: <a href="https://www.gnu.org/software/gsl/doc/html/rng.html">https://www.gnu.org/software/gsl/doc/html/rng.html</a></p><p>GSL offers several types of random number generators (RNG’s), each suitable for different applications. All these functions are declared in gsl_rng.h header file.</p><p>Now, let’s explore how to create random uniform numbers. To do this, we need to first initialize the random number generator using gsl_rng_alloc to create an instance of the generator. According to the documentation, the function signature is:</p><pre>gsl_rng *gsl_rng_alloc(const gsl_rng_type *T)</pre><p>This function takes a struct of type gsl_rng_type and returns a generator instance with type gsl_rng. Out of curiosity, let’s have a peek at the definition of these two structs; they are defined in gsl_rng.h</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8hE-Qw-6w3IL_e8WqCqOsA.png" /><figcaption>Source code of gsl_rng.h</figcaption></figure><p>At a high level, the gsl_rng struct (lines 51 to 56) represents an instance of a random number generator. It consists of 2 parts, the type of the random number generator and its state. The type is a pointer to a gsl_rng_type struct that specifies the algorithm and properties of the random number generator (RNG). There are many such gsl_rng_type definitions available in GSL, some of them are shown in lines 62 to 73. The state is a pointer to the current state of the RNG, keeping track of where you are in the sequence of random numbers.</p><p>Now, let’s take a closer look at the gsl_rng_type struct (lines 39–49). This struct is like a blueprint for a RNG. It defines various aspects such as the name of the RNG, the maximum and minimum values it can generate, the size of its state, and pointers to functions setting the seed, generating the next random integer, and generating the next random double. Basically, gsl_rng_type contains all necessary details and operations that define how the RNG works.</p><h3>Time to Code!</h3><p>With this understanding, let’s dive into some coding! I’ll start by creating a new C file called main.c and I will include gsl_rng.h</p><p>Here I will declare a pointer to the random number generator and use gsl_rng_alloc to initialize it with the Mersenne Twister random number generator (gsl_rng_mt19993) . The Mersenne Twister is a robust pseudo-random number generator and one of the most widely used.</p><pre>//main.c<br><br>#include &lt;gsl/gsl_rng.h&gt;<br><br>int main(int argc, char *argv[]) {<br>  // Declare a pointer to the random number generator<br>  gsl_rng *generator;<br><br>  // Allocate and initialize the RNG of type mt19937 (Mersenne Twister)<br>  generator = gsl_rng_alloc(gsl_rng_mt19937);<br><br>  return 0;<br>}</pre><p>The generator is automatically initialized with a default seed of zero, but we can change this. According to the documentation, we can use gsl_rng_set to set a new seed value. Here’s how to do it: we provide a pointer to our generator along with an integer that represents the seed value:</p><pre>void gsl_rng_set(const gsl_rng *r, unsigned long int s)</pre><p>In our code, we change the seed to 1234567.</p><pre>// main.c<br><br>#include &lt;gsl/gsl_rng.h&gt;<br><br>int main(int argc, char *argv[]) {<br>  // Declare a pointer to the random number generator<br>  gsl_rng *generator;<br><br>  // Allocate and initialize the RNG of type mt19937 (Mersenne Twister)<br>  generator = gsl_rng_alloc(gsl_rng_mt19937);<br><br>  // Let&#39;s change the default seed to 1234567<br>  gsl_rng_set(generator, 1234567);<br><br>  return 0;<br>}</pre><p>This setup works well, but there’s a catch. Every time we run our program, we will obtain the same sequence of random numbers because the seed (1234567) is hard-coded. To ensure that we get different random numbers every time we run the program, we can use the current time as the seed, this way, the seed changes with each execution, resulting in different random numbers each time. Cool trick, right?</p><p>This is how our code looks like when we use the current time as the seed:</p><pre>// main.c<br><br>#include &lt;gsl/gsl_rng.h&gt;<br>#include &lt;time.h&gt;<br><br>int main(int argc, char *argv[]) {<br>  // Declare a pointer to the random number generator<br>  gsl_rng *generator;<br><br>  // Allocate and initialize the RNG of type mt19937 (Mersenne Twister)<br>  generator = gsl_rng_alloc(gsl_rng_mt19937);<br><br>  // Let&#39;s change the default seed to the current time<br>  gsl_rng_set(generator, time(NULL));<br><br>  return 0;<br>}</pre><p>So far, we have initialized our RNG and change its seed to the current time. Now, let’s generate some random numbers!</p><p>There are various functions available to sample random numbers from our generator. For our purposes, we will use gsl_rng_uniform, which, according to the GSL documentation, takes a pointer to our generator and returns a double distributed in the range [0,1).</p><pre>double gsl_rng_uniform(const gsl_rng *r)</pre><p>Great, now let’s generate 10 random uniform numbers:</p><pre>// main.c<br><br>#include &lt;gsl/gsl_rng.h&gt;<br>#include &lt;time.h&gt;<br><br>int main(int argc, char *argv[]) {<br>  // Declare a pointer to the random number generator<br>  gsl_rng *generator;<br><br>  // Allocate and initialize the RNG of type mt19937 (Mersenne Twister)<br>  generator = gsl_rng_alloc(gsl_rng_mt19937);<br><br>  // Let&#39;s change the default seed to the current time<br>  gsl_rng_set(generator, time(NULL));<br><br>  // Let&#39;s generate 10 random numbers:<br>  for (int i=0; i &lt; 10; i++) {<br>    printf(&quot;%f\n&quot;, gsl_rng_uniform(generator));<br>  }<br><br>  // Free the RNG<br>  gsl_rng_free(generator);<br>  return 0;<br>}</pre><p>We can compile our code with the following command, ensuring we include GSL by using the -lgsl flag. This command compiles main.c and links it with the GSL library, allowing us to use its functions in our program.</p><pre>gcc -Wall -Werr main.c -lgsl -o main</pre><h3>Let’s see the results!</h3><p>And now for the results! Let’s start by running our code with a hard-coded seed (1234567):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*3gK5E7AaaaE2objTG7GpZg.png" /></figure><p>As expected, we get the same sequence of random numbers each time we run the code with a hard-coded seed. I’ve run the program 4 times, each time the results are identical.</p><p>Now, let’s run the program using the current time as the seed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*Bj53yRgSps28n3PJI1gytQ.png" /></figure><p>Success! Now, our random numbers are different each time we execute the program.</p><p>And there you have it! We’ve successfully used the GNU Scientific Library (GSL) to generate random numbers in C.</p><p>As we’ve seen, diving into the documentation is crucial while learning new libraries or tools. The GSL documentation is packed with valuable information that can help you understand the nuances of different random number generators and how to implement them effectively. Taking the time to read and understand the documentation can save you a lot of trouble and make your coding journey smoother. So, keep exploring, keep experimenting, and always remember to check the docs!</p><p>Thanks for following along, and happy coding!</p><p>Hasta la vista!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77f5ea77c8e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning in Public: Coding ‘ls’ in C (Part 2)]]></title>
            <link>https://medium.com/@codingcamel/learning-in-public-coding-ls-in-c-part-2-3dd1f78dacfc?source=rss-cfbab30c8a1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3dd1f78dacfc</guid>
            <dc:creator><![CDATA[Muro]]></dc:creator>
            <pubDate>Fri, 14 Jun 2024 07:36:50 GMT</pubDate>
            <atom:updated>2024-06-14T07:41:31.632Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome back to my journey of learning C by building the ls command from scratch. In the <a href="https://medium.com/@codingcamel/learning-in-public-coding-ls-in-c-part-1-ab70eda85551">previous post,</a> we explored the basics of directory streams and took a peek inside using gdb. Now let’s move on to reading from the directory and printing its contents.</p><p>To recap, in <a href="https://medium.com/@codingcamel/learning-in-public-coding-ls-in-c-part-1-ab70eda85551">Part 1</a> we wrote this piece of code to open a directory and we obtained a pointer to a DIR</p><pre>//myls.c<br><br>#include &lt;dirent.h&gt;<br>#include &lt;stdio.h&gt;<br><br>int main(int argc, char **argv) {<br>  // define a pointer to DIR<br>  DIR *dir_stream;<br><br>  // open the current directory (&quot;.&quot;)<br>  dir_stream = opendir(&quot;.&quot;);<br><br>  // opendir returns NULL on error, so we handle the error...<br>  if (dir_stream == NULL) {<br>    perror(&quot;Error while trying to open directory \n&quot;);<br>    return 1;<br>  }<br><br>  return 0;<br>}</pre><p>We used gdb to inspect the contents of dir_stream, which gave us a detailed view of the internal structure. Now, let&#39;s move forward and actually read from the directory.</p><p>To read the contents of a directory, we use the readdir function, which is part of the C standard library (included in dirent.h) . Let’s look at the documentation:</p><p>man readir</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9VtVoU6RcRCdF8bNBoUN4A.png" /></figure><p>So, the readdir function takes a DIR pointer (which is our dir_stream in the code) and returns a pointer to a dirent struct. This struct represents the next entry in dir_stream. To read all entries, we just keep calling readdir in a loop until it returns NULL.</p><p>The documentation also tell us what the dirent struct looks like:</p><pre>struct dirent{<br>  ino_t d_ino;<br>  off_t d_off;<br>  unsigned short d_reclen; <br>  unsigned char d_type;<br>  char d_name[256];<br>};</pre><p>Here’s the cool part: this struct gives us some handy info about each file in the directory:</p><ul><li><strong>d_name</strong>: The filename.</li><li><strong>d_reclen</strong>: The size of the directory entry.</li></ul><p>So, if we iterate through dir_stream, call readdir on each entry, and print out these three values, we’ll have a basic version of our very own ls function.</p><p>We also need to remember to close our directory when we are done. For that we will use the closedir function from the C standard library (also included in dirent.h ). Here is it’s man page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1T5j0eyGF2QdQBQ_x9gbMg.png" /></figure><p>So, to close the directory, we just need to pass a pointer to our dictionary stream dir_stream and it will return 0 if the directory was closed successfully and -1 if there is an error.</p><p>Let’s get to it!</p><pre>// myls.c<br>//<br>//<br>#include &lt;dirent.h&gt;<br>#include &lt;stdio.h&gt;<br><br>int main(int argc, char **argv) {<br>  // define a pointer to DIR<br>  DIR *dir_stream;<br>  // define a pointer to the dirent struct<br>  struct dirent *dir_read;<br><br>  // open the current directory (&quot;.&quot;)<br>  dir_stream = opendir(&quot;.&quot;);<br><br>  // opendir returns NULL on error, so we handle the error...<br>  if (dir_stream == NULL) {<br>    perror(&quot;Error while trying to open directory\n&quot;);<br>    return 1;<br>  }<br><br>  // now let&#39;s read the contents:<br>  while ((dir_read = readdir(dir_stream)) != NULL) {<br>    printf(&quot;%s\t%d bytes\n&quot;, dir_read-&gt;d_name, dir_read-&gt;d_reclen);<br>  }<br><br>  // we also need to close the directory when we are done<br>  if (closedir(dir_stream) == -1) {<br>    perror(&quot;Can&#39;t close the dir \n&quot;);<br>    return -1;<br>  }<br><br>  return 0;<br>}</pre><p>We can now compile and see the results:</p><pre>gcc -Wall -Werror -g myls.c -o myls</pre><p>This is what we expect from the built-in ls function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*uDaovHuo_sRbO3_wUVATUg.png" /><figcaption>This is what we expect from the ls function</figcaption></figure><p>and this is what we get from our own custom myls function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*56Kol9fQ4inpzYZO1uvHqQ.png" /><figcaption>This is what we get with our myls function.</figcaption></figure><p>It’s kind of satisfying to see our code listing the directory contents just like the built-in ls command, right? The built-in ls function offers so much more functionality, but I think we’re in a great position to start adding more features ourselves. That will be part of future posts.</p><p>Thanks for following along in this journey. Happy coding and see you next time!.</p><p><a href="https://medium.com/@codingcamel/learning-in-public-coding-ls-in-c-part-1-ab70eda85551">Learning in Public: Coding ‘ls’ in C (Part 1)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3dd1f78dacfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning in Public: Coding ‘ls’ in C (Part 1)]]></title>
            <link>https://medium.com/@codingcamel/learning-in-public-coding-ls-in-c-part-1-ab70eda85551?source=rss-cfbab30c8a1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab70eda85551</guid>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[gdb]]></category>
            <category><![CDATA[learrning-in-public]]></category>
            <dc:creator><![CDATA[Muro]]></dc:creator>
            <pubDate>Fri, 14 Jun 2024 02:29:17 GMT</pubDate>
            <atom:updated>2024-06-14T07:40:52.895Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been trying to learn C for a long time, but I often find it difficult to grasp. Instead of giving up, I decided to take a different approach: building common utilities and documenting my learning process for future reference. This post is a part of my journey as a total beginner, starting with a implementation of the ‘ls’ command in C.</p><p>Join me as I dive into the basics of C programming and share my experiences along the way. Buckle up!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ClV_nYJfduFNSFok" /><figcaption>Photo by <a href="https://unsplash.com/@clemensvanlay?utm_source=medium&amp;utm_medium=referral">Clemens van Lay</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The ‘ls’ command is one of the basic commands in Linux, and it’s super handy. It lists all the files in the current directory, giving you a quick snapshot of what’s in there. ‘ls’ is a go-to tool for navigating and organizing files. Plus, it has a bunch of options to tweak the output just the way you like it.</p><p>Let’s think about how we can replicate ‘ls’ in a simple way. We need to open a directory, read its contents, print them out, and then close the directory. Luckily, Linux has some functions that can help us with that: opendir, readdir, printf, and closedir.</p><p>First, let’s read the documentation for opendir. We can see that opendir is in the dirent.h header file from the standard C library.</p><pre>man opendir</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-XqSlJam511BXlLF2YyMA.png" /><figcaption>man page for opendir</figcaption></figure><p>The function opendir takes the directory name as a string argument and returns a pointer to DIR which is a directory stream. A directory stream, as I understand it, is an object that represents the directory that we just opened. We get a pointer to the directory stream and then we can use it to read its contents.</p><p>Now, let’s play a bit with our C code and our debugger, gdb, to see what’s happening under the hood:</p><pre>//myls.c<br><br>#include &lt;dirent.h&gt;<br>#include &lt;stdio.h&gt;<br><br>int main(int argc, char **argv) {<br>  // define a pointer to DIR<br>  DIR *dir_stream;<br><br>  // open the current directory (&quot;.&quot;)<br>  dir_stream = opendir(&quot;.&quot;);<br><br>  // opendir returns NULL on error, so we handle the error...<br>  if (dir_stream == NULL) {<br>    perror(&quot;Error while trying to open directory \n&quot;);<br>    return 1;<br>  }<br><br>  return 0;<br>}</pre><p>The code above doesn’t do anything useful (yet), but I’ll use it to see what’s inside DIR using gdb (sorry, curiosity is killing me). We will first compile it using the -g flag in gcc :</p><pre> gcc -Wall -Werror -g myls.c -o myls</pre><p>With the executable ready, let’s fire up gdb to explore what is happening under the hood:</p><p>gdb ./myls</p><p>Here are some basic gdb commands I used to investigate:</p><ul><li>tui layout src It gives me a nice split-screen with the source code at the top and gdb commands at the bottom.</li><li>set print pretty on it formats the printed output to be more readable.</li><li>b 9 or break 9 , sets a breakpoint at line 9 DIR *dir_stream</li><li>run starts the program with gdb.</li><li>p *dir_stream or print *dir_stream shows the contants of the dir_stream pointer.</li><li>n or next resumes execution of the code.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F958121355%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F958121355&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1870153321-c47a1c23819a33dcd09abd7835863d92946e0b40e4fe84dfdaae53570e1343e1-d_1280&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1080" frameborder="0" scrolling="no"><a href="https://medium.com/media/207c03f46c1f050f4376d7762af8766d/href">https://medium.com/media/207c03f46c1f050f4376d7762af8766d/href</a></iframe><p>If we take a peek inside dir_stream , we see something like this:</p><pre>$1 = {<br>  fd = 3,<br>  lock = 0,<br>  allocation = 32768,<br>  size = 0,<br>  offset = 0,<br>  filepos = 0,<br>  errcode = 0,<br>  data = 0x5555555592d0 &quot;&quot;<br>}</pre><p>Let’s try to understand what we have here:</p><ul><li><strong>fd = 3</strong>: This is our file descriptor number. These are integers that identify an open file in a program. The numbers 0, 1, and 2 are usually reserved for standard input, output, and error, so 3 is the next available one.</li><li><strong>allocation = 32768</strong>: This tells us that 32KB of memory has been allocated.</li><li><strong>size = 0</strong>: The current size of the file is 0 bytes.</li><li><strong>offset = 0</strong>: This shows that the position for the next read/write is at the beginning of the file.</li><li><strong>data = 0x5555555592d0</strong>: This is the memory address where the directory stream data is stored.</li></ul><p>I don’t know about you, but for me, now that I can see what’s happening inside, it doesn’t look as scary as it did at the beginning — well, still scary but a little bit less.</p><p>In <a href="https://medium.com/@codingcamel/learning-in-public-coding-ls-in-c-part-2-3dd1f78dacfc">Part 2 </a>we will read from this directory and print its contents.</p><p>Hasta la vista!</p><p><a href="https://medium.com/@codingcamel/learning-in-public-coding-ls-in-c-part-2-3dd1f78dacfc">Learning in Public: Coding ‘ls’ in C (Part 2)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab70eda85551" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extracting Fundamental Stock Data from EDGAR using our favorite language: Common Lisp (Part 3)]]></title>
            <link>https://medium.com/@codingcamel/extracting-fundamental-stock-data-from-edgar-using-our-favorite-language-common-lisp-part-3-5ea58d903b97?source=rss-cfbab30c8a1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ea58d903b97</guid>
            <category><![CDATA[lisp]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[fundamental-analysis]]></category>
            <category><![CDATA[common-lisp]]></category>
            <dc:creator><![CDATA[Muro]]></dc:creator>
            <pubDate>Sat, 02 Mar 2024 14:56:36 GMT</pubDate>
            <atom:updated>2024-03-02T15:00:48.459Z</atom:updated>
            <content:encoded><![CDATA[<p>In our last adventure, detailed in <a href="https://medium.com/@codingcamel/extracting-fundamental-stock-data-from-edgar-using-our-favorite-language-common-lisp-part-2-f28099de4b71">Part 2</a>, we successfully extracted the Earnings Per Share (EPS) for Apple straight from the EDGAR API. Now, let’s press on.</p><p>Let’s take a closer look at the data we gathered in our previous post. We’re dealing with a structure that unfolds into several layers of nesting, ready to be explored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Ac9BVocvl-A7MieyiHKiA.png" /><figcaption>This is the data that we obtained when we called EDGAR to retrieve AAPL Earnings Per Share.</figcaption></figure><p>Let’s inspect our data. The :UNITS part of the association list (or alist, as Common Lisp refers to it) contains the data we need:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mIQWUZrupxMlXm3y1HqQew.png" /><figcaption>The data is in an alist where the key :UNITS contains the data we are looking for.</figcaption></figure><p>Digging a bit deeper, nestled under :UNITS, we discover the :+USD+/SHARES key. It&#39;s here, within :VAL, that the values we&#39;re looking for are hidden.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tR1ypAUC_BVUkXjc19cy1Q.png" /><figcaption>We need to extract the data under the :+USD+/SHARES key.</figcaption></figure><p>Venturing into :+USD+/SHARES, we observe that the Earnings Per Share (EPS) from various reports (such as 10-K and 10-Q) are laid out across different reporting dates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VEDXc-_g4HW8KlEhb3xVIw.png" /><figcaption>Here is the data we need. Unfortunately it is buried within layers of complexity.</figcaption></figure><p>We can navigate through our data by using assoc and cdr as our navigational aids, methodically working our way down to the layer where our EPS data is located. Here&#39;s a sample where we grab the :FY and :VAL fields for only the 10-K reports using a loop and put them in a list called eps:</p><pre>;;; We store our data in a variable called &quot;data&quot;<br>(setf data (get-company-concept &quot;AAPL&quot; &quot;us-gaap&quot; &quot;EarningsPerShareBasic&quot;))<br><br>;;; And now we traverse the nested alist until we get to our EPS information<br> (setf eps (loop for entry in (cdr (assoc :+usd+/shares (cdr (assoc :units data))))<br>      when (equal (cdr (assoc :FORM entry)) &quot;10-K&quot;)<br>      collect (list (cdr (assoc :FY entry)) (cdr (assoc :VAL entry)))))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z6FXBLMRYskK83vQ-tPOcA.png" /><figcaption>Here we have extracted the year and the EPS. As we can see we can get almost 15 years of historical data for free!</figcaption></figure><p>Now we can do some operations with this, for example, let’s calculate the average EPS of our dataset:</p><pre>(/ (apply #&#39;+ (mapcar #&#39;(lambda (x) (cadr x)) eps)) <br>   (length eps))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2FnpupOuEaMkFIqPg5n-uA.png" /></figure><p>I must confess, navigating through the alist to fetch our data isn’t the most thrilling part of our journey. If you’ve got a sleeker, more elegant method up your sleeve, please let me know in the comments below.</p><p>In our next post, we’ll take our adventure a step further by plotting our data. Stay tuned, and see you in the next installment!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*ppbzmobR7kzuBNoU1ZChNg.png" /></figure><ul><li><a href="https://medium.com/@codingcamel/extracting-fundamental-stock-data-from-edgar-using-our-favorite-language-common-lisp-part-2-f28099de4b71">Extracting Fundamental Stock Data from EDGAR using our favorite language: Common Lisp (Part 2)</a></li><li><a href="https://medium.com/@codingcamel/extracting-fundamental-stock-data-from-edgar-using-our-favorite-language-common-lisp-part-1-a3171d100dd4">Extracting Fundamental Stock Data from EDGAR using our favorite language: Common Lisp (Part 1)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ea58d903b97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extracting Fundamental Stock Data from EDGAR using our favorite language: Common Lisp (Part 2)]]></title>
            <link>https://medium.com/@codingcamel/extracting-fundamental-stock-data-from-edgar-using-our-favorite-language-common-lisp-part-2-f28099de4b71?source=rss-cfbab30c8a1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f28099de4b71</guid>
            <category><![CDATA[lisp]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[fundamental-analysis]]></category>
            <category><![CDATA[common-lisp]]></category>
            <dc:creator><![CDATA[Muro]]></dc:creator>
            <pubDate>Sat, 02 Mar 2024 06:05:01 GMT</pubDate>
            <atom:updated>2024-03-02T15:05:23.134Z</atom:updated>
            <content:encoded><![CDATA[<p>In Part 1, we went on a bit of a quest and successfully obtained those CIK numbers using ticker symbols. You can catch up on that journey right here: <a href="https://medium.com/@codingcamel/extracting-fundamental-stock-data-from-edgar-using-our-favorite-language-common-lisp-part-1-a3171d100dd4">Part 1 adventure</a>.</p><p>Before we dive deeper, let’s take a moment to get familiar with XBRL (Extensible Business Reporting Language) and how it is used in the EDGAR API.</p><p>XBRL is a standard based on XML that’s all about exchanging business information in a clear, universal format. Since 2009, the SEC has integrated XBRL directly into financial reports, simplifying the process of extracting financial information.</p><p>To witness XBRL’s integration in action, let’s dive into Apple’s 2023 Annual Report, also known as the 10-K report.</p><p><a href="https://www.sec.gov/ixviewer/ix.html?doc=/Archives/edgar/data/0000320193/000032019323000106/aapl-20230930.htm">Inline XBRL Viewer</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Qx4r5bnSuF8vr9w-TecLA.png" /><figcaption>Here’s Apple’s 10-K form from the SEC’s EDGAR service. The sections marked in red are formatted in XBRL, making them programmatically accessible.</figcaption></figure><p>Let’s explore a bit on the financial statements, we’ll scroll down a few pages until we stumble upon the Consolidated Statements of Operations, this table details revenues, expenses, and net income or loss, giving us a snapshot of the company’s operational efficiency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JK9brtSecD1opv9m2Rf43A.png" /></figure><p>We’re aiming to extract the Earnings Per Share (EPS) from this report programmatically. To identify the specific variable we need to query in the EDGAR API, simply click on the Earnings Per Share box highlighted in red. A popup will appear — make sure to note the Tag value, as that’s our key to retrieving the information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I1TtXXcWHxNcqdNYqZljvQ.png" /></figure><p>The Tag, labeled as “uss-gaap:EarningsPerShareBasic” in this case, holds two crucial bits of information needed to pull our data. The first part, “uss-gaap,” tells us the taxonomy schema being used, and the second part, “EarningsPerShareBasic,” specifies the variable name we’re interested in.</p><p>It’s important to note that XBRL utilizes various taxonomies, such as us-gaap, ifrs-full, dei, and others. The most effective way to identify the correct taxonomy for your needs is to follow the process we’ve outlined above.</p><p>With this insight, we can consult the EDGAR API documentation. There, we discover that extracting this data requires us to make a GET request to a specific URL, in this case:</p><p><a href="https://data.sec.gov/api/xbrl/companyconcept/CIK##########/us-gaap/AccountsPayableCurrent.json">https://data.sec.gov/api/xbrl/companyconcept/CIK##########/us-gaap/EarningsPerShareBasic.json</a></p><p>So let’s write a function to query this data:</p><pre>(defun get-company-concept (ticker taxonomy concept)<br>  &quot;Get company concept using a taxonomy and a concept&quot;<br>  (cl-json:decode-json-from-string (dex:get (format nil &quot;https://data.sec.gov/api/xbrl/companyconcept/CIK~a/~a/~a.json&quot;<br>          (get-stock-cik ticker)<br>          taxonomy<br>          concept)<br>         :headers *sec-headers*)))</pre><p>Now, let’s test our function:</p><pre>(get-company-concept &quot;AAPL&quot; &quot;us-gaap&quot; &quot;EarningsPerShareBasic&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Ac9BVocvl-A7MieyiHKiA.png" /></figure><p>Voila, it works! Stay tuned for our next posts, where we’ll dive into processing this data and creating some insightful plots.</p><p>Hasta la vista!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*ppbzmobR7kzuBNoU1ZChNg.png" /></figure><p><a href="https://medium.com/@codingcamel/extracting-fundamental-stock-data-from-edgar-using-our-favorite-language-common-lisp-part-3-5ea58d903b97">Extracting Fundamental Stock Data from EDGAR using our favorite language: Common Lisp (Part 3)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f28099de4b71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extracting Fundamental Stock Data from EDGAR using our favorite language: Common Lisp (Part 1)]]></title>
            <link>https://medium.com/@codingcamel/extracting-fundamental-stock-data-from-edgar-using-our-favorite-language-common-lisp-part-1-a3171d100dd4?source=rss-cfbab30c8a1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3171d100dd4</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[common-lisp]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[lisp]]></category>
            <category><![CDATA[financial-data]]></category>
            <dc:creator><![CDATA[Muro]]></dc:creator>
            <pubDate>Fri, 01 Mar 2024 20:04:58 GMT</pubDate>
            <atom:updated>2024-03-02T06:08:19.541Z</atom:updated>
            <content:encoded><![CDATA[<p>Lately, I’ve been getting into Fundamental Analysis in an attempt to pick better stocks for my portfolio. I’m really drawn to the idea of value investing. I found some websites that offer financial data for a fee every month (somewhere between 40–100 USD/month to get fundamental data). But honestly, I don’t want to pay for something when I know I can get it for free and more importantly, legally. So, I’ve been looking for ways to get this info without spending money. Remember, a dollar saved is a dollar earned.</p><p>Fortunately, the SEC provides free access to fundamental data through EDGAR. EDGAR uses a format known as XBRL, making it a go-to resource for anyone looking to dive into financial details without the extra cost.</p><p>Alright, enough talk, let’s get down to business. Time to boot up Sly (or Slime) and hop into our REPL.</p><p>We’re going to lean on Dexador for fetching the data with GET requests and cl-json for handling the JSON data. So, let’s kick things off by pulling in these two libraries from Quicklisp:</p><pre>(ql:quickload &#39;(:dexador :cl-json))</pre><p>When using EDGAR, there’s a simple rule: we can make up to 10 requests per second. This keeps things fair so everyone can access the info they need without overloading the system. Also, when we ask EDGAR for data, we need to tell it who we are by using a request header with our email address. This helps keep everything running smoothly and fairly for everyone. So, let’s define a variable for our request headers:</p><pre>(defparameter *sec-headers*<br>  &#39;((&quot;User-Agent&quot; . &quot;example@email.com&quot;)))</pre><p>Peeking into the EDGAR API documentation (<a href="https://www.sec.gov/edgar/sec-api-documentation">https://www.sec.gov/edgar/sec-api-documentation</a>), it’s clear we need the CIK number of the company to tailor our requests like so:</p><p><a href="https://data.sec.gov/submissions/CIK##########.json">https://data.sec.gov/submissions/CIK##########.json</a></p><p>And here’s a little nugget of knowledge: the CIK number must be a 10-digit affair, padded with zeros where needed.</p><p>But then comes the million-dollar question: how do we snag the company’s CIK number? No sweat — the SEC has our backs. They provide an API endpoint right here, serving up the company ticker, the company name, and you guessed it, the CIK number.</p><p><a href="https://www.sec.gov/files/company_tickers.json">https://www.sec.gov/files/company_tickers.json</a></p><p>Let’s create a hash table to store our ticker names and its corresponding company name and CIK number.</p><pre>(defvar *company-info* (make-hash-table :test &#39;equal)</pre><p>And now let’s make a GET request to <a href="https://www.sec.gov/files/company_tickers.json">https://www.sec.gov/files/company_tickers.json</a> to fetch the information. I will store the ticker names as keys in the *company-info* hash table and an association list (alist) as value containing the company name and the CIK number. Note that we are using our headers in the request.</p><pre>(defun read-tickers ()<br>  &quot;Get list of companies from Edgar and store them in the *company-info* hash table&quot;<br>  (let* ((tickers (dex:get &quot;https://www.sec.gov/files/company_tickers.json&quot;<br>                           :headers *sec-headers*))<br>  (response (cl-json:decode-json-from-string tickers)))<br>    (dolist (item response)<br>      (let* ((ticker (cdr (assoc :TICKER (cdr item))))<br>      (cik (cdr (assoc :CIK--STR (cdr item))))<br>      (company (cdr (assoc :TITLE (cdr item))))<br>      (value (list (cons &#39;company company) (cons &#39;cik cik))))<br> (setf (gethash ticker *company-info*) value)))))<br></pre><p>Now let’s populate our hash table by running our read-tickers function:</p><pre>;;; Populate hash table<br>(read-tickers)</pre><p>So now, if we inspect our *company-info* hash-table we can see that it has been filled with company data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mjs0EwK1SmWIFdksgR_KwA.png" /></figure><p>That is great, but remember, the CIK number must be 10 digits long, padded with zeros if shorter, so we need a function to pad the CIK numbers with zeros:</p><pre>(defun pad-cik (cik)<br>  &quot;Pad CIK number so it is always 10 digits long&quot;<br>  (format nil &quot;~10,&#39;0d&quot;  cik))</pre><p>Now let’s write a utility function to get the CIK number using the Ticker name:</p><pre>(defun get-stock-cik (ticker)<br>  &quot;Get CIK number for a given ticker&quot;<br>  (let ((data (gethash ticker *company-info*)))<br>    (pad-cik (cdr (assoc &#39;cik data)))))</pre><p>Let’s test our function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DICCW0Kb9xjyDjZ9d-J07Q.png" /></figure><p>Since we’ve already tucked away the company name in our hash table, how about we write a function to retrieve the company name using its ticker symbol?</p><pre>(defun get-company-name (ticker)<br>  &quot;Get company name for a given ticker&quot;<br>  (let ((data (gethash ticker *company-info*)))<br>    (cdr (assoc &#39;company data))))</pre><p>Let’s test it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H_cVR4--9MM-e2ftmVpVpQ.png" /></figure><p>Okay, I think we are ready to start pulling data from EDGAR. But let’s save that adventure for our next post. See you next time!</p><p><a href="https://medium.com/@codingcamel/extracting-fundamental-stock-data-from-edgar-using-our-favorite-language-common-lisp-part-2-f28099de4b71">Extracting Fundamental Stock Data from EDGAR using our favorite language: Common Lisp (Part 2)</a></p><blockquote>PS. I get it, I get it, Python could handle this, but let’s be honest, tackling it in Common Lisp just adds an extra layer of fun!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*ppbzmobR7kzuBNoU1ZChNg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3171d100dd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Realidad Aumentada — Construyendo un ARSandbox]]></title>
            <link>https://medium.com/@codingcamel/realidad-aumentada-construyendo-un-arsandbox-6920258095ff?source=rss-cfbab30c8a1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6920258095ff</guid>
            <category><![CDATA[proyectos]]></category>
            <category><![CDATA[augmented-reality]]></category>
            <category><![CDATA[realidad-aumentada]]></category>
            <dc:creator><![CDATA[Muro]]></dc:creator>
            <pubDate>Wed, 05 Jun 2019 12:43:51 GMT</pubDate>
            <atom:updated>2019-06-05T12:43:51.773Z</atom:updated>
            <content:encoded><![CDATA[<h3>Realidad Aumentada — Construyendo un ARSandbox</h3><p>Hace algunos años (en 2012, para ser más específico), Oliver Kreylos de UCDavis publicó este video en YouTube donde se convierte una simple caja de arena en una herramienta educativa usando augmented reality. El proyecto se llama ARSandbox.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fj9JXtTj0mzE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dj9JXtTj0mzE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fj9JXtTj0mzE%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c11405b17a9b8c7c4635d2f3956862f2/href">https://medium.com/media/c11405b17a9b8c7c4635d2f3956862f2/href</a></iframe><p>Oliver también publicó las instrucciones paso a paso de cómo construir tu propia ARSandbox (<a href="https://arsandbox.ucdavis.edu/instructions/">https://arsandbox.ucdavis.edu/instructions/</a>) por si algún día te animas a construir una.</p><p>Afortunadamente ese día llegó para mi bajo la excusa de hacer un proyecto para la Feria de Ciencias del colegio de mis hijos. En este post les contaré como construí mi propia ARSandbox y algunos de los problemas que fui encontrando durante el proceso.</p><p><strong>Hardware</strong></p><p><strong><em>Una caja de arena</em></strong><br>La caja debe tener una proporción de 4:3 pues esta es la resolución que se proyectará en la caja y es también la resolución que tiene el sensor del Kinect.</p><p>En mi caso construí la caja de arena con dimensiones de 40x30”. Para construir la caja use tablones de madera de 2x4” así que la profundidad de la caja fue de unos 10cm (casi 4”).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*p6m4B_hCQl0nBS_J3QBYLA.jpeg" /><figcaption>Caja de arena (40 x 30&quot; x 4&quot;)</figcaption></figure><p><strong><em>Un proyector</em></strong></p><p>En mi caso yo tengo un proyector ViewSonic PJD5134. Este proyector tiene una proporción de 4:3 (SVGA) lo cual es conveniente para este proyecto.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*SpjHu1srwrhGqCSI1Bw_wQ.jpeg" /><figcaption>Proyector ViewSonic PJD5134</figcaption></figure><p>Normalmente el proyector debe ir a 40” (aproximadamente 1m) sobre la caja de arena como se muestra en la siguiente figura:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*IcNO2C__196-V51X-cNtqA.png" /><figcaption>Esquema del ARSandbox</figcaption></figure><p>El problema con esto es que si se usa un proyector normal como mi ViewSonic PJD5134, la imagen proyectada será muy pequeña. Como se puede ver en la foto, necesitamos cubrir un area de 40x30” con el proyector colocado a 40” de la caja, pero mi proyector solo es capaz de cubrir un area de 23x17”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*e84uKowPeX23SFZ9ZzKNmw.jpeg" /><figcaption>Mi ViewSonic no puede cubrir 40x30”. Y ahora que hacemos?.</figcaption></figure><p>El tutorial recomienda el uso de un proyector de tiro corto como el BENQ MX631 ST pero este proyector cuesta unos 650 USD y francamente no quería gastar mucho dinero en este proyecto. (Si no sabes que es un proyector de tiro corto puedes leer este <a href="https://hipertextual.com/archivo/2011/12/proyectores-de-tiro-corto-para-dummies/">articulo</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*t6y6awN37Llt6HnkCyFcCg.jpeg" /><figcaption>650 dolares? No, gracias</figcaption></figure><p>Una opción para resolver este problema es poner el proyector más allá de la distancia recomendada de 40” (~1m). Para calcular cual sería la distancia para proyectar 40x30” usé una app llamada ProjectorPro.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*rw94X2QnNAecuJR4c2B3dA.png" /></figure><p>ProjectorPro recomienda suspender el proyector a 2m de la caja de arena para obtener una imagen de 30x40&quot;. Esto no es lo ideal pues con el proyector suspendido esta altura existe el riesgo de que caiga sobre los niños así que preferí evitar el riesgo y me puse a buscar otra alternativa.</p><p>Afortunadamente encontré en YouTube in video que explica cómo transformar un proyector convencional a uno de tiro corto usando sólo un espejo!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F1X_V8Oy-ssY%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D1X_V8Oy-ssY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F1X_V8Oy-ssY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e63b3552abe1b3eb4c5898044621402/href">https://medium.com/media/4e63b3552abe1b3eb4c5898044621402/href</a></iframe><p>Usando este truco lo que hice fue poner el proyector en el piso apuntando hacia arriba y colgué un espejo rectangular a 1m sobre la caja de arena. Esto me permitió conseguir la imagen de 40x30”.</p><p><strong><em>Sensor Kinect</em></strong></p><p>Para este proyecto necesitamos cualquiera de estos modelos de la primera generación de Kinect: 1414 o 1473</p><p>Estos los puedes conseguir en Amazon a unos 20–30 USD.<br>Asegúrate de comprar el adaptador para conectarlo al toma corriente.</p><p><strong><em>Computadora</em></strong></p><p>En mi caso yo usé una PC corriendo Linux Mint. Esta computadora tenía una tarjeta de video Nvidia GTX1070.<br>La tarjeta de video es sólo necesaria si se quiere simular lluvia. Si sólo se quiere tener los mapas topográficos entonces una PC con 2GB de RAM debe ser suficiente para correr el software de ARSandbox.</p><p><strong>La estructura</strong></p><p>Podría decir que casi el 90% del tiempo en este proyecto estuve dedicado en construir la estructura que inicialmente estaba pensada para soportar el proyector y el sensor Kinect. Debo admitir que no soy muy buen carpintero.</p><p>En la foto de abajo se puede ver el proyector apuntando hacia arriba con la imagen siendo reflejada en el espejo que está colgado a aproximadamente 1m de la caja. El sensor Kinect también está colgado a esta altura y apunta hacia el cento de la caja. En la imagen se puede ver un hilo con una tuerca que usé como plomada para asegurarme que el sensor esté apuntando al centro.</p><p>Otro detalle a tener en cuenta es que la imagen del proyector debe ser reflejada en el espejo por lo que tendremos que configurar el proyector en “mirror mode”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*zWc3NkHl29vTBoQiRbTJ8A.jpeg" /><figcaption>La estructura terminada.</figcaption></figure><p><strong>Software</strong></p><p>Para este proyecto necesitamos una PC corriendo Linux. En mi caso yo usé Linux Mint 64 bits.</p><p>Si vamos a usar la tarjeta de video entonces lo primero que debemos hacer es instalar los drivers para nuestra tarjeta de video.</p><p>Una vez que los drivers están instalados abrimos el terminal y escribimos:</p><p>cd ~<br> wget http://idav.ucdavis.edu/~okreylos/ResDev/Vrui/Build-Ubuntu.sh<br> bash Build-Ubuntu.sh</p><p>Esto va a instalar algunas librerías y el toolkit Vrui. Si todo sale bien veremos la imagen de un globo terráqueo.</p><p>Ahora necesitamos instalar el software para Kinect. En el terminar escribe lo siguiente:</p><p>cd ~/src<br> wget http://idav.ucdavis.edu/~okreylos/ResDev/Kinect/Kinect-3.2.tar.gz<br> tar xfz Kinect-3.2.tar.gz<br> cd Kinect-3.2<br> make<br> sudo make install<br> sudo make installudevrules<br> ls /usr/local/bin</p><p>Una vez que termine la instalación verifica que los últimos comandos impresos contengan KinectUtil y RawKinectViewer.</p><p>Ahora toca instalar el software para el ARSandbox. De nuevo, en el terminal escribe los siguientes comandos:</p><pre>cd ~/src<br>wget http://idav.ucdavis.edu/~okreylos/ResDev/SARndbox/SARndbox-2.3.tar.gz<br>tar xfz SARndbox-2.3.tar.gz<br>cd SARndbox-2.3<br>make<br>ls ./bin</pre><p>Una vez que la instalación termine verifica que los últimos comandos impresos contengan CalibrateProjector y SARndbox.</p><p>Ahora conecta tu Kinect al puerto USB de tu computadora y ejecuta el siguiente comando:</p><p>sudo /usr/local/bin/KinectUtil getCalib 0</p><p>Ahora lo que debes hacer es alinear el Kinect para que cubra el interior de la caja de arena. Puedes usar RawKinectViewer para orientarte:</p><p>cd ~/src/SARndbox-2.3<br> RawKinectViewer -compress 0</p><p>De ahora en adelante lo que queda es calibrar el ARSandbox. Para ello puedes usar el siguiente video como referencia:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FEW2PtRsQQr0%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DEW2PtRsQQr0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FEW2PtRsQQr0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/55e0c917b32a6674cacab37d60a3a145/href">https://medium.com/media/55e0c917b32a6674cacab37d60a3a145/href</a></iframe><p><strong>El producto Final</strong></p><p>Aquí les muestro algunas fotos del resultado final. Fue genial ver a niños y adultos experimentar con el ARSandbox durante la Feria de Ciencias.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*k0Mbwt-AHMsz9i3sSC2niA.jpeg" /><figcaption>ARSandbox terminada!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*E625Z5ikI4sPCo8m4NM7kQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*8-MEQ9u7RaS0ls52cNqKFg.jpeg" /><figcaption>Niños experimentando con el ARSandbox</figcaption></figure><p>Hasta la proxima!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6920258095ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>