Categories
Uncategorized

Kotlin + OpenCV + macOS + MacPorts

I saw this very useful post by Simon Hoffman on how to set up Kotlin and OpenCV.

https://dev.to/s1hofmann/kotlin–tornadofx–opencv–fun–39e5

Here is an alternate approach (I’m not adding TornadoFX/JavaFX in this).

1. (After updating and upgrading your MacPorts) install opencv with java:

sudo port install opencv +java

This will install the OpenCV library (jar and dylib) to:

/opt/local/share/OpenCV/java

2. Now create a new Kotlin project in IntelliJ IDEA

3. Add the OpenCV dependency:

File > Project Structure > Modules > Dependencies > + > jars or directories > Navigate to /opt/local/share/OpenCV/java > select the OpenCV jar file – for me it was opencv-348.jar

4. Create a new Kotlin file (I named mine TestOpenCVSetup.kt) to test the installation – paste the following code (taken from Simon Hoffman’s post):

import org.opencv.core.Core
import org.opencv.core.CvType
import org.opencv.core.Mat


fun main() {
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME)

    val mat = Mat.eye(5, 5, CvType.CV_8UC1)
    println("mat = ${mat.dump()}")
}

If you’ve set up the dependency properly, there will be no errors.

5. Now click the green play button in the gutter of fun main()

You should get an error:

Exception in thread "main" java.lang.UnsatisfiedLinkError: no opencv_java348 in java.library.path: [/Users/your_user_name/Library/Java/Extensions, /Library/Java/Extensions, /Network/Library/Java/Extensions, /System/Library/Java/Extensions, /usr/lib/java, .]
	at java.base/java.lang.ClassLoader.loadLibrary(ClassLoader.java:2670)
	at java.base/java.lang.Runtime.loadLibrary0(Runtime.java:806)
	at java.base/java.lang.System.loadLibrary(System.java:1909)
	at TestOpenCVSetupKt.main(TestOpenCVSetup.kt:7)
	at TestOpenCVSetupKt.main(TestOpenCVSetup.kt)

6. Now you have a few options to fix the error.

One option is to copy the libopencv_java348.dylib file from /opt/local/share/OpenCV/java to your user Java libraries /Users/your_user_name/Library/Java/Extensions.

The Java/Extensions folders may not be present so you can create them (mkdir or Cmd + Shift + N).

7. Re-run the program and you should get the following output:

mat = [  1,   0,   0,   0,   0;
   0,   1,   0,   0,   0;
   0,   0,   1,   0,   0;
   0,   0,   0,   1,   0;
   0,   0,   0,   0,   1]

Process finished with exit code 0
Categories
Uncategorized

Lovely Java Improvements – Thanks @JetBrains #IntelliJ

Back in the day, this is how I would sort an array of file names in alphabetical order:


secondaryTaskConfigFiles.sort(new Comparator() {
@Override
public int compare(File o1, File o2) {
return o1.getName().compareTo(o2.getName());
}
});

So IntelliJ told me to change the code to a lambda expression:


secondaryTaskConfigFiles.sort((o1, o2) -> o1.getName().compareTo(o2.getName()));

Looks nice? Yep! …But wait… another suggestion:


secondaryTaskConfigFiles.sort(Comparator.comparing(File::getName));

Thanks JetBrains for a fantastic IDE. For programmers used to the “old” ways it helps a lot!

Categories
Uncategorized

Updating your Composer-based installation (e.g. Laravel) as root

If you have root access to your web server (congratulations!) and you need to update your composer-based installation, e.g. Laravel, then you may get the following warning if you try to run composer update as root.

Take a read of https://getcomposer.org/root for more details.

 

Thanks to user Weboide’s answer on AskUbuntu Question 839107 I was able to run composer as www-data (the Apache user).

Steps:

  1. chsh www-data
  2. Enter the new value, or press ENTER for the default: /bin/bash
  3. su www-data
  4. run composer update in your Laravel directory

[Edit, 28 Feb 2018] PS: For future access you only need to run steps 3 and 4.

[Another edit, 28 Feb 2018]

Sometimes your memory may still be limited (e.g. on a VPS controlled by someone else) and the composer update doesn’t work. I found that shutting down apache, mysqld and php frees up valuable memory.
kill $(ps aux | grep '[p]hp' | awk '{print $2}')[1]

systemctl stop apache2.service
systemctl stop mysqld
[2]

 

[1] https://easyengine.io/tutorials/linux/kill-all-processes/
[2] https://askubuntu.com/questions/824979/stop-lamp-in-16-04

Categories
Uncategorized

Thanks to Janis Elsts, Vladimir Prelovac – devs of “Broken Link Checker” plugin

I haven’t updated content in a while. Found this plugin very useful to find broken links.

THANKS Janis and Vladimir!

Broken Link Checker

Categories
Uncategorized

Py-Audio instantaneous recording to file without buffering

Py-Audio has an awesome script to record sound from your recording device {mic, webcam, etc.} and output to a wave file.

Here is the example script to record audio taken from the Py-Audio website:

"""PyAudio example: Record a few seconds of audio and save to a WAVE file."""

import pyaudio
import wave

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

print("* recording")

frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()

This is awesome, BUT if you’re doing a long recording and something happens like an automatic reboot, crash, etc. then all your recorded samples will be lost.

An alternate way to make sure that your audio is written to file instantaneously is by making a small modification to the above code.

  1. Instantiate the wave file before reading the audio stream.
  2. Write the frames as soon as you read a chunk of input from the stream.

See the modified portion of the script below:

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames = []
    frames.append(data)
    wf.writeframes(b''.join(frames))
print("* done recording")
stream.stop_stream()
stream.close()
p.terminate()
wf.close()

 

Categories
Uncategorized

Exiting full screen exclusive mode in Java AWT

We’ve been using Java AWT and Swing and needed full screen exclusive mode. (Not using JavaFX at the moment – but will be transitioning soon.)

This tutorial provides a nice way to enter full screen mode:
https://docs.oracle.com/javase/tutorial/extra/fullscreen/index.html

One problem that I faced was getting out of full screen mode after setting a window/JFrame as full screen.

The solution turns out to be simple:

myDevice.setFullScreenWindow(null);

See:
https://docs.oracle.com/javase/tutorial/extra/fullscreen/displaymode.html

Categories
Uncategorized

Open Broadcasting Software (OBS) autoload / startup problem on Mac OSX Yosemite with CamTwist

Today, I was using Open Broadcasting Software (OBS) for some projects that we have running.  Due to the nature of the set up, we are using CamTwist as well, because OBS is not currently recognising some of the video capture devices.

During the set up process, the CamTwist options I used made OBS unstable and caused OBS to crash.  Because I had saved these settings, each time I loaded OBS it would crash on startup.

After a quick search and looking at the log files, I found where the autoload settings are located.

$ find ~ -name *obs*

This gives some output, the most important being:

./Library/Application Support/obs-studio

Open the folder:

open ./Library/Application\ Support/obs-studio/basic/scenes/

You’ll find the json configuration file – either delete it or edit it, and you will be able to open up OBS again. :-)

Categories
Uncategorized

How to fix your IEEE pdf and embed fonts in Latex

How to fix your IEEE pdf to embed fonts in Latex

I’m submitting a paper to IEEE.  One of the requirements is that they ask you to put your pdf paper into their online checking system: http://www.pdf-express.org/

They sent me an email telling me that my paper wasn’t suitable for publication – some errors.  These errors were because some fonts were not embedded – Helvetica and Symbol.

First thing:

Get the diagnostic tools from:
http://www.foolabs.com/xpdf/download.html

Use pdffonts <your-file.pdf> command to check if your pdf file has the embedded fonts.

 

Then follow instructions here:

http://www.boekenenproefschriften.nl/proefschriften/sites/default/files/EmbedLaTeXfonts.pdf

  1. latex file.tex (this produces file.dvi)
  2. dvips file.dvi (this produces file.ps)
  3. ps2pdf -dPDFSETTINGS=/prepress -dSubsetFonts=true -dEmbedAllFonts=true -dMaxSubsetPct=100 -dCompatibilityLevel=1.4 file.ps (this produces file.pdf)

Now run pdffonts file.pdf

EDIT:

Had a new problem – Acrobat version is less than 5.0″

>> change dCompatibilityLevel=1.3 to dCompatibilityLevel=1.4

Thanks to http://tientadinh.blogspot.com.au/2008/04/first-hand-experiences-with-author-kit.html for the fix.

Categories
Uncategorized

Best Android, WindowsPhone and iOS Development Tutorials

[quote]

Here are some of my favourite Android, WindowsPhone and iOS Development Tutorials.

[/quote]

 

Android

Derek Banas has the probably the best Android development tutorials that I’ve seen.  It’s been a few months now since I last saw his videos, but when I was beginning to learn Android programming I found his tutorials the best. Derek’s style is funny, informative and you can see he puts a lot of thought and effort into his examples.

Check out his YouTube Channel: http://www.youtube.com/user/derekbanas

iOS

Prof. Paul Hegarty of Stanford University has probably the BEST learning material on iOS development. He starts with an introduction to Objective-C and then delves into Model-View-Controller (MVC) paradigm. His teaching style is very immersive and gives practical examples and creates 4 or so apps during the course of the lessons.  His iOS 7 tutorial is linked below.

https://itunes.apple.com/us/course/developing-ios-7-apps-for/id733644550

iOS 8 has introduced a new programming language called Swift.  I haven’t searched for any tutorials on this, but I expect tutorials and lectures will be coming up soon.

WindowsPhone 8

Microsoft’s Channel 9 has the best WindowsPhone 8 development tutorials that I’ve come across. http://channel9.msdn.com/

I initially learned from the Jump Start tutorial by Andy Wigley and Rob Tiffany:

http://channel9.msdn.com/Series/Building-Apps-for-Windows-Phone-8-Jump-Start

These tutorials are newer, and from a quick glance, look thorough and well-structured.

http://channel9.msdn.com/Series/Building-Apps-for-Windows-Phone-8-1

http://channel9.msdn.com/Series/Windows-Phone-8-1-Development-for-Absolute-Beginners

 

Categories
Uncategorized

Building a Customer Management App Using AngularJS and Laravel (PART TWO)!

[THIS IS OUTDATED! I’M KEEPING IT HERE FOR HISTORICAL PURPOSES :). MOVE ONTO ANGULAR 2 AND LARAVEL 5!]

Single page apps with AngularJS are quite powerful, especially when you can consume a REST API.

angular-routing

I’ve been looking for some tutorials, and scotch.io [OLD BROKEN LINK] scotch.io [GOOD LINK] definitely have a super collection of tutorials and written in a well-thought out way for beginners and are beautifully presented.

I wanted a little more practice with Laravel and AngularJS, so I googled around and found this: Building a Customer Management App Using AngularJS and Laravel.

The tutorial is only half finished, and lots of people were complaining about it! So I thought of finding out how to complete it.

I had been googling around for CRUD stuff a few months ago and came across this: CRUD Grid Using AngularJS, WebAPI, Entity Framework (EF), Bootstrap, which was written for ASP.NET WebAPI, so I decided to port it for Laravel.

So, if you’ve already completed Part 1 of the tutorial on tutsplus, then there’s not much more you have to do!

Note that the steps below create an AngularJS CRUD for the customers table only.  I have not added functionality for the transactions table.

Step 1 – Modify your CustomerController.php – add a handler for the put method

public function putIndex() {
 $id = Input::get('id');

 if (Input::has('id', 'first_name', 'last_name', 'email')) {
 $input = Input::all();
 if ($input['first_name'] == '' || $input['last_name'] == '' || $input['email'] == '') {
 return Response::make('You need to fill all of the input fields', 400);
 }
 $customer = Customer::find($id);
 $customer->first_name = $input['first_name'];
 $customer->last_name = $input['last_name'];
 $customer->email = $input['email'];
$customer->save();

 return $customer;
 } else {
 return Response::make('You need to fill all of the input fields', 400);
 }
 }

Step 2 – AngularJS CRUD interface – create index.html as follows

<!doctype html> 
<html ng-app="app"> 
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.5/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.0/js/toastr.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap-theme.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/css/toastr.css">
<title>AngularJS-WebApi-EF</title>
</head> 
<body> 
 <div ng-controller="IndexCtrl" ng-cloak> 
 <div style="width: 500px;"> 
 <table class="table table-striped table-bordered table-condensed table-hover"> 
 <tr> 
 <th style="width: 100px;"> 
 <div class="btn-toolbar"><i class="glyphicon glyphicon-plus" ng-click="toggleAddMode()"></i></div> 
 </th> 
 <th style="width: 50px;">Id</th> 
 <th>First Name</th>
 <th>Last Name</th>
 <th>Email</th>
 </tr> 
 <tr ng-show="addMode"> 
 <td> 
 <div class="btn-toolbar"> 
 <div class="btn-group"> 
 <i class="glyphicon glyphicon-save" ng-click="addCustomer()"></i> 
 <i class="glyphicon glyphicon-remove" ng-click="toggleAddMode()"></i> 
 </div> 
 </div> 
 </td> 
 <td></td> 
 <td> 
 <input ng-model="customer.first_name" /></td>
 <td>
 <input ng-model="customer.last_name" /></td> 
 <td>
 <input ng-model="customer.email" /></td> 
 </tr> 
 <tr ng-repeat="customer in customers | orderBy:'id':true"> 
 <td> 
 <div class="btn-toolbar" ng-show="customer.editMode == null || customer.editMode == false"> 
 <div class="btn-group"> 
 <i class="glyphicon glyphicon-edit" ng-click="toggleEditMode(customer)"></i> 
 <i class="glyphicon glyphicon-trash" ng-click="deleteCustomer(customer)"></i> 
 </div> 
 </div> 
 <div class="btn-toolbar" ng-show="customer.editMode == true"> 
 <div class="btn-group"> 
 <i class="glyphicon glyphicon-save" ng-click="updateCustomer(customer)"></i> 
 <i class="glyphicon glyphicon-remove" ng-click="toggleEditMode(customer)"></i> 
 </div> 
 </div> 
 </td> 
 <td>{{customer.id}}</td> 
 <td> 
 <span ng-show="customer.editMode == null || customer.editMode == false">{{customer.first_name}}</span> 
 <input ng-model="customer.first_name" ng-show="customer.editMode == true" />
 </td>
 <td>
 <span ng-show="customer.editMode == null || customer.editMode == false">{{customer.last_name}}</span> 
 <input ng-model="customer.last_name" ng-show="customer.editMode == true" />
 </td>
 <td>
 <span ng-show="customer.editMode == null || customer.editMode == false">{{customer.email}}</span> 
 <input ng-model="customer.email" ng-show="customer.editMode == true" />
 </td> 
 </tr> 
 </table> 
 </div> 
 </div> 

 <script> 
 var app = angular.module('app', []); 

 var url = 'http://localhost/tutsplus/public/customers'; 

 app.factory('customerFactory', function ($http) { 
 return { 
 getCustomers: function () { 
 return $http.get(url + '/all'); 
 }, 
 addCustomer: function (customer) { 
 return $http.post(url, customer); 
 }, 
 deleteCustomer: function (customer) { 
 return $http.delete(url + '?id=' + customer.id); 
 }, 
 updateCustomer: function (customer) { 
 return $http.put(url + '?id=' + customer.id, customer); 
 } 
 }; 
 }); 

 app.factory('notificationFactory', function () { 

 return { 
 success: function () { 
 toastr.success("Success"); 
 }, 
 error: function (text) { 
 toastr.error(text, "Error!"); 
 } 
 }; 
 }); 

 app.controller('IndexCtrl', function ($scope, customerFactory, notificationFactory) { 
 $scope.customers = []; 
 $scope.addMode = false; 

 $scope.toggleAddMode = function () { 
 $scope.addMode = !$scope.addMode; 
 }; 

 $scope.toggleEditMode = function (customer) { 
 customer.editMode = !customer.editMode; 
 }; 

 var getCustomersSuccessCallback = function (data, status) { 
 $scope.customers = data; 
 }; 

 var successCallback = function (data, status, headers, config) { 
 notificationFactory.success(); 

 return customerFactory.getCustomers().success(getCustomersSuccessCallback).error(errorCallback); 
 }; 

 var successPostCallback = function (data, status, headers, config) { 
 successCallback(data, status, headers, config).success(function () { 
 $scope.toggleAddMode(); 
 $scope.customer = {}; 
 }); 
 }; 

 var errorCallback = function (data, status, headers, config) { 
 notificationFactory.error(data.ExceptionMessage); 
 }; 

 customerFactory.getCustomers().success(getCustomersSuccessCallback).error(errorCallback); 

 $scope.addCustomer = function () { 
 customerFactory.addCustomer($scope.customer).success(successPostCallback).error(errorCallback); 
 }; 

 $scope.deleteCustomer = function (customer) { 
 customerFactory.deleteCustomer(customer).success(successCallback).error(errorCallback); 
 }; 

 $scope.updateCustomer = function (customer) { 
 customerFactory.updateCustomer(customer).success(successCallback).error(errorCallback); 
 }; 
 }); 
 </script> 
</body> 
</html>

The HTML file above is self-contained and integrates the AngularJS controller and models in one file.  Usually it is better coding style to separate the files into the MVC (Model view controller) approach.

Here is what the final product looks like!

Screen Shot 2014-04-09 at 3.31.31 pm Screen Shot 2014-04-09 at 3.31.08 pm Screen Shot 2014-04-09 at 3.30.52 pm Screen Shot 2014-04-09 at 3.30.41 pm Screen Shot 2014-04-09 at 3.30.24 pm Screen Shot 2014-04-09 at 3.30.11 pm

Special thanks to Chris Sevilleja, Eduardo Pires and Maciej Sopyło for top tutorials and contributions!