<?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 Jonathan Mines on Medium]]></title>
        <description><![CDATA[Stories by Jonathan Mines on Medium]]></description>
        <link>https://medium.com/@jonathanmines?source=rss-abab53e7b107------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*VM1Mq_h3M_4je-iD.jpeg</url>
            <title>Stories by Jonathan Mines on Medium</title>
            <link>https://medium.com/@jonathanmines?source=rss-abab53e7b107------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 07:05:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jonathanmines/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[Hiding Your Secrets in Rails 5 Using Credentials]]></title>
            <link>https://medium.com/@jonathanmines/hiding-your-secrets-in-rails-5-using-credentials-e37174eede99?source=rss-abab53e7b107------2</link>
            <guid isPermaLink="false">https://medium.com/p/e37174eede99</guid>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[credentials]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Jonathan Mines]]></dc:creator>
            <pubDate>Sun, 16 Sep 2018 17:10:13 GMT</pubDate>
            <atom:updated>2018-09-16T17:10:13.149Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*gmsa-qjBdv7FAwUQ_CQCbw.jpeg" /></figure><p>While there are a number of blog posts that address the new Rails’ way of handling secrets, there was still a bit of piecing together I had to do in order to figure out exactly how to use the new Credentials file correctly. It was also a bit unclear how to tie this in with Heroku so I wanted to walk through the whole process.</p><p>First off, there’s only two files to deal with:</p><pre>config/credentials.yml.enc</pre><p>and…</p><pre>config/master.key</pre><p>All your secrets are encrypted and stored in the credentials file (Do not edit this file directly!!). And the master.key file will hold the key to decrypt the credentials file.</p><p>What this is means is you <strong>CAN</strong> check your credentials file into version control but you <strong>SHOULD NOT</strong> upload your master.key file.</p><h3>Changing Credentials</h3><p>In order to change/update your credentials you’ll need to use the rails credentials edit command in the terminal. In your terminal, type:</p><pre>// ♥ EDITOR=&quot;atom --wait&quot; rails credentials:edit</pre><p>You can swap out atom for whichever editor you prefer. Note that two things should happen:</p><ol><li>A file should open with a name that ends in “.credentials.yml”. This file will hold all your current credentials (in may be blank if you have none).</li><li>Your terminal should hang. The “wait” flag we added is telling the terminal that we haven’t finished editing our credentials file and so the file isn’t ready to be encrypted. While the Atom window is open, the terminal should be waiting. Once you save and close the window you should get this message:</li></ol><pre>New credentials encrypted and saved.</pre><h3>Formatting Your Credentials</h3><p>Your credentials should be written as key-value pairs in plain text. In other words, no quotations needed for strings. For example:</p><pre>github_secret: 1241212</pre><p>You can also nest your credentials if you’d like:</p><pre>github:<br>  secret: 1241212</pre><p>Lastly, if you’d like to create Environment specific variables, you can do that, as well:</p><pre>development:<br>  github:<br>    secret: 1241212</pre><pre>production:<br>  github:<br>    secret: 1241212</pre><p>But whatever you do, don’t touch the “secrete_key_base” line at the bottom of the file. That is generated automatically. Remember it, because you’ll need it later.</p><h3>Reading Your Credentials</h3><p>You can access your credentials in your code like so</p><pre>// One Key-Value pair<br>Rails.application.credentials.github_secret</pre><pre>// Nested Key-Value pair<br>Rails.application.credentials.github[:secret]</pre><pre>// Environment Variables<br>Rails.application.credentials[Rails.env.to_sym][:github][:secret]</pre><h3>Deploying Master.key to Heroku</h3><p>This system is pretty straightforward in development but what happens when you deploy your project, leaving your Master.key file behind?</p><p>Heroku.config to the rescue.</p><p>Heroku provides a fast and easy way to upload secret keys and information you may not want in your code but which is necessary for your program to work. There’s two keys we’ll need to set to Heroku.config in order to make our credentials accessible in production:</p><ol><li>Our Master Key</li><li>Our Secret Key base</li></ol><p>From the config/master.key file in your Rails project, copy the line of jumbled numbers and letters. Then, in your terminal, run:</p><pre>heroku config:set RAILS_MASTER_KEY=&lt;your_master_key_here&gt;</pre><p>To see if that worked, type:</p><pre>heroku config:get RAILS_MASTER_KEY</pre><p>Next, you’ll want to use the same command to set your Secret Key base:</p><pre>heroku config:set SECRET_KEY_BASE=&lt;your_secret_key_base_here&gt;</pre><p>Check to make sure that stuck.</p><p>And that’s it! Your credentials are now hidden but accessible when they’re needed both in production and development.</p><p><strong>Resources:</strong></p><ul><li><a href="https://medium.com/cedarcode/rails-5-2-credentials-9b3324851336">Rails 5.2 credentials</a></li><li><a href="https://devcenter.heroku.com/articles/config-vars">Configuration and Config Vars</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e37174eede99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ultimate Github Collaboration Guide]]></title>
            <link>https://medium.com/@jonathanmines/the-ultimate-github-collaboration-guide-df816e98fb67?source=rss-abab53e7b107------2</link>
            <guid isPermaLink="false">https://medium.com/p/df816e98fb67</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[version-control]]></category>
            <dc:creator><![CDATA[Jonathan Mines]]></dc:creator>
            <pubDate>Tue, 29 May 2018 21:53:23 GMT</pubDate>
            <atom:updated>2018-05-29T21:53:23.406Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*xPjeXkXbzEPfRtZpY5DQAg.png" /></figure><p>This is just one of many ways to collaborate on a project using GitHub. But it’s one I would suggest if you’re just starting out working with a team and haven’t established a git flow yet or know where to start in establishing one.</p><h4><strong>Step 1: Initialize a New Project</strong></h4><p>Create a new project/directory from the command line</p><pre>$ rails new github_guide</pre><p>Go to Github and click the ‘+’ button in the rop right corner and select ‘New Repository’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*0gx83wX79Wfq3WdcjN5nvw.png" /></figure><p>Then fill out the Repository name and the Description fields. Keep it public, and do not “Initialize this repository with a README”. Don’t change anything else. Click “Create repository”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJdSUFk1d-1uTmrLkJkjmw.png" /></figure><p>Next you’ll see the setup page. These are the instructions for connecting the Repo you just created in Github (Remote) to the directory you created in your terminal (Local).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pvRwPOug8wVuk8EM25ws-Q.png" /></figure><p>Paste the lines in the red box line by line starting with “echo…” into the terminal while you’re cd’ed into the directory you just created locally. Your terminal should look like this when you’re done:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*moqvwzJVDxkjH-Qy2UFtmw.png" /></figure><p>This adds a ‘.git’ folder to your repo, connects you to your remote Github Repo and also gives you a ‘.gitignore’ file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*qYeHJmd9OB9wvs8PqQDhPQ.png" /></figure><p>And if you go to your Github Repo page, you’ll see the ReadMe that you intialized with and the reference to the first commit you made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1crKu14IoOuFulcVLCZA9Q.png" /></figure><p>Now let’s get this Repo up to date. Go back to your terminal and git add, git commit, and git push:</p><pre>$ git add .</pre><pre>$ git commit -m &quot;Second commit&quot;</pre><pre>$ git push</pre><p>Now check out your repo. It should have all the files you created your local directory with along with a new commit id (9c2e2f6):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8CzAFDVFCRSUyIEOKGD1iw.png" /></figure><p>You’re initialized and ready to start working!</p><h4>Step 2: Setup Your Team</h4><p>You’re a team player, so you’re going to need to add your team to your repo so they can collaborate. Once your team is added as collaborators they’ll be able to push, merge, and a ton of other destructive things so make sure you’re only adding your teammates.</p><p>Click on the “Settings” tab of your rep, then “Collaborators” then search for Github users and add them by clicking “Add Collaborator”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d9X61cAkfn6Tf6BowMv0bA.png" /></figure><p>They’ll receive an email letting them know you added them and will be listed as a collaborator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-pN7vCBetD7X8Of0xSN2Qg.png" /></figure><p>If you’re a collaborator, go to the Github Repo page, Git Clone the project, and cd into the directory. <strong>Don’t fork it!</strong> Forking will copy it in a new Repo to your Github page, but you don’t want that — you want to collaborate on the same Github Repo with your teammates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cY5xNLKiGczmwju9iJ3L0A.png" /></figure><pre>$ git clone git@github.com:MinesJA/github_guide.git</pre><pre>$ cd github_guide/</pre><p>And now you’re ready to collaborate!</p><h4>Step 3: Collaborating</h4><p>When you’re using git to work on the same project with multiple people, there’s one central rule you must follow:</p><p><strong>THE MASTER BRANCH SHOULD ALWAYS BE DEPLOYABLE</strong></p><p>The way to keep Master deployable is to create new branches for new features and merge them into Master when they’re completed. Here’s how that works.</p><p><strong>Step 3a: Branches</strong></p><p>To start, branches should always represent features. For example, if you want to add the ability for a user to login you should probably create a branch called “user_authentication” and in that branch you should only update what you need to to enable a user to login.</p><p>It’s also important when collaborating that your team picks features that don’t have overlapping code. For example, you shouldn’t be working on a “user_login” branch at the same time that your teammate is working on a “user_logout” branch because the chances that you’re working on the same files and are writing overlapping code are very high.</p><p>So let’s say you want to create the User model. In your terminal create a new branch:</p><pre>$ git co -b create_user</pre><p>“co” is short for “checkout” which is used to switch between branches. Adding the “-b” and a name at the end creates a new branch and then moves into that new branch for us.</p><p>You should be able to verify this with the command:</p><pre>$ git branch</pre><p>Which should produce:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*D3_hkRB0bpq12yJKWE_WIw.png" /></figure><p>You’re now in your new branch and can start coding away.</p><p><em>Note: As a general rule, you should git add frequently and git commit when you finish something that allows your code to work (ends up being a couple times an hour). For example, when you finish a method and the code base works, git commit like so:</em></p><pre>$ git commit -m &quot;Added function to allow Users to say &#39;Hello World&#39;&quot;</pre><p><strong>Step 3b: Submitting Pull Requests</strong></p><p>Your team spent all day and night working on their separate features in their various branches. They come back the next day with their completed features and want to merge them back into Master to be deployed.</p><p>Determining your Git Flow is a huge part of working in a team, but here’s one Git Flow you could adopt for now:</p><p>First, determine who’s going to be in charge of handling merging. The less people acting independently on merging the better so for a team of 4 it would probably behoove you to have one official “Reviewer” or “Merge Master”.</p><p>Next, have everyone git push their branches:</p><pre>$ git push</pre><p>Now go to the Github Repo page. You should see the branch you pushed up in a yellow bar at the top of the page with a button to “Compare &amp; pull request”.</p><p><em>Note: Alternatively, you can select the branch in the drop-down “Branch:” menu and select the branch you just pushed up. You’ll then have a “Pull request” and “Compare” button on the right hand side.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kaW2pkUlWGRXAfV8SgbriQ.png" /></figure><p>Click “Compare &amp; pull request”. This will take you to the “Open a pull request” page. From here, you should write a brief description of what you actually changed. And you should click the “Reviewers” tab and select whoever your team decided would be the “Merge Master”. When you’re done, click “Create pull request”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uildE3NOi5GUzV9Ua_US-Q.png" /></figure><p><strong>Step 3c: Merging Pull Requests</strong></p><p>Note that if you’re a collaborator, you can merge your own pull requests. But, again, if you’re working on a team, it makes more sense to have one person do all the merging and everyone else submit “Pull Requests” and assign the “Master Merger” as a reviewer just to make sure you’re dealing with any merge conflicts one branch at a time.</p><p>So, assuming you are the one charged with taking care of all merges and someone has assigned you as “Reviewer” on a pull request, when you login to your Github you’ll notice you have a notification letting you know that someone has assigned you as a reviewer. You’ll also noticed a yellow bar indicating one of your teammates as “requested your review on this pull request.”</p><p>Go ahead and click the “Add your review” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PzcyyMvbXcqLpEYX2jegiQ.png" /></figure><p>This will take you to the Pull Request page. How you move forward from here is up to you and your team. If you’re working together I would use every morning to sit down as a team and go through pull requests together. If you do that, you won’t have to necessarily leave long-winded, detailed Review Summaries.</p><p>However, if you’re working remotely, this will be your main tool for letting the requester know if they need to make changes or if you’re going to merge their request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-zGySbe7YiIYaxXZ5ISk7g.png" /></figure><p>When you click “Submit review” on the “Review changes” drop-drown your review will now exist as a comment on the pull request thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hgwTKcQgHGRmhSei7ulp3w.png" /></figure><p>When you’re satisfied with the pull request, go to the bottom of the pull request and click “Merge pull request”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D7vtotpgLhtS7pysz3pxjQ.png" /></figure><p>You’ll then see a “Pull request successfully merged and closed” message and a button to “Delete branch” which you should click.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YZXAH8PyO6relJe7H0258w.png" /></figure><h4>Step 4: Rinse, Repeat</h4><p>And that’s pretty much it! Keep adding new branches for new features and then coming together as a team to merge them into master. Keep master clean and deployable and don’t try to merge more than one branch at a time and you should be good to go.</p><p>**************<br>Here’s the repo I used for this demonstration. I’ll add the text of this article into the ReadMe. Feel free to make a pull request if there’s anything you want to change or if you just want to test out your pull request skills!</p><p><a href="https://github.com/MinesJA/github_guide">https://github.com/MinesJA/github_guide</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df816e98fb67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The MapLector: A Beginners Guide to Creating Array Methods in Ruby]]></title>
            <link>https://medium.com/@jonathanmines/the-maplector-a-beginners-guide-to-creating-array-methods-in-ruby-3f059bcebace?source=rss-abab53e7b107------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f059bcebace</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[array-methods]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Jonathan Mines]]></dc:creator>
            <pubDate>Fri, 11 May 2018 21:06:39 GMT</pubDate>
            <atom:updated>2018-05-12T15:29:12.817Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*OczpyalO_wC7F-wrUfxL_A.png" /></figure><p>While conducting a review lecture of many-to-many relationships in Ruby, my students had one demand of the higher-level array methods .select and .map I pushed them to use:</p><blockquote>“Why isn’t there a method that does both those things?”</blockquote><p>So I figured, what better way to illustrate how different blocks work in higher-level array methods than to build a custom array method ourselves that achieves this. We’ll call it: <strong>The MapLector.</strong></p><h4>The Problem We’re Trying to Solve</h4><p>To illustrate the problem, let’s setup some instances we’ll want to iterate over. We’ll create a Person class, give it an attribute of name and age set on initialization, and collect those instances in a global variable:</p><pre>class Person<br>  attr_accessor :name, :age<br>  <br>  @@all = []</pre><pre>  def initialize(name, age)<br>    @name = name<br>    @age = age<br>    @@all &lt;&lt; self<br>  end</pre><pre>  def self.all<br>    @@all<br>  end</pre><pre>end</pre><p>Now lets create people instances and verify that they’re all there:</p><pre>bob = Person.new(&quot;Bob&quot;, 29)<br>susy = Person.new(&quot;Susy&quot;, 19)<br>carl = Person.new(&quot;Carl&quot;, 46)<br>frank = Person.new(&quot;Frank&quot;, 41)<br>sue = Person.new(&quot;Sue&quot;, 21)<br>susan = Person.new(&quot;Susan&quot;, 15)<br>betty = Person.new(&quot;Betty&quot;, 46)<br>stacy = Person.new(&quot;Stacy&quot;, 4)</pre><pre>Person.all</pre><pre>=&gt; [#&lt;Person:0x000055a012f32818 @name=&quot;Bob&quot;, @age=29&gt;, <br>    #&lt;Person:0x000055a012f327c8 @name=&quot;Susy&quot;, @age=19&gt;, <br>    #&lt;Person:0x000055a012f32778 @name=&quot;Carl&quot;, @age=46&gt;, <br>    #&lt;Person:0x000055a012f32700 @name=&quot;Frank&quot;, @age=41&gt;, <br>    #&lt;Person:0x000055a012f326b0 @name=&quot;Sue&quot;, @age=21&gt;, <br>    #&lt;Person:0x000055a012f32660 @name=&quot;Susan&quot;, @age=15&gt;, <br>    #&lt;Person:0x000055a012f32610 @name=&quot;Betty&quot;, @age=46&gt;, <br>    #&lt;Person:0x000055a012f325c0 @name=&quot;Stacy&quot;, @age=4&gt;]</pre><p>Awesome, we’ve got 8 different people between the ages of 4 and 46. Now, let’s say we wanted to select all the people over the age of 19.</p><pre>Person.all.select {|person| person.age &gt; 19}</pre><pre>=&gt; [#&lt;Person:0x000055a012f32818 @name=&quot;Bob&quot;, @age=29&gt;, <br>    #&lt;Person:0x000055a012f32778 @name=&quot;Carl&quot;, @age=46&gt;, <br>    #&lt;Person:0x000055a012f32700 @name=&quot;Frank&quot;, @age=41&gt;, <br>    #&lt;Person:0x000055a012f326b0 @name=&quot;Sue&quot;, @age=21&gt;, <br>    #&lt;Person:0x000055a012f32610 @name=&quot;Betty&quot;, @age=46&gt;]</pre><p>Piece of cake. The .select only includes a particular item if its block evaluates to true. So all we had to do is give it a statement that evaluated to true for every instance that had an age attribute greater than 19.</p><p>But what if we wanted to return just the names? Let’s try:</p><pre>Person.all.select {|person| person.age &gt; 19 return person.name}</pre><pre>syntax error, unexpected &#39;}&#39;, expecting end-of-input ...on.age &gt; 19 return person.name}</pre><p>So it didn’t like that. What if we tried:</p><pre>Person.all.select {|person| person.name if person.age &gt; 19}</pre><pre>=&gt; [#&lt;Person:0x000055a012f32818 @name=&quot;Bob&quot;, @age=29&gt;, <br>    #&lt;Person:0x000055a012f32778 @name=&quot;Carl&quot;, @age=46&gt;, <br>    #&lt;Person:0x000055a012f32700 @name=&quot;Frank&quot;, @age=41&gt;, <br>    #&lt;Person:0x000055a012f326b0 @name=&quot;Sue&quot;, @age=21&gt;, <br>    #&lt;Person:0x000055a012f32610 @name=&quot;Betty&quot;, @age=46&gt;]</pre><p>But that returned the entire instance, just like before. We wanted an array of just their names. At this point it should be clear that it’s the way in which the select block is designed that prevents this kind of selective return. The only thing the block cares about is whether or not something is true or false.</p><p>.map, on the other hand, will actually return what we explicitly tell it to return, meaning, we can map over the area of selected instances and print out just their names like so.</p><pre>over_19 = Person.all.select {|person| person.age &gt; 19}</pre><pre>over_19.map {|person| person.name}</pre><pre>=&gt; [&quot;Bob&quot;, &quot;Carl&quot;, &quot;Frank&quot;, &quot;Sue&quot;, &quot;Betty&quot;]</pre><p>Awesome, but like we mentioned earlier, we want to create a method that gives us the above functionality in one iteration/step.</p><h4>The MapLector</h4><p>To start, we’ll want the same functionality as a .select or .map, meaning we’ll want to be able to call it on an array in the same way we can call</p><pre>[1,2,3].select</pre><pre># or </pre><pre>[1,2,3].map</pre><p>Turns out, arrays are just instances of the Array class and .select/.map are just instance methods on the Array class. So let’s start by defining a method on the Array class:</p><pre>class Array<br>  <br>  def maplector<br>    puts &quot;hello world&quot;<br>  end</pre><pre>end</pre><p>Now check this out:</p><pre>[1,2,3].maplector</pre><pre>=&gt; hello world</pre><p>Unbelievable.</p><p>Now let’s try to formulate this iterator. We know we’ll want to iterate through a collection and then return a new array. So let’s build a simple loop with a counter that increments after every loop and then stops after it hits the length of the array.</p><pre>class Array<br>  <br>  def maplector<br>    i = 0<br>    out_array = []<br>    <br>    while i &lt; self.length<br>      puts i</pre><pre>      i += 1<br>    end<br>    <br>    out_array<br>  end</pre><pre>end</pre><pre>[5,6,7].maplector</pre><pre>0<br>1<br>2<br>=&gt; []</pre><p>Awesome, it works! We established a counter starting at 0, created an empty array, created a loop that runs as long as the counter is less than the length of the array instance (called by “self” in this case), printed out “i” for every loop (just to make sure it’s working) and incremented the counter at the end of every loop. Lastly, after the loop was finished, we returned the array we originally created.</p><p>Now, let’s make it maplect.</p><p>First off, we’ll need to create the “block” functionality. We do that using the Ruby keyword “yield”. “yield” allows us to pass a value to the block and then operate on the return value. Let’s go back to our Person class to demonstrate how this works:</p><pre>class Array<br>  <br>  def maplector<br>    i = 0<br>    out_array = []<br>    <br>    while i &lt; self.length<br>      puts yield self[i]</pre><pre>      i += 1<br>    end<br>    <br>    out_array<br>  end</pre><pre>end</pre><pre>Person.all.maplector{|person| person.name }</pre><pre><strong>   <br></strong>Bob<br>Susy<br>Carl<br>Frank<br>Sue<br>Susan<br>Betty<br>Stacy<br>=&gt; []</pre><p>As you can see, “yield” passed the value of self[i] up to the block on every iteration, and the block grabbed the name of each item and sent it back down to the while loop to be put out to the screen.</p><p>To further drive home this point, look what happens when we take yield out:</p><pre>class Array<br>  <br>  def maplector<br>    i = 0<br>    out_array = []<br>    <br>    while i &lt; self.length<br>      puts self[i]</pre><pre>      i += 1<br>    end<br>    <br>    out_array<br>  end</pre><pre>end</pre><pre>Person.all.maplector{|person| person.name }</pre><pre>#&lt;Person:0x0000562889831f00&gt;<br>#&lt;Person:0x0000562889831eb0&gt;<br>#&lt;Person:0x0000562889831e60&gt;<br>#&lt;Person:0x0000562889831e10&gt;<br>#&lt;Person:0x0000562889831dc0&gt;<br>#&lt;Person:0x0000562889831d70&gt;<br>#&lt;Person:0x0000562889831cf8&gt;<br>#&lt;Person:0x0000562889831ca8&gt;<br>=&gt; []</pre><p>Instead of everyones name being printed the instance itself is printed because the “person.name” clause isn’t being run; the block isn’t being invoked at all.</p><p>Alright, so we’ve got the tools. Let’s pull it all together. To revisit, I want to be able to do the following:</p><pre>Person.all.maplector {|person| person.name if person.age &gt; 19}</pre><pre>=&gt; [&quot;Bob&quot;, &quot;Carl&quot;, &quot;Frank&quot;, &quot;Sue&quot;, &quot;Betty&quot;]</pre><p>While there are a couple ways of doing this, a simple, straightforward approach would be to push every return of a yield into the array we created above our loop like so:</p><pre>class Array<br>  <br>  def maplector<br>    i = 0<br>    out_array = []<br>    <br>    while i &lt; self.length<br>      out_array.push(yield self[i])<br>      i += 1<br>    end<br>    <br>    out_array<br>  end<br>    <br>end</pre><p>That will give us a map-like functionality resulting in the following array:</p><pre>Person.all.maplector {|person| person.name if person.age &gt; 19}</pre><pre>=&gt; [nil, nil, &quot;Carl&quot;, &quot;Frank&quot;, nil, nil, &quot;Betty&quot;, nil]</pre><p>From there, excluding the “nil’s” is as simple as running Ruby’s .compact method on the array before returning it like so:</p><pre>class Array<br>  <br>  def maplector<br>    i = 0<br>    out_array = []<br>    <br>    while i &lt; self.length<br>      out_array.push(yield self[i])<br>      i += 1<br>    end<br>    <br>    out_array.compact<br>  end<br>    <br>end</pre><pre>Person.all.maplector {|person| person.name if person.age &gt; 19}</pre><pre>=&gt; [&quot;Bob&quot;, &quot;Carl&quot;, &quot;Frank&quot;, &quot;Sue&quot;, &quot;Betty&quot;]</pre><p>Behold, the .maplector!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f059bcebace" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Upload CSV’s using React, Rails and Fetch]]></title>
            <link>https://medium.com/@jonathanmines/how-to-upload-csvs-using-react-rails-and-fetch-5cb33dca7c01?source=rss-abab53e7b107------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cb33dca7c01</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jonathan Mines]]></dc:creator>
            <pubDate>Thu, 12 Apr 2018 14:21:39 GMT</pubDate>
            <atom:updated>2018-04-12T14:21:39.781Z</atom:updated>
            <content:encoded><![CDATA[<p>While working on a project I ran into some trouble finding the right way to upload CSV files to my rails backend using a React frontend and fetch requests as the mechanism for posting. So once I figured out the right way to do that I figured I’d write a post for the next person who might come across this issue.</p><h4>React Frontend</h4><p>On your FrontEnd, you’ll need an Input component with a type of “file”. I’m using Semantic UI React components so I imported their Input component like so:</p><pre>&lt;Input<br>   type=&quot;file&quot;<br>   ref={(input) =&gt; { this.filesInput = input }}<br>   name=&quot;file&quot;<br>   icon=&#39;file text outline&#39;<br>   iconPosition=&#39;left&#39;<br>   label=&#39;Upload CSV&#39;<br>   labelPosition=&#39;right&#39;<br>   placeholder=&#39;UploadCSV...&#39;<br>   onChange={this.handleChange}<br> /&gt;</pre><p>You’ll also need a handleChange function that grabs the attribute containing the actual file. Generally, with an input you might find yourself grabbing event.target.value. In The case of CSV uploads, you’re instead looking for your uploaded file in the “files” attribute. Because the files attribute is an array and I’m only looking to upload a single file at a time, I just select the first file by giving the selector a [0] index like so.</p><pre>handleChange = (event) =&gt; {<br>    this.setState({<br>      csv: event.target.files[0]<br>    })<br>  }</pre><p>Once you have the file you want to upload to your backend you’ll need to make a post request. Here’s where things may be a little different from how you would normally format post requests. First, you’ll need to create an instance of a FormData and append the file and any other information you may want to send like so:</p><pre>let formData = new FormData();<br>  formData.append(&#39;file&#39;, csv);<br>  formData.append(&#39;buys&#39;, buys)</pre><p>From the documentation, FormData is simply:</p><blockquote>provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send">XMLHttpRequest.send()</a> method. It uses the same format a form would use if the encoding type were set to &quot;multipart/form-data&quot;.</blockquote><p>So think of it as an object creator, and the result of its instantiation as an object. In my case, I wanted to send the csv itself, which I set to a key of “file” in the first append and I also wanted to send a boolean called “buys” which I set to the key “buys” in the second append.</p><p>Now I can format my post request. The options for my post request I created as follows:</p><pre>let options = {<br>    method: &#39;POST&#39;,<br>    headers: {&quot;Authorization&quot;: localStorage.getItem(&quot;token&quot;)},<br>    body: formData<br>  }</pre><p>Notice that I do not include the typical ‘Content-Type’ and ‘Accept’ keys in my headers. In fact, the only reason I have a header at all is because I want to associate the incoming data with a particular user. You may not need to do that so there’s a good chance you won’t have headers at all. This is a crucial difference between a traditional post request and a post request with a CSV.</p><p>The rest of your request is standard:</p><pre>fetch(`<a href="http://localhost:3000/api/v1/csvs%60">http://localhost:3000/api/v1/csvs`</a>, options)<br>      .then(resp =&gt; resp.json())<br>      .then(result =&gt; {</pre><pre>alert(result.message)</pre><pre>})</pre><h4>Rails Backend</h4><p>On your backend, if you put a byebug in the action you’re trying to target in your fetch request you can see the incoming params of the file you’re sending.</p><p>There’s a couple interesting things to note about the file in the params.</p><pre>#&lt;ActionDispatch::Http::UploadedFile:0x007f8b8dae3998 @tempfile=#&lt;Tempfile:/var/folders/bz/184lnygx3pg31h1kjlgmr41r0000gn/T/RackMultipart20180412-5373-1ojnv76.csv&gt;, @original_filename=&quot;StoreDataWon.csv&quot;, @content_type=&quot;text/csv&quot;, @headers=&quot;Content-Disposition: form-data; name=\&quot;file\&quot;; filename=\&quot;StoreDataWon.csv\&quot;\r\nContent-Type: text/csv\r\n&quot;&gt;</pre><p>The attribute you’re most interested in is the tempfile. Using my params I can access that file using the following selectors:</p><pre>params[&quot;file&quot;].tempfile</pre><p>Because this tempfile is just a temporary copy of your CSV you can do whatever you would normally do to a CSV on your backend. For example, adding .read to the end of your tempfile will produce the text that is your CSV file.</p><p>With that string you can use the CSV class to operate on your CSV, extract data, parse the text etc.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cb33dca7c01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data-Oriented vs Object-Oriented Design]]></title>
            <link>https://medium.com/@jonathanmines/data-oriented-vs-object-oriented-design-50ef35a99056?source=rss-abab53e7b107------2</link>
            <guid isPermaLink="false">https://medium.com/p/50ef35a99056</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-oriented]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jonathan Mines]]></dc:creator>
            <pubDate>Tue, 20 Mar 2018 17:40:42 GMT</pubDate>
            <atom:updated>2018-03-20T17:40:42.904Z</atom:updated>
            <content:encoded><![CDATA[<p>Video games are greedy. They can required a tremendous amount of RAM, processing power, and generally put a ton of strain on the physical hardware responsible for fetching, manipulating, and returning data. For that reason, a number of proponents of Data-Oriented Design have emerged to say that maybe Object-Oriented Design isn’t the best way of organizing the code that run these monolithic applications.</p><p>So what is Data-Oriented Design, how does it differ from OOP, and what are some of the rules surrounding how to think about writing DOP code?</p><h4>How does it differ from OOP?</h4><p>As it’s name suggests, Object-Oriented Programming is centered around defining, producing, and operating on objects. It directs coders to:</p><ol><li>Establish what objects are.</li><li>Determine what types of data belong to an object.</li><li>Describe the functionality an object has.</li></ol><p>These objects then interact with other objects through the functions each object owns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*vPgsi75vPCs0MeOEHf9SGQ.jpeg" /><figcaption>How objects work in OOP</figcaption></figure><p>One of the great benefits of OOP is how closely it seems to mirror how we interact with the real world. For example, by knowing something about the class of “Tables” I can save myself a lot of time by knowing what I can and cannot do with a table. You would never point to an instance of a table and ask “What kind of cappuccino’s does this table make?” because the class of tables does not give tables the functionality to make cappuccino’s.</p><p>Out of this concept we also get the benefit of Polymorphism (Poly — Many; Morph — Forms) describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface. If you think about the classification of animals, by knowing that a cat and a tiger are part of the “feline” class, I automatically know a good deal about each of them without diving into any specifics of their particular classes. They both “inherit” certain attributes and data from the higher class of feline.</p><p>But, with this paradigm, functions are restricted to certain pieces of data and cannot be reused. If you want a function to operate on a different piece of data within an object, that function needs to either inherit from a parent class or needs to be rewritten. It’s important to think about how data held within a class that inherits from a parent class is accessed in this paradigm. The data needs to be fetched through multiple classes in order to be accessible the processor, which can be inefficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*qfwHVxcEq7XQjASYCClQpg.png" /><figcaption>An example of the work a processor may have to do in an OOP system.</figcaption></figure><p>Data-Oriented Programming approaches coding in a slightly different way. Instead of objects, everything is data and everything can be acted upon. This separates the functionality and data. They no longer are intertwined by a specific rule set. In DOP your functions are general purpose and are applied to large chunks of data. Ideally, you would structure the data as closely to the output data as possible to ensure the least amount of effort is done by the function itself.</p><blockquote>“Data-Oriented design shifts the perspective of programming from objects to the data itself: The type of the data, how it is laid out in memory, and how it will be read and processed in the game.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*T4XqlgosIzMA_WLzlKWyEw.png" /><figcaption>An example of a DOP call sequence. Much less work for the processor.</figcaption></figure><h4>Why DOP?</h4><p>The simple answer is because processors love locality of reference. This rules dictates many of the other benefits given us with DOP. For example, writing code that optimizes for locality of reference gives us a much easier way to implement Parallelization. Parallelization attempts to use more than one core of the computers processor to execute tasks simultaneously. This can be extremely hard to do with OOP because you run the risk of multiple threads of the processor attempting to concurrently access the same data. However, when you group like-minded data together and write code focusing on the data that is going to be processed in general, it becomes much easier to use multiple threads of the processor to process those functions.</p><p>Another benefit of DOP is efficient use of memory cacheing. Because DOP utilizes the same functions over and over again, the cache isn’t forced to keep storing more and more new-but-not-really-new blocks of instruction.</p><h4>Sources</h4><p><a href="https://www.danielsefton.com/2016/05/developing-a-data-oriented-game-engine-part-1/">https://www.danielsefton.com/2016/05/developing-a-data-oriented-game-engine-part-1/</a></p><p><a href="https://www.packtpub.com/books/content/what-difference-between-functional-and-object-oriented-programming">https://www.packtpub.com/books/content/what-difference-between-functional-and-object-oriented-programming</a></p><p><a href="https://www.gamasutra.com/view/news/126498/Opinion_What_You_Need_To_Give_Up_When_Going_Data_Oriented.php">https://www.gamasutra.com/view/news/126498/Opinion_What_You_Need_To_Give_Up_When_Going_Data_Oriented.php</a></p><p><a href="https://prateekvjoshi.com/2013/11/30/programming-paradigms-object-oriented-vs-data-oriented/">https://prateekvjoshi.com/2013/11/30/programming-paradigms-object-oriented-vs-data-oriented/</a></p><p><a href="http://gamesfromwithin.com/data-oriented-design">http://gamesfromwithin.com/data-oriented-design</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50ef35a99056" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[It’s All 1s and 0s: How Computers Map the Physical World]]></title>
            <link>https://medium.com/@jonathanmines/its-all-1s-and-0s-how-computers-map-the-physical-world-18a361fae3a5?source=rss-abab53e7b107------2</link>
            <guid isPermaLink="false">https://medium.com/p/18a361fae3a5</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[binary]]></category>
            <category><![CDATA[logic]]></category>
            <category><![CDATA[computers]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jonathan Mines]]></dc:creator>
            <pubDate>Thu, 01 Mar 2018 00:38:00 GMT</pubDate>
            <atom:updated>2018-03-05T01:04:46.454Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*uAp4K4IuVOaJp6v4B99KSQ.jpeg" /></figure><p>The number “12&quot; is not the value 12 in a carton of eggs. The word “rock” is not the rock you come across outside. Instead they are merely symbols, created from a collection of other symbols, that represent specific concepts that map well to the world around us. They are tools that give us the ability to break down the world, a mass of matter, into manageable chunks. We use them, not because they are objectively “true”, but because they are useful in meeting our goals given a set of physical restrictions.</p><p>In essence, computers use of binary is no more complicated than that. Just another man-made system created to achieve some goal with a certain set of restrictions in mind.</p><h3><strong>The World According to Denary</strong></h3><p>Before thinking about how computers use the binary system, it’s helpful to think about why we use the denary system. Our goal is to be able to represent numerical values and communicate those value to others. We can imagine a system in which we had a new character for every number imaginable. For example, 156 would actually be a type of squiggly line with a hook on top, not to be confused with the symbol for 38, which would be represented by a circle with a line across the top. That would be the most efficient way of representing values as you would only ever need one character at a time to represent even the biggest numbers, instead of a chain of characters. But it wouldn’t be the most practical. Imagine a 1st Grade teacher testing her students on the difference between the character representing 1,589 and the character representing 2,000,478 and all the characters in between.</p><p>Clearly, there’s a limit to how many characters we want to have availible in our system of representation. So what about the opposite end of the spectrum: a tally system with a single availible character? Sure, that’s possible — now show me 2,000,478 using a base-1 system. Clearly, this is also impractical.</p><p>Suddenly, the base-10 system makes sense as not the only availible numerical system, but a good fit given our need for practicality, elegance and efficiency. With only 10 availible characters I can represent the number 2,000,478 easily by multiplying the numerical value of that column by the next power of 10 as demonstrated below:</p><ul><li>2 x 10⁶= 2,000,000</li><li>0 x 10⁵= 0</li><li>0 x 10⁴= 0</li><li>0 x 10³= 0</li><li>4 x 10² = 400</li><li>7 x 10¹ = 70</li><li>8 x 10⁰ = 8</li></ul><p>SUM = 2,000,478</p><p>What a great system of representing values. So why don’t computers use that system?</p><h3><strong>From Denary to Binary</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*6rK4miScqh0HQ576Me6CHw.png" /></figure><p>Electrical currents are either running (open/on) or they’re not (closed/off) meaning we have two value characters availible to us: 1 and 0. Given those restrictions, we can use the same methodolgy we used to choose the base-10 system to find a system of representation that computers can use.With only two states availible to represent different characters the only other alternative to binary would be a tally system. But to represent the value 255 in a tally system we would need 255 digits. That’s 255 “on” transistors to represent a relatively small number. Binary only needs 8 to achieve the same goal.</p><p>Here’s how binary does that.</p><p>A base 2 system works similarly to the base-10 system but instead of multiplying the value of each column by the next multiple of 2, they’re instead multipled by the next multiple of 2. For example, the binary number 10100 can be translated into a base 10 number by simply adding the calculated values below together:</p><ul><li>1 x 2⁴ = 16</li><li>0 x 2³ = 0</li><li>1 x 2² = 4</li><li>0 x 2¹ = 0</li><li>0 x 2⁰ = 0</li></ul><h3><strong>From Bits to Bytes</strong></h3><p>From here, we can start to build a convention for how to use this numerical system to map the world around us on electrical pulses of on and off. First, let’s give our characters a name: Binary digITs or Bits for short, the smallest unit of data in a computer.</p><p>Next we’ll determine how many bits it will take to represent a non-numerical value, like a letter or special character. This process is as contrived as the process of picking a numerical system to represent value. We have certain goals, certain pre-established tools, and a general desire for elegance and efficiency. There are 101 characters on a keyboard, meaning we’ll need to represent 101 in binary as the max value. Turns out 101 in base-10 is the number 01100101 in binary. That’s a baseline requirement of 7 availible transistors if we want to map each key to a specific numerical value. But what if there are other characters we want to represent? With 7, all on, we only represent up to the number 127 in base-10. May as well give us one more bit to work with.</p><p>And thus, we have bytes, the baseline unit for measuring data, said to represent at a minimum, a single character. We can now represent the values from 0–255 (00000000–11111111).</p><p>As computers can only understand numbers, the American Standard Code for Information Interchange (ASCII) was established to assign each character on the keyboard a specific numerical value as depicted below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*SskvQ8WxIFIcYGvlsSL8NQ.png" /></figure><p>As an example, here’s how you would represent the phrase “Hello World!” in binary:</p><ul><li><strong>Text: </strong>Hello World!</li><li><strong>ASCII Numbers:</strong> 072 101 108 108 111 032 087 111 114 108 100 033</li><li><strong>Binary: </strong>00110000 00110111 00110010 00100000 00110001 00110000 00110001 00100000 00110001 00110000 00111000 00100000 00110001 00110000 00111000 00100000 00110001 00110001 00110001 00100000 00110000 00110011 00110010 00100000 00110000 00111000 00110111 00100000 00110001 00110001 00110001 00100000 00110001 00110001 00110100 00100000 00110001 00110000 00111000 00100000 00110001 00110000 00110000 00100000 00110000 00110011 00110011</li></ul><p>Like text, images also need to be converted into binary. We can represent images in binary by splitting an image up into a grid of pixels and breaking down each pixels color into a combination of 3 colors (red, green, and blue), typically referred to as that pixels RGB value. The max value each of those colors can have individually is 255 and the minimum is 0, meaning, each colors value for each pixel can be represented by 1 byte for a total of 3 bytes per pixel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*jAwgilaT5R95uCY6V80zgw.png" /></figure><p>As an example, we can represent the shade of the green pixel shown above at location (1,0) in RGB and binary below:</p><ul><li><strong>RGB Values:</strong> (6, 250, 7)</li><li><strong>Binary:</strong> 00000110, 11111010, 00000111</li></ul><p>Lastly, we can represent sound data in binary as well using “sampling”. By graphing the sound waves of a recorded sound and noting the values of the waves heights at regular intervals we can then convert those values to binary and then recreate that sound wave using those binary values at a later time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*iS9pkFhfJ7zBnsBKrLiKcg.png" /></figure><p>For example, the sound wave above has a decimal value of 8 at the time interval 1, giving it a byte value of 00001000.</p><h3>From Binary to Logic</h3><p>There are many different ways to store binary data including punched cards, magnetized tape, optical discs, etc. All use this convention of representing values in a base-2 system. However, representing the world in binary is only half the battle. The other half is operating on it. Enter bitwise operators.</p><p>Bitwise operators operate on individual bits and are the fundamental arithmetic operations that a CPU uses. Each bitwise operator has a set of predetermined rules that produce a certain output given two inputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*JJtdgUzLjOfNjrdMuv8M2g.png" /><figcaption>Bitwise operators and their corresponding outputs</figcaption></figure><p>You may recognize these tools as ones that are part of a system we’ve been using long before electricity was even discovered: logic. While a bitwise operator may seem foreign, they’re derived from logical operators and like numerical systems we use logical operators as bitwise operators because they serve our purposes efficiently and elegantly given our current physical constraints.</p><p>Our goal is to take two different values represented by two possible characters produce a new value according to a set of deterministic rules. You can see how our system of propositional logic translates well into computational logic below:</p><p>Think about the AND operator in the context of this sentence: “Bob ate lunch and Bob went to the movies.” If the first statement is true and the second statement is false, then the sentence is false.</p><p>T &amp; F = F</p><p>But if the first statement is true and the second statement is true then the statement is true.</p><p>T &amp; T = T</p><p>What about the OR operator: “Bob ate lunch or Bob went to the movies”. If the first statement is true and the second statement is false, the sentence is still true.</p><p>T v F = T</p><p>But if both are false then the sentence is false.</p><p>F v F = F</p><p>Now replace the T’s and F’s with 1’s and 0’s and we have the building blocks for manipulating binary to create new strings of binary and therefore new representations of values. We use these bitwise operators in logic gates, electronic switches that use this logic to produce new values. Picture the following scenario:</p><p>You need to light up the bottom right LED in a calculator to begin displaying the numbers 0, 1, 3, 4, 5, 6, 7, 8, and 9 but not the number 2. That means the binary numbers 00, 01, 100, 101 110, 111, and 1001 but not 10 need to produce a single ON signal (1). To turn those electric signals into a single ON signal for that LED we can chain 3 OR logic gates and a NOT logic gate together to ensure that those values result in either a 1 or a 0. Below, you can see an example of the number 7 represented in binary (1110) resulting in a single ON signal, which results in the bottom right LED lighting up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*gtbHnKYV2SrbDv7ofXXIlQ.gif" /></figure><h3><strong>Quantum Computing</strong></h3><p>The only exception to this rule of representing the world in 1’s and 0’s in computers lies in Quantum computing.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FEak_ogYMprk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DEak_ogYMprk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FEak_ogYMprk%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/6b04986da4eac90f313b262592359424/href">https://medium.com/media/6b04986da4eac90f313b262592359424/href</a></iframe><p>Quantum computing attempts to use the “spooky” nature of sub-atomic particles to represent represent data. Photons, for example, have been shown to exhibit seemingly contradictory behavior, representing multiple states at once. The multi-state behavior gives us extra values to play with besides the typical on/off that we generally get with electric signals. Instead of using a bit to store data, quantum computers use qubits, which can be either a 1 or 0 or both at the same time.</p><p><a href="https://www.bbc.co.uk/education/guides/zwsbwmn/revision">https://www.bbc.co.uk/education/guides/zwsbwmn/revision</a></p><p><a href="http://introcomputing.org/">http://introcomputing.org/</a></p><p><a href="https://www.bbc.co.uk/education/guides/zwsbwmn/revision">https://www.bbc.co.uk/education/guides/zwsbwmn/revision</a></p><p><a href="https://www.bbc.co.uk/education/guides/zpfdwmn/revision/2">https://www.bbc.co.uk/education/guides/zpfdwmn/revision/2</a></p><p><a href="https://web.stanford.edu/class/cs101/bits-bytes.html">https://web.stanford.edu/class/cs101/bits-bytes.html</a></p><p><a href="http://www.explainthatstuff.com/how-computer-memory-works.html">http://www.explainthatstuff.com/how-computer-memory-works.html</a></p><p><a href="http://nookkin.com/articles/computer-science/why-computers-use-binary.ndoc">Why Computers Use Binary</a></p><p><a href="http://www.explainthatstuff.com/logicgates.html">http://www.explainthatstuff.com/logicgates.html</a></p><ul><li><a href="http://www.asciitable.com/">Ascii Table - ASCII character codes and html, octal, hex and decimal chart conversion</a></li><li><a href="https://plus.maths.org/content/how-does-quantum-commuting-work">How does quantum computing work? | plus.maths.org</a></li><li><a href="http://yosefk.com/blog/efficiency-is-fundamentally-at-odds-with-elegance.html">Efficiency is fundamentally at odds with elegance</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18a361fae3a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I, Twitter Bot]]></title>
            <link>https://medium.com/@jonathanmines/i-twitter-bot-85b17c305aeb?source=rss-abab53e7b107------2</link>
            <guid isPermaLink="false">https://medium.com/p/85b17c305aeb</guid>
            <category><![CDATA[bots]]></category>
            <dc:creator><![CDATA[Jonathan Mines]]></dc:creator>
            <pubDate>Tue, 06 Feb 2018 14:35:53 GMT</pubDate>
            <atom:updated>2018-02-06T14:38:42.889Z</atom:updated>
            <content:encoded><![CDATA[<p>How to make a twitter bot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0TTiNb7xW6WufzBgH1aNsg.jpeg" /></figure><p>Twitter bots are in right now. Twitter recently released a statement saying 1.4 million Americans interacted with Russian trolls during the 2016 Presidential Election. They’re increasingly being used to spread disinformation campaigns, push products, and give the impression that a particular view or support for legislation is more popular than it might otherwise seem.</p><p>For that reason, I wanted to look a little deeper into how bots work and wanted to deploy a bot of my own. As an exercise I wanted to create a bot that would listen for tweet mentions with its name and respond. To ensure coherence, I programmed my bot to listen for questions related to it being a bot and to respond saying it wasn’t.</p><p>To begin with, you’ll need a twitter account. This will be your bot. Navigate to Twitter’s Application Manager and sign in with your account. Then create a new app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wk1MW2jYq3iR2nzw8hOlKQ.png" /></figure><p>From there you’ll need to fill out the apps Name, Description and URL. Once on the application details page, click on the Keys and Access Token button to grab your Consumer Key and Consumer Secret Keys. Then scroll down to the bottom and “Create a New Access Token.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*p03KgCynAuaXrkhmTntoTQ.png" /></figure><p>Once you have those keys, you’re ready to start writing some Ruby. Open up your IDE and install the twitter gem:</p><p>$ gem install twitter</p><p>Next, you’ll need to enter in your consumer key, consumer secret key, access token, and access secret token like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*CW_vGiLQNHGfrSHzjUrwUQ.png" /></figure><p>You’re officially connected to Twitter. Using the client variable you just created, you can access a ton of twitter specific methods like update (“Tweet”), mentions (“Return all mentions for a specific user”), and friends (“Return all friends for a specific user”).</p><p>Here’s how I used some of these methods to create a bot that would respond to being accused of being a bot. First, say hello to, Bob:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*_7PK2ewEsGY62jcYFkO0gw.png" /></figure><p>When I run my program, Bob runs on a loop as long as the time is between 10AM and 10PM (to make him seem more human). He runs two main methods:</p><ol><li>He looks for mentions of him.</li><li>He analyzes and responds to those mentions.</li></ol><p>Here’s the run file Bob uses to boot up:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*DOhO0QSlw4Wqut6II5OZWw.png" /></figure><p>Because Bob is an instance of a User class that I created, I turned the client variable into a get method like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*z5od_VIAX08ulapIgPLgbg.png" /></figure><p>So if I wanted to have Bob connect with twitter I would run:</p><p>$ bob.get.(twitter_method_to_use)</p><p>Bob checks to see if he has a new mention of him by comparing the array returned by the bob.get.mentions is longer than the Mentions saved in Bob’s database. If there is an extra mention, the Mention class will save that mention and then pass it to the respond_to_mention argument where Bob can take a look at the text and respond accordingly.</p><p>At this point I realized how hard it would be to create a bot that could respond dynamically so I just had him look for two characteristics of the mention:</p><ol><li>That it was a question (looked for a “?” at the end of the string)</li><li>That it contained the word bot.</li></ol><p>That looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*g6K4r425GyJRwqz8NaQocQ.png" /></figure><p>If the string met those parameters, Bob pulled from an array of preset responses and randomly chose one to return and tweet. The tweet response is saved in the database with the mention it’s associated with to keep track of what was responded to and what wasn’t.</p><p>The result:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FBZUlLqD713Q%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DBZUlLqD713Q&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FBZUlLqD713Q%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbb79704f6f242bb2c51a602bd4a80c3/href">https://medium.com/media/cbb79704f6f242bb2c51a602bd4a80c3/href</a></iframe><p><strong>Things I’d Like to Revisit</strong></p><ol><li>Streaming Client: Twitter has a Streaming client which prevents you from having to make repeated calls to the API on a loop. However, the methods included in the streaming client are different from the REST client so I’ll have to investigate further to make this work.</li><li>I wanted to look more into the language capabilities of the bot. Can I make him respond to a greater variety of topics? Is there a way to make sure he responds appropriately? Are there patterns in English I could utilize?</li><li>I wanted to create a program that could host a number of bots. At the moment, Bob’s particular client authorization is embedded in the User class, but what if there were more than one client (like Suzy’s client?). I wanted to create specific user classes that inherited from the User class.</li></ol><p><strong>Sources</strong></p><p><a href="http://www.codebycodes.com/blog/2015/08/31/creating-a-simeple-twitter-bot-with-ruby">Creating a Simple Twitter Bot With Ruby</a></p><p><a href="https://techcrunch.com/2018/01/31/twitter-now-says-1-4-million-people-interacted-with-russian-trolls-during-2016-presidential-campaign/">https://techcrunch.com/2018/01/31/twitter-now-says-1-4-million-people-interacted-with-russian-trolls-during-2016-presidential-campaign/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85b17c305aeb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Solid with Solidity]]></title>
            <link>https://medium.com/@jonathanmines/getting-solid-with-solidity-22f5b1a58287?source=rss-abab53e7b107------2</link>
            <guid isPermaLink="false">https://medium.com/p/22f5b1a58287</guid>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Jonathan Mines]]></dc:creator>
            <pubDate>Tue, 23 Jan 2018 17:21:46 GMT</pubDate>
            <atom:updated>2018-01-23T17:21:46.105Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qoB9LCDY6DDwvurwwKmAdA.png" /></figure><p>With the huge fluctuations in the Cryptocurrency market it’s easy to lose the proverbial thread. <em>Bitcoin’s at $14,000?! That’s insane! Wait, what’s bitcoin again?</em> At the end of the day, there were very specific problems cryptocurrencies aimed to solve and very specific ways in which they aimed to solve them. I wanted to take a look at one, in particular: Ethereum, outline the problem it was trying to solve and take a brief look at the language, Solidity, it uses to try to solve those problems.</p><p><strong>The Problem</strong></p><p>The problem Ethereum aim’s to solve boils down to a problem of trust.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*eWfCkPnUSYTfjldLbTSYgQ.png" /></figure><p>Imagine a world where cab’s did not have meters. In this hypothetical world, each time you stepped into a cab and contracted their services you would have to trust that they were charging you a fair price based on the services you contracted. Going deeper than that, you would have to trust that they had formulated some fair system for charging you, taking into account the specific inputs of your ride (time, distance, etc.) and spitting out a fare consistent with those inputs. But with incomplete information you would have to blindly guess at which drivers were the fairest. You might end up relying on inconsistent or unfair patterns to help you discriminate and avoid getting burned (“I notice beat up cabs tend to charge me more than I think I should be charged so I’ll write off all beat up cabs”). That might lead to a world in which certain cabs are trusted less than other cabs through no fault of their own.</p><p><strong>The Solution</strong></p><p>In the world we currently live in we’ve solved this problem with cab meters. But wait, how do we know the cab meters are accurate? How do we know no one has tinkered with the meter to make it spit out an unfair reading?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*jNlG9dYrgOsfc6FZgESQVQ.png" /></figure><p>This is where Ethereum steps in. The reason a cab meter might still be unfair is because it’s controlled by one company that keeps the secrets behind how it’s meter works under lock and key. You still have to trust that that company isn’t ripping you off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*iMrjJOJFVKhqo3eLAaHR5g.png" /></figure><p>Conversely, the processes behind apps created and run on the Ethereum blockchain are running on everyones machines and can be verified for their validity. Here’s how it works:</p><p>Every decentralized app on the Ethereum blockchain is run on what is called an Ethereum Virtual Machine. Every change that takes place needs to be verified by every other node on the network, meaning the outcomes are entirely deterministic. This is in contrast to the way a typical app is run online in which any transactions are verified by only one entity (like PayPal).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*DD451gEY8faUwm_vBOK65g.png" /><figcaption>A map of all the current Ethereum Nodes.</figcaption></figure><p>These apps are written using a language called ‘Solidity’, which is used to write Smart Contracts. Smart Contracts function similarly to traditional contracts with one important difference: because they are coded they automatically fulfill the obligations explicitly outlined in the contract. Because a contract is essentially just a conditional, a smart contract evaluates the if clause and executes the code in the then clause if the condition is met. The store of value most often exchanged via smart contracts is the Ethereum coin.</p><p><strong>A Simple Solidity Program</strong></p><p>Here’s a breakdown of a simple election program written in Solidity. To start, we’re going to be coding a basic election with two candidates where authorized users can set the candidates and authorized voters can vote in the election. We’re going to be coding this contract in <a href="http://remix.ethereum.org/#optimize=false">Remix</a>, a web browser based IDE that allows you to tap into the functionality of the EVM, deploy, and run smart contracts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*95BlM1IYQWfvrOcPUAoTpA.png" /></figure><p>We start by defining an election contract using contract Election {} in which all of our code goes. We then define two struct’s: 1) aCandidate and 2) a Voter.</p><p>A Candidate is going to have a name, with a datatype of string, and a voteCount, with a datatype of uint.</p><p>A Voter is going to be able to hold a boolean of voted which will let us know if they’ve already voted. They’ll also have a voteIndex of uint and a weight of uint.</p><p>Lastly, we’ll define a constructor function of Election. Constructor functions are defined by mimicking the name of the contract itself. They run once and then never again meaning they can’t be called again within the contract. Our Election constructor function accepts an argument of a string for the election question (“Who would you like to vote for?”), a time limit (in minutes), and two candidates saved as strings (“Bob”, “Susy”, for example).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*fJJ5uVALI7zJFymm2tkVSg.png" /></figure><p>We then create an authorize function which accepts an address of voter. Essentially, the authorize function is what allows the owner to determine who will be allowed to vote.</p><p>Next we create a vote function which allows authorized users to vote and for their vote to be recorded. This accepts an argument of voteIndex, stored as integer. The voteIndex corresponds to the values inputed as candidates. For example, if the candidates are “x” and “y” they would correspond to indices of [0] and [1].</p><p>Lastly, we define the end function, which allows us to end the election. Note, the end function only allows us to end the election if it is past the given time limit. If the time limit is 10 minutes and we try to end the election at minute 7, the program will throw an error and will not allow any changes made to the data.</p><p>Now, we can try to run this program in the Remix compiler. We create our election by entering in the necessary arguments into the create field and pushing create.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E592-BNMFxTxALGUhm6cPA.png" /></figure><p>In our case, we’ll start an election asking the user to “Vote for one”, giving a time limit of 2 and offering 2 candidates: “x” and “y”. You can see that we’ve created the contract and the “input” or bytecode to be send to the various nodes has been generated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCuTN3_AHOu9rDUb1A4r7w.png" /></figure><p>You can also see the actual code that was changed and transmitted. As you can see, we have our election string message, two candidates of “x” and “y” and and 2 minute time limit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sorxKgePfIvziGA1rTAoew.png" /></figure><p>If we use one of the dummy accounts generated above we can authorize a voter. When we click “voters” we get a return value of “0: bool: voted false” indicating that this voter has not voted yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*VPAthEzeaN2RiqqxZRKPHQ.png" /></figure><p>When we enter “0” into the vote field and click vote and then paste in the account number from which we voted into the voters field and click voters, we see that the boolean value now evaluates to true and the weight has increased by 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*09reddtiDEUwqgGkYDV96A.png" /></figure><p>If we try to end the election before the time limit has expired we get an error code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*i09EkFkKloLfMzCaYtGw0w.png" /></figure><p>Once the 2 minutes is up, we can then end the election and the results are passed through:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u43ApyRk7BA5QUFI3HlhgQ.png" /></figure><p>As you can see, “x” received 1 vote and “y” received no votes.</p><p>What’s incredible about this system is there is no way to cheat this system. The results are what they are, no one can tinker with the algorithm or hack into it. This is just one example of how you can use Solidity to make useable programs that are safe from outside interference and guarantee fairness.</p><p><strong>Sources</strong></p><p><a href="https://ethereum.github.io/browser-solidity/#optimize=false&amp;version=soljson-v0.4.19+commit.c4cbbb05.js">https://ethereum.github.io/browser-solidity/#optimize=false&amp;version=soljson-v0.4.19+commit.c4cbbb05.js</a></p><p><a href="https://medium.com/@mvmurthy/ethereum-for-web-developers-890be23d1d0c">https://medium.com/@mvmurthy/ethereum-for-web-developers-890be23d1d0c</a></p><p><a href="https://medium.com/@mvmurthy/ethereum-for-web-developers-890be23d1d0c">https://medium.com/@mvmurthy/ethereum-for-web-developers-890be23d1d0c</a></p><ul><li><a href="https://medium.com/@mvmurthy/ethereum-for-web-developers-890be23d1d0c">Ethereum for web developers</a></li><li><a href="https://www.coindesk.com/information/how-ethereum-works/">How Ethereum Works - CoinDesk</a></li><li><a href="https://www.coindesk.com/information/what-is-ethereum/">What is Ethereum? - CoinDesk Guides</a></li><li><a href="https://blockgeeks.com/guides/solidity/">How To Learn Solidity: The Ultimate Ethereum Coding Guide</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22f5b1a58287" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>