How To Open $ionicPopover Popup from Controller

How To Open $ionicPopover from Controller programmatically without a mouse click event:


var self = this; // store reference to 'this' controller object

this.openCustomPopover = function ($event) {

        $event = document.getElementsById('myElementID'); // html element ID 

        $ionicPopover.fromTemplateUrl('popovers/myhtmlpopover.html', {
                scope: $scope
            }).then(function (popover) {
                console.log('in the popover then function');
                self.popover = popover;
                self.popover.show($event);
            });
        }

You can call this function from your controller without a true click event, by faking the $event object.

How to Display and Format Code Snippets on WordPress

How to Display and Format Code Snippets on WordPress ?

What I use is Pretty print, and it’s very simple to setup.

1. Include this script in your header run_prettify.js

2. Start your code with the pre tag

<pre class="prettyprint">
class Voila {
public:
  // Voila
  static const string VOILA = "Voila";

  // will not interfere with embedded tags.
}
</pre>

More information at https://github.com/google/code-prettify

How to Dynamically Load Dark Mode CSS with JavaScript

How to Dynamically Load Dark Mode CSS in your Website or WebApp (Ionic, React, or Angular):

1. Create the two separete css files, one for dark colors and one for bright
2. Upload those to your server to css folder
3. Use the script example below to load the appropriate css file based on the hours in the day.


function loadcssfile(filename, filetype){
    if (filetype=="css"){ //check filename is an external CSS file
        var fileref=document.createElement("link");
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("href", filename);
    }
    if (typeof fileref!="undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref);
}

var date = new Date();

 if (date.getHours() >= 19 || date.getHours() <= 7) // after 7pm before 7am
	loadcssfile("../css/darkmode.css", "css");
 else
	loadcssfile("../css/lightmode.css", "css");

Don't blind your readers at night -_-

If you want to incorporate sunset and sunrise you can look into Suncal library, but you will have to request user's location which is always rude and not recommended.

How to fork and pipe multiple processes on Linux

The C code here is used for reference of how to pipe 3 separate children processes. It can be improved to support a dynamic amount of processes and corresponding pipes and system calls.

// This program is an example of how to run a command such as
// ps aux | grep root | grep sbin
// using C and Unix.
// pipe_example.c

#include 
#include 
#include 

int pid;
int pipe1[2];
int pipe2[2];

void exec1();
void exec2();
void exec3();

int main()
{

	// create pipe1
	if (pipe(pipe1) == -1)
	{
		perror("bad pipe1");
		exit(1);
	}

	// create pipe2
	if (pipe(pipe2) == -1)
	{
		perror("bad pipe2");
		exit(1);
	}

	// fork (ps aux)
	if ((pid = fork()) == -1)
	{
		perror("bad fork1");
		exit(1);
	}
	else if (pid == 0)
	{
		// stdin --> ps --> pipe1
		exec1();
	}
	// parent

	// fork (grep root)
	if ((pid = fork()) == -1)
	{
		perror("bad fork2");
		exit(1);
	}
	else if (pid == 0)
	{
		// pipe1 --> grep --> pipe2
		exec2();
	}
	// parent

	// close unused fds
	close(pipe1[0]);
	close(pipe1[1]);

	// fork (grep sbin)
	if ((pid = fork()) == -1)
	{
		perror("bad fork3");
		exit(1);
	}
	else if (pid == 0)
	{
		// pipe2 --> grep --> stdout
		exec3();
	}
	// parent
}

void exec1()
{
	// input from stdin (already done)
	// output to pipe1
	dup2(pipe1[1], 1);
	// close fds
	close(pipe1[0]);
	close(pipe1[1]);
	// exec
	execlp("ls", "ls", NULL);
	// exec didn't work, exit
	perror("bad exec ls");
	_exit(1);
}

void exec2()
{
	// input from pipe1
	dup2(pipe1[0], 0);
	// output to pipe2
	dup2(pipe2[1], 1);
	// close fds
	close(pipe1[0]);
	close(pipe1[1]);
	close(pipe2[0]);
	close(pipe2[1]);
	// exec
	execlp("grep", "grep", "c", NULL);
	// exec didn't work, exit
	perror("bad exec grep c");
	_exit(1);
}

void exec3()
{
	// input from pipe2
	dup2(pipe2[0], 0);
	// output to stdout (already done)
	// close fds
	close(pipe2[0]);
	close(pipe2[1]);
	// exec
	execlp("grep", "grep", "y", NULL);
	// exec didn't work, exit
	perror("bad exec grep y");
	_exit(1);
}

This code also works on Unix/Mac.
Compile with gcc pipe_example.c -o pipe_example.o
Run with ./pipe_example.o

Creating and Opening PDF on Ionic 1 on iOS

Recently I ran into an issue using the PdfMake on Ionic 1 on iOS. It works fine on the browser with a simple download or open command but not on the actual device.

Install the cordova libraries:

cordova.plugins.fileOpener2
cordova-plugin-file

Download the pdfmake javascript files and include them in your index.html

<script src='build/pdfmake.min.js'></script>
<script src='build/vfs_fonts.js'></script>

The code:

  var self = this ; // defined on top of the file

  var docDefinition = { content: 'This is an sample PDF printed with pdfMake' };

            self.pdfObj = pdfMake.createPdf(docDefinition);

            if (window.cordova) {
                self.pdfObj.getBuffer(function (buffer) {
                    var blob = new Blob([buffer], { type: 'application/pdf' });
                    // Save the PDF to the data Directory of our App
                    $cordovaFile.writeFile(cordova.file.dataDirectory, 'myletter.pdf', blob, { replace: true }).then(function () {
                        // Open the PDf with the correct OS tools
                        cordova.plugins.fileOpener2.open(cordova.file.dataDirectory + 'myletter.pdf', 'application/pdf');
                    })
                });
            }

Setup Config.xml

In your config.xml make sure you have the file settings

<preference name="AndroidPersistentFileLocation" value="Compatibility" />
<preference name="iosPersistentFileLocation" value="Library" />

How To Use Ionic & Angular q Promises?

The Deferred API

A new instance of deferred is constructed by calling $q.defer().

The purpose of the deferred object is to expose the associated Promise instance as well as APIs that can be used for signaling the successful or unsuccessful completion, as well as the status of the task.

Methods

resolve(value) – resolves the derived promise with the value. If the value is a rejection constructed via $q.reject, the promise will be rejected instead.

reject(reason) – rejects the derived promise with the reason. This is equivalent to resolving it with a rejection constructed via $q.reject.

notify(value) – provides updates on the status of the promise’s execution. This may be called multiple times before the promise is either resolved or rejected.
Properties

promise – {Promise} – promise object associated with this deferred.

// for the purpose of this example let's assume that variables `$q` and `okToGreet`
// are available in the current lexical scope (they could have been injected or passed in).

function asyncGreet(name) {
  var deferred = $q.defer();

  setTimeout(function() {
    deferred.notify('About to greet ' + name + '.');

    if (okToGreet(name)) {
      deferred.resolve('Hello, ' + name + '!');
    } else {
      deferred.reject('Greeting ' + name + ' is not allowed.');
    }
  }, 1000);

  return deferred.promise;
}

var promise = asyncGreet('Robin Hood');
promise.then(function(greeting) {
  alert('Success: ' + greeting);
}, function(reason) {
  alert('Failed: ' + reason);
}, function(update) {
  alert('Got notification: ' + update);
});

This code example was taken from Angular Documentation page: https://docs.angularjs.org/api/ng/service/$q