Getting Sequel Pro to read MySQL on MacOS

As a follow-up to the previous post (Installing MySQL on MacOS with Homebrew), to get Sequel Pro working you need to do the following:

Open my.cnf (usually at /usr/local/etc) and add the following line and save:
[mysqld]
default-authentication-plugin=mysql_native_password

Sign into mysql with mysql -u root -p

Set the root user password with:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '[PASSWORD]';

where [PASSWORD] is a password of your choosing.

Delete my.cnf (MySQL will regenerate it):

sudo rm -rf /usr/local/etc/my.cnf

Restart mysql:

brew services restart mysql

Now Sequel Pro should be able to log into MySQL.

Reference:
Sequel Pro and MySQL connection failed
Cannot find MySQL.sock

Advertisement

Installing MySQL on MacOS with Homebrew

I was trying to install MySQL on MacOS and I followed the instructions to install it via Homebrew:

$ brew install mysql

Pretty easy, but then as I worked along I screwed something up where I could not load mysql in the command line. I would get the following error:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

So I do the logical step of uninstalling and reinstalling:

$ brew uninstall mysql
$ brew install mysql

I still get the same error. Two hours of browsing StackOverflow later, I figured it out. I failed to notice the following errors during reinstallation:

2019-02-21T01:02:48.455076Z 0 [System] [MY-013169] [Server] /usr/local/Cellar/mysql/8.0.15/bin/mysqld (mysqld 8.0.15) initializing of server in progress as process 18070
2019-02-21T01:02:48.457920Z 0 [ERROR] [MY-010457] [Server] --initialize specified but the data directory has files in it. Aborting.
2019-02-21T01:02:48.457929Z 0 [ERROR] [MY-013236] [Server] Newly created data directory /usr/local/var/mysql/ is unusable. You can safely remove it.
2019-02-21T01:02:48.457994Z 0 [ERROR] [MY-010119] [Server] Aborting
2019-02-21T01:02:48.458203Z 0 [System] [MY-010910] [Server] /usr/local/Cellar/mysql/8.0.15/bin/mysqld: Shutdown complete (mysqld 8.0.15) Homebrew.

This is the key line:
Newly created data directory /usr/local/var/mysql/ is unusable. You can safely remove it.

What do I do? Remove that directory!

$ sudo rm -rf /usr/local/var/mysql/

Then run the post install script:

$ brew postinstall mysql

And voilà, mysql loads!

$ mysql -uroot
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.15 Homebrew

Learn from my fail.

Cloning Mongo Database From Heroku to Local

These are the steps I compiled to clone a Mongo database from Heroku to local. It is provided as-is without warranty nor guarantee nor support.

  1. Open command prompt (Windows) or Terminal (Mac/Linux) and navigate to the project’s working folder.
  2. Get the config vars from Heroku with heroku config --app <appname>
    • Find the MONGOLAB_URI value. It will be in the form of: mongodb://<username>:<password>@<url>:<port>/<database>
  3. Run the following command to make a copy of the production database to your local working directory.
    • Use the values from the config file: mongodump -h <url>:<port> -d <database> -u <username> -p <password>
    • mongodump will create the following directory to store the data: dump/<database>/
  4. Make sure your local instance of mongod is running.
  5. Drop your existing local database with the following command.
    • mongo <dbname> --eval "db.dropDatabase()"
    • <dbname> is your local database name specified in your project’s config file under MONGOLAB_URI.
  6. Use mongorestore to put the prod data into your local mongodb.
    • mongorestore -d <dbname> dump/<database>/
  7. Ensure data was restored
    • Start mongo command line interface: mongo
    • Show databases and ensure <dbname> is in the list: > show databases
    • Switch to <dbname>: > use <dbname>
    • Ensure games and players tables exist: > show collections
    • If satisfied, then exit mongo command line: > exit
  8. Run the app and see the prod data (see “Running” section below)
  9. ???
  10. Profit!

Get off my lawn!

It’s funny how modern icons use symbols of things that were ubiquitous years ago. This article showcases a nice list of icons and their archetype.


The Floppy Disk means Save, and 14 other old people Icons that don’t make sense anymore

I can say I’ve used every analogue in the list except for the car radio and the old-school microphone. And yes, my TV does have rabbit ears. And it’s not a huge honkin’ CRT with wood paneling either. I’m pretty sure most of the designers grew up using the depicted items as well. It’s just lost on people born after 1993.

I hate this penguin movie

This isn’t the “March of the Penguins”! If I had to watch this on a long-haul flight, I’d lock myself in the lavatory and cry.

linuxboot

Source: There I Fixed It

Do people in other countries program in English?

I was browsing Stack Overflow’s programming section and came across an interesting topic asking if programmers in other countries code in English. This answer from a Canadian is hilarious:

I’m from Canada, but live in the States now.

It took me a while to get used to writing boolean variables with an “Is” prefix, instead of the “Eh” suffix that Canadians use when programming.

For example:

MyObj.IsVisible

MyObj.VisibleEh

I should name my boolean variables that way from now on.

Beep! Beep!

So I wrote a post about creating basic beeping sounds in C# a few months ago:
https://inphamousdevelopment.wordpress.com/2012/05/07/console-beep-for-64-bit-windows/

Well, someone asked me if I could make the source code available. Well, because I’m a nice guy, I’ve cleaned up the project and uploaded it here:

http://phamous-apps.com/wordpress/MusicBeeperPA.zip

You will need Visual Studio 2010 or newer to run the project as-is. I have not tested it in Mono, and I do not guarantee that it will work in Mono. The code is offered AS-IS WITH NO SUPPORT.

If you find the project useful, please make a video response to the YouTube video with your creation.

Learn from my fail: check your pointers

I spent quite some time tracking down an issue I was having with my C++ project. Here is a snippet of the code:

class foo
{
private:
    bool* myArray;

public:
    foo()
    {
        myArray = new bool[5];

        for(int i=0; i<5; i++)
        {
            myArray = false;
        }
    }

    void init()
    {
        myArray[0] = true;
    }
};

Every time I ran it, it would throw a memory access violation. I was very puzzled by this since it was just a standard boolean array holding true or false. It wasn’t anything very advanced. I used the Visual Studio debugger to poke around. It goes through the constructor fine and then when it goes into the init() function myArray would become a null pointer. The debugger would report that myArray has a memory address of 0x00000000.

I was very confused because how could the pointer be initialized properly in the constructor, but not be initialized when I step into another function in the same object? I chased it all afternoon and decided to give up and walk away. The next morning, I looked at the code again. Then it hit me: the problem and solution was staring at me in the face.

In the for loop in the constructor I have this code:

myArray = false;

I had forgotten to put in the array subscript! If myArray was a true null pointer, it would have just said it was uninitialized or “nullptr” with a stop icon instead of a zero memory location. What was happening was that the pointer was being set to false, which is zero. That is why the debugger showed that the memory location was 0x00000000. So when I access the pointer to assign a value, I am accessing memory that is already reserved or in-use so it throws a memory access violation. The code is “valid” which is why it doesn’t show any errors during compilation, but it doesn’t produce the desired results at runtime.

With the correct code:

myArray[i] = false;

Everything works fine and I was able to continue my project! After working with C# for a while, it’s an eye opener how much the .Net garbage collector and managed heap does for the programmer.

Sending callbacks from C# to C++

Some days you just have to work with old methods to get the job done. I am working on a project that needs to be in native C++ for legacy reasons, but would prefer to bring it to the modern era of programming by using C#. I wanted a way to get data from the native classes to the managed classes so the entire program could be extended easier in the future and made more simple for someone to use (the original program was very linear and very tightly integrated that the user was required to be a programmer to use it). Using Microsoft’s Common Language Infrastructure (CLI) as a bridge between native C++ and managed C#, it is possible to make the two play together nicely. I’m going to assume that you have a basic knowledge of Microsoft Visual Studio 2008 and basic C#/C++/CLR coding skills.

If you want to follow along, the complete code for the demo program is available at:

http://phamous-apps.com/wordpress/NativeCallbackDemo.zip

I first create a new C++/CLR Class Library and a new C# Windows Form application in Visual Studio:

My solution looks like the following image. CEventTest is the CLI bridge between native and managed classes while NativeClass is a class written in pure C++. I keep all the code in the header file so there is nothing in the CPP file except for a #include for the associated header file so the compiler will compile the program.

The C# project (EventTest) is just a windows form with a multi-line textbox and some buttons like the following image.

In NativeClass.h, I have the following code:

#pragma once

#include
using namespace std;

typedef void (__stdcall *CallbackType)(unsigned char*, int);

class NativeClass
{
public:

    NativeClass(void);
    ~NativeClass(void);

    void CreateByteArray(CallbackType callback)
    {
        int size = 64;
        int byteSize = size * sizeof(float);

        unsigned char* byteArray = new unsigned char[byteSize];
        float* myFloatArray = new float[size];

        for(int i=0; i<size; i++)
        {
            myFloatArray[i] = (float)i * 2;
        }

        memcpy(byteArray, myFloatArray, byteSize);

        callback(byteArray, byteSize);
    }
};

Ok, this seems like very advanced code, but keep calm and I’ll explain what’s going on. The line:

typedef void (__stdcall *CallbackType)(unsigned char*, int);

declares the callback function prototype. CallbackType is a type that I made up. You can call it FooBarType if you want. The next part is the parameter list of the function that is going to be passed. The function I’m sending will have a byte array (unsigned char pointer) and an integer (to define the size of the array). The rest is standard boilerplate code for a function pointer. Just accept that it is magic and change the parts that I mentioned.

The rest of the file is a standard C++ class. The function CreateByteArray takes in the function pointer, so “callback” contains the pointer to the function. We can use “callback” like any other function now. The rest of the code of this function creates a byte array and fills the array with sequential float values. At the end of the function I use “callback” like a normal function. So, that’s one step and the native code is done for now.

Let’s turn to the CEventTest class now. CEventTest will bridge the native code with the managed code. The code is as follows (the comments will explain the code):

// CEventTest.h

#pragma once

#include
using namespace std;

#include "NativeClass.h"

namespace CEventTest {

	// must be outside of class so other classes can use them
	public delegate void NumberSender(int x);

	// delegate used for native C++ callback function
	public delegate void NativeDelegate(unsigned char* buffer, int bufferSize);

	public ref class Processor
	{
	private:
        // native C++ class to use. it must be a pointer.
        static NativeClass* nativeC;

        // must be declared outside of method or else garbage collector will delete!
        static NativeDelegate^ callback;

	public:

		/*
		events must be static in order to be accessed by thread
		and is public so other class can register the event handler
		*/
		static event NumberSender^ SendNumber;

		/*
		This function starts the C++ native class and passes our managed method to it as a callback funtion.
		*/
		static void StartNative()
		{
			using System::IntPtr;
			using System::Runtime::InteropServices::Marshal;

			// get a pointer to the delegate
			IntPtr cbPtr = Marshal::GetFunctionPointerForDelegate(callback);

			// call the native C++ function with our delegate pointer
			nativeC->CreateByteArray(static_cast(cbPtr.ToPointer()));
		}

		// constructor
		Processor()
		{
			nativeC = new NativeClass();

			// cast our managed method to a delegate
			callback = gcnew NativeDelegate(&Processor::NativeByteReceiver);
		}

		// destructor
		~Processor()
		{
			delete nativeC;
		}

		/*
		Our managed method which is to be used as native C++ callback function
		*/

		static void NativeByteReceiver(unsigned char* byteArray, int byteSize)
		{
			int size = byteSize / sizeof(float);

			float* myFloatArray = new float[size];

			memcpy(myFloatArray, byteArray, byteSize);

			for(int i=0; i<size; i++)
			{
				// signal an event
				SendNumber((int)myFloatArray[i]);
			}
		}

		void RunNativeDemo()
		{
			StartNative();
		}
   };
}

Delegates are the equivalent of callback functions in CLI. They must be declared outside of the class like the callback function declaration in C++. I’ve declared two delegates here:

public delegate void NumberSender(int x);
public delegate void NativeDelegate(unsigned char* buffer, int bufferSize);

The first delegate “NumberSender” is used to send an integer value to managed code (ie- the C# class). The other delegate “NativeDelegate” is used to magically take the managed C++ function and get a function pointer for the native C++ class. Remember the managed function and the delegate must have the same argument list (an unsigned char pointer and an integer).

In the class, the native C++ code must be in an object so a pointer can be used. Just accept that it has to be a pointer in order for it to work so that is why it is a static pointer:

// native C++ class to use. it must be a native pointer.
static NativeClass* nativeC;

I also have a public event so that the event can be registered with managed classes:

// managed CLI pointer for the event
static event NumberSender^ SendNumber;

The function for starting the native code has to be static. We need to use the IntPtr type and the Marshal class to get the pointer. A new NativeDelegate is created and is told the function in this class to use. Pass the memory address to the delegate constructor. Then a memory pointer is derived via marshalling. Then we call the function in the native class like normal, but we need to cast the delegate pointer to the callback function type that was declared in native class. Just change the following code to suit your needs.

/*
This function starts the C++ native class and passes our managed
method to it as a callback funtion.
*/

static void StartNative()
{
    using System::IntPtr;
    using System::Runtime::InteropServices::Marshal;

    // cast our managed method to a delegate
    NativeDelegate^ callback = gcnew NativeDelegate(&Processor::NativeByteReceiver);

    // get a pointer to the delegate
    IntPtr cbPtr = Marshal::GetFunctionPointerForDelegate(callback);

    // call the native C++ function with our delegate pointer
    nativeC->CreateByteArray(static_cast(cbPtr.ToPointer()));
}

When the function is called in the native code, the order of events shift back to the CLR class:

/*
Our managed method which is to be used as native C++ callback function
*/

static void NativeByteReceiver(unsigned char* byteArray, int byteSize)
{
    int size = byteSize / sizeof(float);

    float* myFloatArray = new float[size];

    memcpy(myFloatArray, byteArray, byteSize);

    for(int i=0; i<size; i++)
    {
        // signal an event
        SendNumber((int)myFloatArray[i]);
     }
}

It does the reverse of the native class function where it takes the byte array and puts the data into a float array. Each value in the float array is then sent to the C# code via the SendNumber event.

The last function in the class (“RunNativeDemo”) just starts the entire process.

Go to the EventTest project in the Solution Explorer, right click on the project name, and click “Add Reference”. Find the project CEventTest and add the reference. Now the CLR library can be used by the C# windows form project!

In the C# designer view, double-click on the “Native Demo” button and it will generate the method stub. Create the object for the CLR class library (I name the class “Processor” and the object “countThread”). Inside the button’s method stub, I just called the function that runs the native code via CLR.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

// remember to include the reference to the CLR class library
using CEventTest;

namespace EventTest
{
	public partial class Form1 : Form
	{
		// declare the CLR object
		private Processor countThread;

		public Form1()
		{
			InitializeComponent();

			// initialize the CLR object
			countThread = new Processor();

			// link the event for the number sending to a function in this class
			Processor.SendNumber += new NumberSender(Processor_SendNumber);
		}

		/// <summary>
		/// Given an integer, display the number in the textbox
		/// </summary>
		///The integer value sent from the caller
		void Processor_SendNumber(int x)
		{
			// Invoking is required for accessing GUI components
			if (this.InvokeRequired)
			{
				Invoke(new NumberSender(Processor_SendNumber), new object[] { x });
			}
			else
			{
				// Create a string with the number to display in the textbox
				textBox1.AppendText(string.Format("Received Value: {0}\r\n", x));
			}
		}

		/// <summary>
		/// Starts the process to run native code
		/// </summary>
		private void uxNative_Click(object sender, EventArgs e)
		{
			countThread.RunNativeDemo();
		}
	}
}

The callback function in the form requires invoking the delegate. The subject matter is somewhat advanced to explain here so if you want to know more then read up on MSDN and Google. We’ll just accept it as magic here. As long as you have the if-else statement like the above code, swap out the delegate for your own delegate, put your argument list in the object array, and put the GUI-related code in the else block, then you are fine.

Compile the project and run. If everything is working correctly, when the “Native Demo” button is pressed, it should show a list of numbers in the textbox.

There we go! It’s magic! I’m sorry if I skipped a lot of conceptual details because I know I did but I just wanted to throw some code out there for those who want to see the concept in action. It seems there are a lot of write-ups out on the web that explain the theory and have a very basic example, but nothing to show a practical use of the concept.

I also want to note that even though my example uses a byte array, you can use any type you want for the callbacks. Floats, integers, doubles, arrays, etc. I just chose to use a byte array because that is what my project required. I could have just sent the original float array as-is if I wanted to. All I would have to do is change the type to float* instead of unsigned char* and remove the mempy step.

Also it may seem a bit much too just return a byte array from native C++ to C# in this way, but the original code in my project had the callback in a C++ thread (to separate it from the C# GUI thread), which would have complicated the example. I did not want to confuse you so the threading code was removed.

Hopefully this tutorial helped someone and didn’t bore anyone to sleep. For further reading, these links were the ones I used to piece this project together:

http://stackoverflow.com/questions/6507705/callbacks-from-c-back-to-c-sharp

http://stackoverflow.com/questions/2298242/callback-functions-in-c

http://forums.asp.net/t/571841.aspx

Console.Beep for 64-bit Windows

Lately, I’ve been experimenting with making music with computers. I do not have a music background so it’s been a difficult route. One of the things I regret is not taking a music or band class in high school. Fortunately, there are plenty of websites that explain how to read sheet music and plenty of videos to watch to learn how to play popular songs. It’s like learning a new programming language in which you’re learning new syntax and semantics, but takes a lot of practice and constant self-improvement via experimentation and feedback from others to perfect.

Now you’re probably thinking why I’m talking about music theory on a programming blog. Well, a cheap and easy way to make music is to write a console application using Visual C# Express. You can use Console.Beep() and specify a frequency and duration to make a note. This is the route I tried, but I was extremely disappointed to find out that Console.Beep() didn’t work with the 64-bit version of Windows starting with Vista and newer.

Well, there is a work-around! This MSDN forum post outlines how to send the beep to the computer speakers via a class. It appears to take the note information (amplitude, frequency, and duration), convert it into a sine wave, converts the sine wave to a byte array, saves the byte array as a WAV file in memory, and plays the WAV file to the computer speakers. Brilliant!

I am not the author of the code so any questions regarding it should be posted in the forum post, but I will repost the code here in case the forum post disappears.

// include these at the top of the file:
// using System;
// using System.IO;
// using System.Media;

// the following code goes inside your namespace
public class Beep
{
    // I added this function because amplitude should just always be 1000
    // < 1000 sounds muffled and > 1000 throws an exception
    public static void Play( double frequency, double duration )
    {
        BeepBeep( 1000, frequency, duration );
    }

    private static void BeepBeep( double Amplitude, double Frequency, double Duration )
    {
        double Amp = ( ( Amplitude * ( System.Math.Pow( 2, 15 ) ) ) / 1000 ) - 1;
        double DeltaFT = 2 * Math.PI * Frequency / 44100.0;

        int Samples = (int)(441.0 * Duration / 10.0);
        int Bytes = Samples * sizeof(int);
        int[] Hdr = { 0X46464952, 36 + Bytes, 0X45564157, 0X20746D66, 16, 0X20001, 44100, 176400, 0X100004, 0X61746164, Bytes };

        using ( MemoryStream MS = new MemoryStream( 44 + Bytes ) )
        {
            using ( BinaryWriter BW = new BinaryWriter( MS ) )
            {
                for ( int I = 0; I < Hdr.Length; I++ )
                {
                    BW.Write( Hdr[I] );
                }
                for ( int T = 0; T < Samples; T++ )
                {
                    short Sample = System.Convert.ToInt16( Amp * Math.Sin( DeltaFT * T ) );
                    BW.Write( Sample );
                    BW.Write( Sample );
                }

                BW.Flush();
                MS.Seek( 0, SeekOrigin.Begin );
                using ( SoundPlayer SP = new SoundPlayer( MS ) )
                {
                    SP.PlaySync();
                }
            }
        }
    }
}