Numpy Note

x.shape = (1, 2) or (1, )

x.size = total number of elements

np.empty([1, 2])

np.trace(X)

 

 

import scipy as sp

sp.optimize.minimize(func, x0, arg=() ) where x0 is the initial guess that specifies the soln’s dimension, arg is the tuple that contains extra argument to func

returns scipy.optimize.OptimizeResult

scipy.optimize.OptimizeResult.x is the soln, possibly multiple elements because the dimension might be greater than 1

sp.optimize.bisect

 

Two Sandwiches

There was this new homeless person outside of Walgreens, squatting on a broken old paint bucket and holding a sign that read “HELP! Hungary and jobless.”

As many others, I walked by without speaking. I went into Walgreens and lifted a sandwich off the shelf. I did something peculiar that day; I convinced myself that I was hungry and therefore required the nourishment of two sandwich.

I held with my left hand the one I liked more, and hid the other under my jacket. Why did I hide it? I was ashamed. But for what? Was I fearful of what others would think of me, when they see this futile act?

The pretext of hunger collapsed as I passed the homeless person. I casually asked, “Want a sandwich?”

He said sure and took it. I walked on to my classes. The whole encounter lasted 1 seconds.

Did I actually help?

A month ago I was outside of McDonald’s, and two homeless people approached me. I gave them my dinner. When they asked for money, I shook my head and said, “That I cannot do.” They disappointedly wandered away for some kinder souls.

This has always haunted me. Did I actually help? Would they have fared better had I minded my own business, allowing them to get on their own feet? Was I in the wrong?

I don’t’ have an answer. Yet, for now, I decided that I will help by not helping.

The Walgreens homeless person was there for the following months. I never once bought two sandwiches.

My Cooking Journey: Uncooperative Pancakes

I continued my journey to become a self sustaining college student by cooking. This time:

Pancake

Result: FAILED
Reason: Impatience. Hey pal I tried! I was too lazy to follow my bible and bought some pancake mix. But even that didn’t work. The mix’s instruction asked for a griddle. Who the hack would spend the money to buy a graddle!? So I merged the mix’s instruction with my bible’s instruction. It was a mess.

Rewind.

After I mixed all the ingredient into a giant lump of white, I turned on the heat to my non-stick pan. I didn’t know whether I should use butter or not. So I tried one without. The lump of white sizzled on the pancake and I was very optimistic.

Thus I cooked my first pancake. An one giant pancake on a 12-inch pan. I totally ignored the suggestion of adding no more than 1/4 cups. After all, the more the merrier, right?

In any case, when both sides turned brown, I put it in my plate and savored my first pancaky success. And… and it was tasty! The blueberries were awesome. It was great.

I told myself, “Hey it’s pancake. Of course it is easy.”

After that, I wanted a more watery texture, so I added more milk. My hand shook and I poured way way way too much. Back then I haven’t realized this mistake yet. Then I added butter just to test. In the interest of time, I added 4 times the white lumps. (Again, ignoring the warning of putting too much on the pan.)

This was where the failure came from. Disaster. Apocalypse. So watery were the pancakes that they failed to solidify. Gosh darn it, why wouldn’t you cooperate? You silly pancakes.

I ended up getting some random depressing cooked mix.

And two overcooked pancakes because I turned on the heat due to impatience.

What the ******* is this?

So depressed was I that I threw the rest of the ingredient away. Sorry.

Lesson learned: do not improvise please.

An Unexpected Adventure: Berkeley Rose Garden

Lately in an effort to not start the day without studying, I would meandered around the neighborhood in the morning. Without a destination. Wind was perhaps my only direction. Sometimes, I would find unexpected beauties in this busy hustling city of Berkeley.

I remembered I was jogging along Euclid Ave. 7am. The air fresh. The sun low. Streets were quiet, and the people scarce.

At first, the scenery was the familiar restaurants and tiny cramped college apartments. But the more north I went, the more interesting things got.

I knew of a horizontal street called Vine. Yet, this is a walk for pedestrians only. Its curvatures and flowers seemed to welcome me down the path.

I took the invitation and the walk greeted me with mossed staircase and over arching branches. When I reached the other side, I turned back because the only way to go back home was through Euclid.

Then I saw rose street.

Right then I didn’t grasp the subtle hints, nor what they were trying to tell of the beauty that lies ahead, until I saw it with my own eyes.

Berkeley Rose Garden. A circular download garden with pergola filled with myriad of roses. It was a project during the depression to increase employment.

I was never a plant or rose person. I was immensely curious when I saw the bizarre roses names: Gold celebration, American Beauty, etc. Especially striking was the King’s Ransom. A king? A ransom? For what?

It was winter. The rose garden had no blooming rose. Yet I allowed my imagination to soared.

Summer time.

Morning dew. Roses. Colors and energy.

I promised myself in May I would visit this place once again. I would find out the price of the king’s ransom.

At the heart of the garden lies a poem and a creek. I read it and pondered a bit.

California has always been in constant drought. Only the lowered side of the creek had flowing water.

I gazed down.

I saw my own reflection.

I reflected.

What a failure I was! I have lived in his city for more than a year and a half. Only now I found this wondrous place?

I reflected on the books the university had me read. They were supposed to enlighten me and broaden my view of this world. I now began to see that I was instead confined in a frame 7″ by 10″ held loosely by a spine.

There are many ways to learn; books are but one way.

React: Jest Unit Testing with redux-axios-middleware

Motivation and sad story: When I was a newbie in React and Redux, I was too lazy to figure out how to do unit testing. Every time I call the backend API, I would console log my API response. It was very very very… very slow. Evnetually, I took the courage to google it. But back then, there weren’t copy-and-paste-able solution, so I had to understand redux middleware, thunk, promise, etc—things that I should have known before I coded a single line of react. Hopefully this tutorial saves some poor soul some times in understanding and setting up the unit testing.

Overview

In order for this to work, you need the following:

  1. Setting up Jest, as detailed here. Note that if you used react-create-app, it is used by default
  2. Getting a mock store, which serves as our fake redux store
  3. Applying the axios middleware to the mock store
  4. Lastly, use the expect function to verify the success of the API call

Code and Explanation

import configureMockStore from 'redux-mock-store';
import axios from 'axios';
import expect from 'expect'
import axiosMiddleware from 'redux-axios-middleware';

const client = axios.create({
    baseURL: your_base_url_here,
    responseType: 'json'
});

let middlewares = [axiosMiddleware(client)];
const mockStore = configureMockStore(middlewares);
const store = mockStore();

test('Test if axios middleware successfully get a response from the api', () => {
    const expectedAction = { type: YOUR_ACTION_TYPE + '_SUCCESS'};
    return store.dispatch(YOUR_ACTION_CREATOR()).then(() => {
        expect(
            store.getActions().find(a => a.type === expectedAction.type)
        ).toBeDefined();
    });
});

We first set up the mock store and the middleware. Middlewares are essentially things that users can interject between an action and a reducer to do extra work. (A deeper understanding of middlewares can be found at here). In axios’ case, we perform an api call.

We first define the api url:


const client = axios.create({
    baseURL: your_base_url_here,
    responseType: 'json'
});

We then apply the middlewares. Unlike the actual redux store, we simply put all the middlewares we want in an array and pass the array to configureMockStore. Every time we want a fresh new store, we call mockStore()


const middlewares = [axiosMiddleware(client)];
const mockStore = configureMockStore(middlewares);
const store = mockStore();

We define the test case. This is just the general Jest test case:


test('Test if axios middleware successfully get a response from the api', () => {

    ...

});

In summary, if your action contains a request property, axios middleware will call the api in that url. And if the call is successful, it will create another action with type suffixed with “_SUCCESS”. Therefore, we verify the call is successful by checking that suffixed action type was ever recorded in the store.


const expectedAction = { type: YOUR_ACTION_TYPE + '_SUCCESS'};
return store.dispatch(YOUR_ACTION_CREATOR()).then(() => {
    expect(
        store.getActions().find(a => a.type === expectedAction.type)
    ).toBeDefined();
});

More in depth: when the store dispatch your action (aka the store takes in your action and tells every reducer that such an action has occurred), axios middleware call the api and eventually returns a Promise (more on Promise here).


store.dispatch(YOUR_ACTION_CREATOR()) // This is a Promise Object

If we use the then function on Promise, we ensure the testing logic happens after the original action and the succeeded (or failed) action have taken place.


.then(() => {
    ...
}

Then we ask the mock store all the action types that it ever recorded, and we check if the success suffix was one of them.


expect(
    store.getActions().find(a => a.type === expectedAction.type)
).toBeDefined();

That’s it! Putting the pieces and understanding how each part works do take some time, but the actual code is short. The beauty of React!