Testing out React-Native Deeplinks…

Testing out React-Native deeplinks… http://www.rnn.com/deeplink

 

[SOLVED] How the Hell to Install psycopg2 on Mac?

Woah ho ho! Welcome back dear internet friend. This blog is sure to be short, but will pack a punch! If you are having a hard time installing psycopg2 on your Mac using pip and are a bit intimidated by all the talk about PATHs and requisite dependencies et cetera et cetera… fret not! All you need is this little one liner:

$ pip3 install psycopg2-binary

That’s right, all you need to do is install psycopg2-binary INSTEAD of psycopg2 and everything will be easy peasy.

 

Painfully Slow UPDATEs and DELETEs when using Python, MySQL, and Oracle’s mysql.connector Library

For the past week I’ve been banging my head against the wall trying to figure out why my MySQL database is so slow performing UPDATEs and DELETEs. Single UPDATE or DELETE statements aren’t so bad, but whenever I try to delete many entries, say 30,000 or so rows, things just grind to a halt!

Well this is what I’ve figured out: Oracle’s mysql.connector library for Python is extremely slow at doing UPDATEs and DELETES. While mysql.connector handles SELECT statements just fine, and can perform INSERTs blazing fast as well when using the executemany() method, the library is just awful at doing bulk UPDATEs and DELETEs.

It kind of makes sense that this might be the case, as MySQL has long been associated with PHP. PHP and MySQL are like peanut butter and jelly. Likewise, when you think about Node.js, MongoDB seems to be the preferred database of choice for backend JavaScript programming. Python and MySQL? That combo just doesn’t seem to go well together from what I have found.

Personally, I’ve decided that the best solution for my needs is to simply move my data from MySQL over to a new PostgreSQL database, not because MySQL is slow, but because I know that PostgreSQL has an excellent Python library: psycopg2

If you happen to find yourself in a similar situation, struggling to get MySQL to play nicely with Python, I suggest you dump the dolphin and unleash the Psycho Pig!

UPDATE (January 3rd, 2020… 1 Day Later): After finishing moving all of my data over from MySQL to PostgreSQL, I found that using Python + PostgreSQL + psycopg2 has completely eliminated my problem with painfully slow UPDATEs and DELETEs. If you find yourself running into a similar problem with Python, MySQL, and mysql.connector, I highly recommend switching over to Python/PostgreSQL/psycopg2. However, you need to make sure that you are using psychopg2’s execute_batch() method in order to see these performance gains. Again, make sure to use psycopg2’s execute_batch() method when doing BULK UPDATEs, DELETEs, or INSERTs.

 

Android onClick Listener: A Short How-To Guide

Good ole’ Java, gotta love all the boilerplate! Am I right? Okay, so as we all know there’s a lot of boilerplate and verbosity involved in writing Java/Android code, so I just wanted to create this quick blog post demonstrating how to setup an OnClickListener to listen for and respond to button clicks in Android. Unfortunately the Android documentation doesn’t include a lot of code snippets so sometimes references like this are necessary. So without further ado, here is an XML layout file and an Android Activity written in Java demonstrating how to listen for onClick events in Android:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/my_button"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="CLICK ME" />
</LinearLayout>
package blog.topherpedersen.uselesscameraapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button myButton = findViewById(R.id.my_button);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Button Clicked!", Toast.LENGTH_LONG).show();
}
});
}
}
 

unresolved reference activity_main

Writing this blog post today because a lot of the blog posts regarding this error message are out of date. If you happen to be getting started on a brand new Android Studio project using Kotlin, and you run into the error message “unresolved reference activity_main,” here’s the problem: your blank activity is probably importing android.R instead of import kotlinx.android.synthetic.main.activity_main.* in your MainActivity.kt file. So here is all you need to do…

First, delete the following line of code:

import android.R

And replace it with this line of code:

import kotlinx.android.synthetic.main.activity_main.*

And that’s all there is to it! Happy coding 🙂

 

Getting to Hello, World in Assembly Language on the Commodore 64

Well hello there! If you are looking to get up and running writing computer programs in machine code on your Commodore 64, you’ve found the right blog post! In fact, this is something that I’m trying to learn myself at the moment, and I’ve been having somewhat of a hard time getting to “hello, world.”

So here are the three key pieces of information that I’ve discovered thus far…

  1. THE COMMODORE 64 MACRO ASSEMBLER DEVELOPMENT SYSTEM is the name of the official assembler program from Commodore for the C64. There are other assemblers out there you can try as well, but this was the actual assembler that Commodore put out for people to be able to write machine language programs for their machine. However, if you happen to read Commodore’s Commodore 64 Programmer’s Reference Guide they call it something else in that book. So don’t waste your time looking for the 64MON Assembler Cartridge mentioned in that book. I personally was never able to find any of these cartridges on eBay, and had trouble finding any information at all regarding 64MON. However, I found plenty of information regarding THE COMMODORE 64 MACRO ASSEMBLER DEVELOPMENT SYSTEM so I suggest using it instead of hunting for the mysterious 64MON Cartridge.
  2. An assembly language aficionado I discovered on YouTube advised that the Commodore 64 Programmer’s Reference Guide isn’t a very good book for learning assembly language. However, I found that the beginning of the manual for THE COMMODORE 64 MACRO ASSEMBLER DEVELOPMENT SYSTEM the author(s) mention several better books for getting started with assembly-language/machine-code programming for the MOS Technology 6502/6510 microprocessor.
  3. And last but not least, the best book I’ve found is actually for kids: Assembly Language for Kids Commodore 64 by William B. Sanders. Most importantly his book actually talks about getting to “hello, world” using three different assembler programs.

So there you have it. Those are the three things you need to get started writing machine code on your Commodore 64. My goal tonight was to actually get to “hello, world” myself… but it’s about time for bed! But before falling asleep I really wanted to make sure to jot down this information for my own personal reference and maybe anyone else who is trying to get in to assembly language programming on the C64.

Also, I wanted to try and upload some of these old manuals here to my blog for archival/reference purposes. They are also available on Archive.org, but I figured hosting them here as well can’t hurt. (Having a little bit of trouble uploading large PDFs here to WordPress, so for now, I’ve including links below)

UPDATE (August 19th, 2021)

I’ve been running into some trouble figuring out how to save my hello, world assembly language programs created using the Commodore 64 Macro Assembler Development system as the book by William B. Sanders kind of skips over this step! So I just wanted to make note of another book I’m now referencing to try and get a better basic understanding of how to use the Commodore 64 Macro Assembler Development System to create and distribute assembly language programs which can be run by anyone from disk without all sorts of other crazy steps. If you find yourself in a similar situation check out this book: Commodore 64 Assembly Language Arcade Programming by Steve Brees

 

How to Find and Strip Duplicate Items from an Array in JavaScript (the Easy Way)

I found today at work I needed to identify duplicates in an array, and happened to stumble upon this highly ranked StackOverflow post full of hard to understand answers. Whenever I write code at work, I really want to make sure that I understand all of the code that I contribute to the company’s codebase and that I’m not blindly copying and pasting directly from StackOverflow. So if you’ve happened to find this blog post looking for something a little easier to understand than many of the other answers out there on the internet, maybe consider my solution:

// Duplicates: Bob, Aaron, Frank
const arrayWithDuplicates = ["Aaron", "Bob", "Chris", "Dave", "Edward", "Bob", "Aaron", "Frank", "George", "Frank", "Henry", "Bob", "Bob", "Aaron", "Aaron", "Frank"];
function findDuplicates(arrayWithDuplicates) {
let duplicates = [];
arrayWithDuplicates.forEach( (value, index) => {
const indexWhereValueFirstAppears = arrayWithDuplicates.findIndex( (value_) => {
return value_ === value;
});
const indexWhereValueLastAppears = arrayWithDuplicates.lastIndexOf(value);
if (index !== indexWhereValueFirstAppears && index === indexWhereValueLastAppears) {
duplicates.push(value);
}
});
return duplicates;
}
const duplicatesFound = findDuplicates(arrayWithDuplicates);
duplicatesFound.forEach( (duplicate) => {
console.log("Duplicate: " + duplicate);
});

And if you need to simply strip duplicates from an array, try:

// Duplicates: Bob, Aaron, Frank
const arrayWithDuplicates = ["Aaron", "Bob", "Chris", "Dave", "Edward", "Bob", "Aaron", "Frank", "George", "Frank", "Henry", "Bob", "Bob", "Aaron", "Aaron", "Frank"];
function stripDuplicates(arrayWithDuplicates) {
let uniques = [];
arrayWithDuplicates.forEach( (value, index) => {
const indexWhereValueFirstAppears = arrayWithDuplicates.findIndex( (value_) => {
return value_ === value;
});
if (index === indexWhereValueFirstAppears) {
uniques.push(value);
}
});
return uniques;
}
const arrayWithNoDuplicates = stripDuplicates(arrayWithDuplicates);
arrayWithNoDuplicates.forEach( (unique) => {
console.log("Unique: " + unique);
});
 

TypeScript type = foo | bar | baz ??? Union Types Demystified

At work this past Friday I found myself exposed, exposed as an imposter: a TypeScript imposter! Often times hang loose JS script kiddies like myself can manage to fumble or fake their way through working with statically typed enterpise grade TypeScript codebases if they have to, but this past Friday a single line of code brought me to my knees! But fret not my friend, if you happen to be stumped by the following line of code:

type Something = Foo | Bar | Baz;

I have your answer: Union Types

Let me explain. If you ever run into a mysterious line of code like the one above where a type equals one thing OR another thing OR something else entirely, you are looking at a TypeScript Union Type. So what is a Union Type? A Union Type is simply a type which can include several different types. Take an “Athlete” for example. One could create a union type called “Athlete” which could be used to represent several different sub-types such as “FootballPlayer”, “BasketballPlayer”, or “BaseballPlayer”. If for some reason you happen to encounter a union type in your company’s codebase that you need to work with, there are two main things you need to know about these types.

First, if you are working with an object with a union type, know that you will be able to access all of that objects properties which are shared among all of the different types which the union type unites. So if FootballPlayer, BasketballPlayer, and BaseballPlayer all have a shared set of properties, you can access those shared properties from your object with the type Athlete.

Second, you need to know that if you try to access a property of your Athlete object which is not shared among FootballPlayer, BasketballPlayer, and BaseballPlayer, your code will crash!

However, if you really need to access a property from your Athlete object that isn’t shared among those three types, you can cast the object as a specific type to access the unique property. I know that I may be loosing some of you right about now, so… without further ado, here is a nifty little example script demonstrating how to work with TypeScript Union Types if you ever find yourself in a tricky situation trying to juggle union types:

// DEMO: Using Union-Types in TypeScript
// Question: What are Union Types???
// Answer: Union Types are TypeScript types which can be equal to many different types which often share 'union' properties amongst the various different types. For example, an Athlete Union-Type could be used to represent FootballPlayer, BasketballPlayer, and BaseballPlayer types
type FootballPlayer = {
firstName: string,
lastName: string,
jerseyNumber: number,
sport: string,
touchdowns: number,
};
type BasketballPlayer = {
firstName: string,
lastName: string,
jerseyNumber: number,
sport: string,
points: number,
};
type BaseballPlayer = {
firstName: string,
lastName: string,
jerseyNumber: number,
sport: string,
hits: number,
};
type Athlete = BaseballPlayer | BasketballPlayer | FootballPlayer;
const quarterback: Athlete = {
firstName: "Ben",
lastName: "DiNucci",
jerseyNumber: 7,
sport: 'Football',
touchdowns: 0,
};
function displayStats(athlete: Athlete) {
switch(athlete.sport) {
case "Football":
// NOTE: We can access shared 'union' properties such as firstName,
// lastName, jerseyNumber, and sport using 'athlete' which is of the
// union type 'Athlete'
console.log("Player: " + athlete.firstName + " " + athlete.lastName);
// HOWEVER: If we want to access a non-union-type property such as
// touchdowns, we cannot use 'athlete' which is of the union type
// 'Athlete'. Attempting to call athlete.touchdowns will crash the app.
// Instead, we need to type-cast athlete as FootballPlayer if we wish
// to access the 'touchdowns' property
let footballPlayer: FootballPlayer = athlete as FootballPlayer;
console.log("Touchdowns: " + footballPlayer.touchdowns.toString());
break;
case "Basketball":
console.log("Player: " + athlete.firstName + " " + athlete.lastName);
let basketballPlayer: BasketballPlayer = athlete as BasketballPlayer;
console.log("Points: " + basketballPlayer.points.toString());
break;
case "Baseball":
console.log("Player: " + athlete.firstName + " " + athlete.lastName);
let baseballPlayer: BaseballPlayer = athlete as BaseballPlayer;
console.log("Hits: " + baseballPlayer.hits.toString());
break;
default:
console.log("Error: Something went wrong...");
}
}
displayStats(quarterback);
view raw unionTypes.ts hosted with ❤ by GitHub
 

How to use Postman to Query your Company’s Backend API: A Junior Developer’s Crash Course

As a junior frontend or mobile developer, it can be quite intimidating to work with your companies backend API for the first time using a tool like Postman. In a corporate setting, there’s a good chance that you may not have access to the backend code, and that there may be little to no documentation available to you to help guide you through working with the backend API. In the real world, a lot of the knowledge regarding how the frontend and backend systems work may be locked up inside the heads of other teammates, and you may find yourself having to figure things out for yourself.

But fret not! Many companies follow a pretty straightforward convention for granting access to the backend API, so that’s what I would like to share with you here in this blog post. Obviously, companies don’t want to let anyone access their backend API. Take Snapchat for example. Snapchat doesn’t want anyone to be able to query their API and read any message they want. Snapchat only wants users to be able to read their own messages, not everyone’s messages. And this goes for pretty much all companies. Backend APIs need to be able to authenticate requests to make sure the person or computer making the request is who they claim to be and that they have access to the information they are requesting.

And how do backend APIs handle this authentication? Bearer Tokens!

Just like you have usernames and passwords for logging in to websites and apps, backend APIs have a similar method of authentication. But instead of a username and password, backend APIs roll all of that information into one– a bearer token. What is a bearer token? A bearer token is long string of text which essentially represents a username and password. You can think of it as a magic passphrase that grants the bearer access to all of the data for a given account. And why is this important? Well the bearer token is the primary thing that you will need to access your companies backend API using Postman.

So without further ado, here’s how you add a bearer token in Postman:

First, you’ll need to sift through your companies frontend code and programmatically retrieve a token for the test user you want to access the backend API as. Let’s say your company has a test user with an email address of johndoe@gmail.com and a password of p@$$w0rD123. You’ll run the development version of your companies app on your development machine, log in as user johndoe@gmail.com and see if you can programmatically retrieve a token for this test user. Somewhere in your companies codebase there will be a variable or method which will let you retrieve the user’s token. Find the token, print it to your developer console, then copy and paste it to a text file and you’re all set. Now you have the magic word!

Second, you’ll need the URL for the API endpoint which you want to query. Just like with the token mentioned above, you’ll need to hunt through your companies frontend codebase to find this, then print it to your developer console, and then copy and paste it to a text file to save it.

Third, you will need to find the JSON data which you want to send to the backend API. Typically with a POST request, you will be sending information to the backend API in the form of a JSON object. So find the JSON which you want to send the backend API, print it to the console, and copy and paste it to a text file.

Now we’re all set. We have our token, API endpoint URL, and the JSON data we wish to send via Postman. You can either fire up the Postman desktop app to send your request, or log in to getpostman.com and use their web-app. For this example, we will be making an HTTP POST request (as opposed to an HTTP GET request).

Once logged in to Postman, click on “Create a Request” to get started. Select “POST” from the dropdown menu and paste the URL for the endpoint which you wish to query. Under the “Authorization” tab, paste your bearer token. Under the “Headers” tab, enter the key “Accept” and the value “application/json”. And under the “Body” tab, select the “RAW” radio button and select “JSON” from the dropdown menu, then paste your JSON into the text field.

Press “SEND” to make your HTTP request, and that’s it!

 

How to Upgrade/Update Git to the Latest Version on Mac

Need to upgrade/update git to the latest version on your Mac? The following should do the trick:

First, if you don’t already have homebrew installed, install homebrew:

$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Then update/upgrade brew:

$ brew update

$ brew upgrade

Install the latest version of git with homebrew:

$ brew install git

Now, make sure to close your terminal app. This is key because if you don’t close your terminal app and then re-open it, your terminal will not recognize the latest version installed via homebrew.

In a new terminal window, run the following to confirm you are now running the latest version of git:

$ git --version