in elixir

While I haven't written about it here yet, much of my past year has been spent learning and writing Elixir.

As I have started to delve beyond surface-level language features I have found topics that are not discussed to my satisfaction (or at least in words that I think make sense) so I am determined to document my adventures here.

One such feature I recently started using that fit this bill is the macro. A macro in Elixir is a feature that essentially enables a sort of metaprogramming. For example, say you have several modules that all do the same things essentially, but in a different context - like notifications.

You might have MyApp.SMS, MyApp.Email and so on, where each module has common functions that they need. One option would be to write each module with all the functions it needs. Another would be to extract it to another module. But what if you could utilize the design approach of separating things into modules, without extracting and also without repeating yourself? Enter macros!

Here are some example code snippets without macros:

defmodule MyApp.SMS do

    def send(target, body) do
        # Your logic
    end
    
    def create_body(body) do
        # Shared function
    end
end 
defmodule MyApp.Email do
    def send(target, body) do
      # Your logic  
    end
    
    def create_body(body) do
        # Shared function 
    end
end

In this example imagine that create_body/1 does something that both modules will need. Perhaps it will take a body string and replace certain characters, sanitize it, or something along those lines. You could write it each time like I did above, or maybe even move it to a common module, but with macros you could bake in this behavior using using.

defmodule MyApp.NotificationFramework do
    def __using__(_opts) do
        defmacro do
            def create_body(body) do
                # Shared function
            end
        end
    end
end

With this macro created, we can now use it in one of the modules above:

defmdoule MyApp.Email do
    use MyApp.NotificationFramework
    
    def send(target, body) do
        # Your logic
    end 
end

use differs from import or require in that it essentially allows the module you are useing to arbitrarily insert things into the context that used it. In this case, that means that it is inserting the macroed create_body/1 function. At run time, the module as written above is essentially the same as the one with the use clause.

Here is what the module really looks like after the use:

defmodule MyApp.Email do
    def send(target, body) do
      # Your logic  
    end
    
    def create_body(body) do
        # Shared function 
    end
end

This can essentially create modules that are similar with the exception of maybe one or two functions that must be implemented differently, but should be self contained for design reasons (like ease of reading, or something similar).

Note there are some caveats around when the things in the macro are inserted into the context where use is called - in general the macro is compiled late so it will not overwrite things defined in the module directly. There are also some considerations around declaring variables - I recommend referencing the official documentation if this is an area you want to know more about.

There are other uses for macros that I have not yet explored, but I will certainly write more about them as I learn more.

in project, docuie, documentation

social_media_blue_bg

Over the past 6 or so months I have been working on a new project. It started as a way to dive into Elixir and the Phoenix framework but ended up being (in my opinion) a fully fledged product.

The idea was to provide a hosted documentation service that was simple, affordable and easy to use. During my work on Statusy, I spent a great deal of time trying to find a decent product that 1) didn't cost a ton of money (a lot of options were easily $50+ a month for essentially a static site), 2) didn't require a ton of setup and 3) was mostly hands off. I couldn't find such a product, so I began working on Docuie.

Docuie allows you to create documentation projects as well as pages and headings to create a hierarchy for your users. It has a WYSIWYG editor, supporting both point-and-click style writing and full HTML editing if you wish to take that route. Docuie supports free docuie.com domains in addition to custom domains on the higher packages. Pricing is based around the features and number of seats you need, the cheapest plan starts at just $10 per month and gives you a fully featured product.

In addition, one thing we did with Statusy that I really enjoyed was offering free service to open source projects, so I will be continuing this with Docuie. If you run an open source project (or a charity of some sort) please reach out to me if you are interested in getting set up on Docuie.

You can view an example of the product through Docuie's own documentation site here: https://docs.docuie.com

Thanks for reading, I hope you will give it a shot if you are in the market for a documentation service.

While a number of other payment processors have sprung up in recent years, Paypal continues to remain one of the de facto standards because of its relative prevalence and its ability to tokenize personal information. Many users have come to prefer Paypal for websites and services that may not have yet been fully vetted and would thus prefer to not hand over personal information, like credit card numbers, directly.

That said, integrating with Paypal is almost always a great business move as it will aid in capturing as many customers as possible for your web service or platform.

This post will walk you through a basic integration for Paypal with recurring billing. Paypal's latest REST API will be used in combination with Paypal-Checkout.

Terms

Before diving in, it is worth explaining a few terms that Paypal uses often when it comes to recurring billing:

  1. Agreement - An agreement is essentially a subscription, that is, a recurring payment that happens based on a predetermined schedule.

  2. Billing Plan - A billing plan provides the basic information to create an agreement. Things like cost, term and taxes are defined on a billing plan.

Integrating Checkout.js

To begin, Paypal-Checkout (checkout.js) will need to be included on the web page(s) where you would like to offer support for Paypal subscriptions.

This can be done by adding the following script to the scripts area of your web page:

<script src="https://www.paypalobjects.com/api/checkout.js" data-version-4></script>

Next, you will want add a <div> where the Paypal button should be shown:

<div class="paypal-button"></div>

Lastly, some Javascript code will be required to instantiate the button and remaining functions. You can add the following directly to a web page, or you can add the Javascript to a separate js file and include that in your web page.

paypal.Button.render({

    env: 'sandbox', // Or 'production',
    commit: true, // Show a 'Pay Now' button
    client: {
        'sandbox': 'YOUR CLIENT ID HERE', // switch to 'production' if in prod
    }

    payment: function(data, actions) {
        /* 
         * Set up the payment here 
         */
         
         // The goal here is to return a promise or callback that
         returns a payment ID
    },

    onAuthorize: function(data, actions) {
        /* 
         * Execute the payment here 
         */
         
         // Once the user has authorized the subscription, you will
         need to execute the agreement here.
    },
}, '#paypal-button');

If you reload your page you should now see a button similar to what is shown below:

Paypal Button

Creating Plans

Next you will need to create a plan to offer to your customers. Currently Paypal does not offer a web interace to do this, so plans must be configured via the REST API. That said, the best source for examples here would be the Paypal API documentation directly, found here.

Creating an Agreement

With plans created you can now begin the process of creating your first agreement. Paypal-Checkout does not offer direct support for billing agreements so you will need to manually handle this information server side.

First, write the server endpoint - in this example Python, the Flask framework and the Paypal Python SDK will be used (pip install paypalrestsdk - docs here) will be utilized:

# import standard flask modules
from urllib.prase import urlparse, parse_qs

@billing.route('/billing/paypal/agreement/token', methods=['POST'])
def get_agreement_token():
    plan_id = json.get('plan_id') // Get the plan ID from the request
    
    agreement = paypalrestsdk.BillingAgreement({})
    
    if agreement.create():
        parsed_url = urlparse(agreement.links[0]['href'])
        return jsonify({ 'token': parse_qs(parsed_url.query)['token'][0]})
    
    return jsonify({ 'error': 'failed'})

The goal with this endpoint is to take the plan ID selected by your customer and use it to retrieve a payment token. The token is retrieved on this line: parsed_url = urlparse(agreement.links[0]['href']) and then returned as a JSON object here: return jsonify({ 'token': parse_qs(parsed_url.query)['token'][0]}).

Back on the Javascript side, you can write an AJAX call to this endpoint like so:

paypal.Button.render({

    env: 'sandbox', // Or 'production',
    commit: true, // Show a 'Pay Now' button
    client: {
        'sandbox': 'YOUR CLIENT ID HERE', // switch to 'production' if in prod
    }

    payment: function(data, actions) {
        var plan_id = '1'; // change this to be the actual paypal plan ID
        
        $.ajax({
          url: '/billing/paypal/agreement/token',
          type: 'POST',
          data: JSON.stringify({ plan_id: plan_id }),
          contentType: 'application/json',
          dataType: 'json',
          success: function(data, status, xhr) {
            agreement_id = data.agreement_id;
            resolve(data.token); // resolve the promise so onAuthorize is called
          },
          error: function(xhr, status, error) {
            console.log('checkout error', error);
            reject(error)
          },
});        
    },

    onAuthorize: function(data, actions) {
        /* 
         * Execute the payment here 
         */
         
         // Once the user has authorized the subscription, you will
         need to execute the agreement here.
    },
}, '#paypal-button');

Once the payment token is returned in resolve the user is prompted to accept the agreement you have created. Once this has been done, the onAuthorize handler is called and you will need to execute the agreement for it to complete.

Executing the Agreement

To execute the agreement a separate server side endpoint will need to be created. Here is an example:

@billing.route('/billing/paypal/agreement/execute', methods=['POST'])
def execute_agreement():
    payment_token = json.get('payment_token')
    
    if paypalrestsdk.BillingAgreement.execute(payment_token):
        return jsonify({ 'status': 'success' }) // we're good to go!
        
    return jsonify({ 'error': 'failed' }) // something broke!

This endpoint does not need to return anything in particular, so long as the response code is 200. The payment_token is obtained in the JSON body POSTed to this endpoint, it is then supplied to the Paypal Python SDK and the execute function is called with that parameter. If all is well, the status: success line is returned, else an error is returned.

To integrate this on the Javascript side, another AJAX call will need to be made:


    env: 'sandbox', // Or 'production',
    commit: true, // Show a 'Pay Now' button
    client: {
        'sandbox': 'YOUR CLIENT ID HERE', // switch to 'production' if in prod
    }

    payment: function(data, actions) {
        var plan_id = '1'; // change this to be the actual paypal plan ID
        
        $.ajax({
          url: '/billing/paypal/agreement/token',
          type: 'POST',
          data: JSON.stringify({ plan_id: plan_id }),
          contentType: 'application/json',
          dataType: 'json',
          success: function(data, status, xhr) {
            agreement_id = data.agreement_id;
            resolve(data.token); // resolve the promise so onAuthorize is called
          },
          error: function(xhr, status, error) {
            console.log('checkout error', error);
            reject(error)
          },
});        
    },

    onAuthorize: function(data, actions) {
         $.ajax({
          url: '/billing/paypal/agreement/execute',
          type: 'POST',
          data: JSON.stringify(
            {
              payment_token: payment_token,
            }
          ),
          contentType: 'application/json',
          dataType: 'json',
          success: function(data) {
            // success!
          },
          error: function(xhr, status, error) {
            // failure! 
          },
    },
}, '#paypal-button');

If all is well, the success handler will be called and you can then direct the user to the appropriate page, do further requests or obtain additional information if necessary.

Conclusion

At this point you should have a very basic Paypal integration with support for recurring payments. Please note, the endpoints shown in Python are written under the assumption you have a working Flask application, to do that you will need to import additional modules not explicitly shown above. However, regardless of backend, the flow would be the same:

  1. User clicks Paypal button
  2. Fire request to server to get a payment token
  3. User accepts agreement
  4. Fire another request to server to execute it with the agreement token
  5. success or error is called, redirect appropriately

I hope this has been a helpful look at creating a basic Paypal subscription integration. Please do not hesitate to let me know if you have any questions, thanks!

Introduction

One of my all time favorite topics is the brain, but more specifically, how the brain's operation results in the human condition. Recently I have been reading about the dichotomy between the conscious and unconscious mind.

The most interesting of which, I think, is a study conducted at the University of Tennesee that investigates the timing of the decision making process while observing brain activity in an fMRI machine (an imaging device that allows researchers to view brain activity in real time) [1].

Research

During the study, researchers placed subjects in an fMRI machine and prompted them to decide to press a button in their left or right hand. Simulatenously, the subject is shown a clock with a rapidly moving second hand. Subjects are asked to identify which number the hand is closest to when they make the decision to press one button or the other. Comparing the data, researchers identified a roughly 200-300ms delay between when the subject reported making the decision and when they actually pressed the button. More interestingly, though, is that the fMRI scanner showed activity in the area of the motor cortex (the part of the brain that drives our movements) 300-500ms before the subjects reported making their decision.

This effect was so prevalent, researchers found they could readily and consistently predict how the subject would react before the subject reported making a decision.

In a separate but related study at Harvard University, Alvaro Pascual-Leone went on to modify the experiment to utilize TMS (transcranial magnetic stimulation, a way to manually stimulate the brain). In the follow up experiment, subjects were asked to think about moving one hand or the other during a specific auditory cue. Following a random pause, a second distinct auditory cue signaled that they should actually move the hand they decided to move. During some tests, researchers determined the hand that the subject intended to move using real time brain imaging and, prior to the second auditory cue, delivered a shock to the subject's motor cortex that would result in the opposite hand moving. When this happened, the subjects were questioned about the change in behavior with researchers noting that the subject's brain activity suggested that they would move their other hand. Consistently the subjects seemingly made up an explanation, stating they changed their minds, or something similar. But, given the brain imaging, it is possible to discerne with reasonable accuracy that this was not the case, and rather, the conscious brain simply tried to rationalize why the decision it made (to move the left hand, for example) did not happen. Moreso, subjects reported feeling completely normal, as if making a decision to move one hand and having the other move instead was normal.

These findings seem to suggest that this is a completely normal state for the brain. That is, that the conscious mind is not the portion of the brain that actually results in decision making.

fMRI scans during these experiments showed the activation of various regions of the brain, showing that the motor cortex was stimulated 300-500ms before the subject reported making a decision, suggesting the decision was made elsewhere in the brain and that the conscious mind, seemingly, was one of the last to know.

Foreward

From here, I wanted to take some time to expand upon the findings above, but before that I would like to note I am aware the objective of the studies above was to determine brain functionality and not to attempt to support or reject the concept of free will. However, I do believe that these findings can be used for further extrapolation in the discussion of free will.

Concept

What would it mean if the findings of these studies actually meant that free will was an illusion at best? We tend to operate under the assumption that our conscious minds are making the decisions we eventually act out, but it seems that the conscious mind is just along for the ride while doing its best to make sense of our actions.

If this is true, it would imply that what we typically consider to be free will simply does not exist. How then do we ultimately formulate our relatively complex actions then? I would like to assert that the brain operates deterministically. That is, given a specific brain state and a set of stimuli, the brain will always product the same output, similar to a computer program.

Discussion

With a deterministic brain we can be expected to react the same way every time a set of criteria are met. If I were to poke your arm right now, the reaction you would have is the same reaction you would have if we replicated the poke with the exact same brain and the exact same stimuli. That said, it is worth noting that it would be neigh impossible for the physical state of the brain to be the same since brain plasticity (the tendency for the brain to physically change based on actions and memory) has been well documented [2]. But, if you took your brain as it is right now, placed it in a vat and gave it all the stimuli you are currently experiencing, along with my poke, you would likely react the same way you did originally.

To further expand upon this idea - with a brain operating in a deterministic way, every action we take is literally the only action we will ever take because, given a certain state and a certain set of stimuli we will always act the same way.

If this is the case, then regardless of how much you want to think you wouldn't do X or Y, it is ultimately the state of your brain that decides what you will actually do.

Conclusion

If we were to agree that the idea the brain operates in a deterministic way is correct, what would that mean for the idea of free will? Researchers have demonstrated it is not the conscious mind that is first made of aware of decisions, rather, it is looped in on a need to know basis and allowed to make its own narrative. Think about this the next time you take a seemingly random action - why did you do that? Take some time to ponder the reason your conscious mind provides you - does it actually make sense?

Furthermore, consider what this means in terms of law and order. When we punish a criminal for committing a crime, are we punishing the conscious mind or the unconscious mind that likely decided to take the criminal action in the first place? Is this ethical if the brain is truly deterministic, if so, the criminal was incapable of acting in any other way.

What else would be impacted if we were to determine with certainly that our brains operate in a deterministic way?

[1] https://www.nature.com/news/2008/080411/full/news.2008.751.html

[2] https://www.psychologytoday.com/blog/the-athletes-way/201702/how-do-neuroplasticity-and-neurogenesis-rewire-your-brain

I have been fortunate in that I made it through 26 years of life before I lost somebody very close to me. This streak ended yesterday, May 23rd, 2017 when my grandmother passed in her sleep. Death is not something I had spent a great deal of time pondering before now, but sitting here in the aftermath of it all, I have had a great deal of time to think it through.

I think we all realize that death is the unfortunate end we are all moving towards. It is an inevitability, a when and how, not an if. In my experience, most deal with death by way of religion. Many major religions have a concept of a heaven or heaven equivalent, with this, it is easy to find comfort knowing your loved one is in a better place. I have no gripes with this, in fact I have found myself finding comfort through similar ideas since learning of my grandmother’s passing. However, I ultimately identify as an agnostic or atheist depending on the exact context. That said, I have been spending time trying to reconcile my beliefs with my need for comfort in such a difficult time.

In doing this, I read similar anecdotes by other atheists and one in particular caught my eye and truly resonated with me.

While I highly recommend giving the original article a read, the author is posed with a question by friend whose father had passed recently. The friend asks how the author deals with death given he is an atheist. The author discusses this in the form of a letter, during it he highlights this passage by Aaron Freeman:

You want a physicist to speak at your funeral. You want the physicist to talk to your grieving family about the conservation of energy, so they will understand that your energy has not died. You want the physicist to remind your sobbing mother about the first law of thermodynamics; that no energy gets created in the universe, and none is destroyed. You want your mother to know that all your energy, every vibration, every Btu of heat, every wave of every particle that was her beloved child remains with her in this world. You want the physicist to tell your weeping father that amid energies of the cosmos, you gave as good as you got.

And at one point you'd hope that the physicist would step down from the pulpit and walk to your brokenhearted spouse there in the pew and tell him that all the photons that ever bounced off your face, all the particles whose paths were interrupted by your smile, by the touch of your hair, hundreds of trillions of particles, have raced off like children, their ways forever changed by you. And as your widow rocks in the arms of a loving family, may the physicist let her know that all the photons that bounced from you were gathered in the particle detectors that are her eyes, that those photons created within her constellations of electromagnetically charged neurons whose energy will go on forever.

And the physicist will remind the congregation of how much of all our energy is given off as heat. There may be a few fanning themselves with their programs as he says it. And he will tell them that the warmth that flowed through you in life is still here, still part of all that we are, even as we who mourn continue the heat of our own lives.

And you'll want the physicist to explain to those who loved you that they need not have faith; indeed, they should not have faith. Let them know that they can measure, that scientists have measured precisely the conservation of energy and found it accurate, verifiable and consistent across space and time. You can hope your family will examine the evidence and satisfy themselves that the science is sound and that they'll be comforted to know your energy's still around. According to the law of the conservation of energy, not a bit of you is gone; you're just less orderly. Amen.

Having never read (or heard) this quote, I was very moved by it. I found it particularly interesting that the ideas conveyed in the passage so easily mirror those that the religious among us rely on during difficult times. When it is broken down, what we truly want to know is that our loved ones mattered, that their existence changed something in the world irrevocably, and through that change they live on.

While I am ultimately not sure if there is a heaven or hell, I do know that my grandmother lived a long, passionate and fulfilling life. She had two children, my mother and my uncle, both went on to have children of their own. My grandmother’s actions have profoundly changed the world, as a nurse she cared for the sick, as a mother she brought new life into this world, and as a grandmother she helped raise the future generations of our family. Her energy and passion live on in her children, her grand-children, and eventually my children, their children and so on.

I am comforted by the fact that, while yes, my grandmother is no longer with us, that her life had meaning. This meaning is not something that will ever die, it lives on in all of us, and in a way, my grandmother lives on too.