BCS c++ Class Source Code Generator

This application creates a new c++ class (header and cpp file). A dialog allows the user to supply the target for the source and new module name and a new class name.

The resulting header file is depicted below.

/*
 * newclassh.h
 *
 *  Created on: Apr 5, 2018
 *      Author: Mr. Arch Brooks
 */
 
#ifndef NEWCLASSH_H_
#define NEWCLASSH_H_
 
/**
 * This is some test Doc Text
 */
 
class ncl {
 
/**
 * Private  Declarations Go Here
 */
 
private:
 
/**
 * Public  Declarations Go Here
 */
 
public:
	void gui();
	void mainProc();
};
 
#endif /* NEWCLASSH_H_ */

The associated c++ file is depicted below.

/*
 * newclassh.cpp
 *
 *  Created on: Apr 5, 2018
 *      Author: Mr. Arch Brooks
 */
 
#include "newclassh.h"
 
using namespace std; // @suppress("Symbol is not resolved")
 
void ncl::gui(){
 
}
void ncl::mainProc(){
 
}

This simple code generator reads skeleton files and scripts them in order to produce newly created source code.

Mr. Arch Brooks, Software Engineer, Brooks Computing Systems, LLC authored this article.

BCS Create Django Admin

To create and administration site for you models you must first establish a super user by issuing the following command in the project directory.

python3 manage.py createsuperuser

The results of issuing the command is as follows.

Superuser created successfully is the desired result.

Modify the admin.py in your application directory to reflect the following.

from django.contrib import admin
from .models import Post
 
# Register your models here.
 
admin.site.register(Post)

Start the server and bring up the administration web site.

python3 manage.py runserver

In the browser issue the following command.

http://localhost:8000/admin

When prompted to login use the credentials created when you established the superuser.

Mr. Arch Brooks, Software Engineer, Brooks Computing Systems, LLC authored this article.

BCS Create Django Application

Return to the project location in terminal and issue the following command.

django-admin startapp blog

In the terminal application change directories to current application sub directory.

Modify models.py to define the tables in question.

All the associated field descriptions can be reviewed by clicking here.

After the tables have been defined use the following command to make migrations.

b

python3 manage.py makemigrations blog

The following depicts the output from the command.

We should apply all migrations to the database by issuing the following command.  Return to the project root and issue the following command.

python3 manage.py migrate

The result of the following command is as follows.

Mr. Arch Brooks, Software Engineer, Brooks Computing Systems, LLC authored this article.

BCS Create Django Site with MySQL Backend

For those times when Django site need to support MySQL this tutorial may be helpful.

The first task is to create the Django project. Go to the command prompt and issue the following command.

django-admin startproject mysite

The result may be observed in the following screen shot.

Next we should allow the MySQL connection.  Firs we need to import the MySQL interface by including the two statements below into settings.py for your project.

import pymysql 
pymysql.install_as_MySQLdb()

Next declare the default database description to point to the correct MySQL database by incorporating the following lines.

'ENGINE': 'django.db.backends.mysql', 
  'NAME': 'pblog', 
  'USER' : 'bcs', 
  'PASSWORD' : 'YourPassword', 
  'HOSTS' : 'localhost', 
  'PORT' : '3306',

After the chages are incorporated the resulting settigs.py file reflects the following.

"""
Django settings for mysite project.
 
Generated by 'django-admin startproject' using Django 1.11.8.
 
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
 
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
 
import os
import pymysql
pymysql.install_as_MySQLdb()
 
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 
 
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
 
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'r8=&&1s%@60c%&cffq(bb54%_=px-@z=z#(htd!)jo^ny8xy9j'
 
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
 
ALLOWED_HOSTS = []
 
 
# Application definition
 
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]
 
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
 
ROOT_URLCONF = 'mysite2.urls'
 
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
 
WSGI_APPLICATION = 'mysite2.wsgi.application'
 
 
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
 
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'pblog',
        'USER' : 'bcs',
        'PASSWORD' : 'YourPassword',
        'HOSTS' : 'localhost',
        'PORT' : '3306',
    }
}
 
 
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
 
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]
 
 
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
 
LANGUAGE_CODE = 'en-us'
 
TIME_ZONE = 'UTC'
 
USE_I18N = True
 
USE_L10N = True
 
USE_TZ = True
 
 
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
 
STATIC_URL = '/static/'

We should start the server to determine the correctness of our configuration.

python manage.py runserver

Notice the server is running at the prescribed location.

The final step to this portion of the process is to migrate the database by issuing the following command.

python3 manage.py migrate

After the migration is successful you should have similar output messages in your terminal session.

Mr. Arch Brooks, Software Engineer, Brooks Computing Systems, LLC authored this article.

BCS c++ App That Creates Eclipse c++ Project And Class

This application accepts a workspace path, family id and class name to create a fully functional Eclipse Oxygen c++ project.

After this application executes the developer should import the newly created project into the Eclipse Oxygen IDE for c++ and continue developing the application.

Initially all libraries for GTK3+ (via gtkmm), Boost and other capabilities are available as well as some custom routines which are useful for in the design and coding of c++ applications.

What is generated is the complete project development environment and the source code for the mainline as well as aforementioned class.  This is accomplished by using a completed project as a template  while simultaneously creating and naming all component parts based on the family id and the class name provided.

Below is the structure to suppling input to the application.

struct gen_params {
	string projHome = "/home/archman/workspace/cpp/";
	string famId = "Gen01";
	string clas = "cl01";
};

Here is the main flow for accomplishing this task.

void utils::gen02(gen_params gp) {
	cout << "In Gen 02" << endl;
	utils::forceDirectories(gp.td + "Debug");
	utils::forceDirectories(gp.td + "src");
	utils::forceDirectories(gp.td + ".settings");
	utils::fileCopy("/home/archman/workspace/cpp/skelp/.cproject",
			gp.td + ".cproject");
	utils::fileCopy("/home/archman/workspace/cpp/skelp/.project",
			gp.td + ".project");
	utils::fileCopy("/home/archman/workspace/cpp/skelp/.settings/language.settings.xml", gp.td + ".settings/language.settings.xml");
	utils::fileCopy("/home/archman/workspace/cpp/skelp/Debug/makefile", gp.td +"Debug/makefile");
	utils::fileCopy("/home/archman/workspace/cpp/skelp/Debug/objects.mk", gp.td +"Debug/objects.mk");
	utils::fileCopy("/home/archman/workspace/cpp/skelp/Debug/sources.mk", gp.td +"Debug/sources.mk");
	utils::forceDirectories(gp.td + "Debug/src/");
	utils::fileCopy("/home/archman/workspace/cpp/skelp/Debug/src/subdir.mk", gp.td +"Debug/src/subdir.mk");
	mod_rec mr;
	utils::init_repl(mr, gp);
	string str[sizeOfStringArray];
	int lcnt;
	lcnt = utils::fin("/home/archman/workspace/cpp/skelp/src/skelp.cpp", str);
	utils::upd(mr, str, lcnt);
	utils::fot(gp.td + "src/" + gp.famId + "p.cpp", str, lcnt);
	lcnt = utils::fin("/home/archman/workspace/cpp/skelp/src/skelh.h", str);
	utils::upd(mr, str, lcnt);
	utils::fot(gp.td + "src/" + gp.famId + "h.h", str, lcnt);
	lcnt = utils::fin("/home/archman/workspace/cpp/skelp/src/skelh.cpp", str);
	utils::upd(mr, str, lcnt);
	utils::fot(gp.td + "src/" + gp.famId + "h.cpp", str, lcnt);
}

The following structure identifies the replacement values from the skeleton template to the newly generated source code.

void utils::init_repl(mod_rec& mr, gen_params gp) {
	mr.numPair = 3;
	mr.mp[0].from = "skelp";
	mr.mp[0].to = gp.famId + "p";
	mr.mp[1].from = "skelh";
	mr.mp[1].to = gp.famId + "h";
	mr.mp[2].from = "SKELH";
	mr.mp[2].to = boost::to_upper_copy(gp.famId + "h");
	mr.mp[3].from = "utils";
	mr.mp[3].to = gp.clas;
}

 
The workhorse to the application is the section of code listed below.

void utils::upd(mod_rec rmrp, string stv[sizeOfStringArray], int cnt) {
	int ii = rmrp.numPair;
	string rline;
	int j = 0;
	while (j < cnt) {
		int i = 0;
		while (i <= ii) {
			boost::replace_all(stv[j], rmrp.mp[i].from, rmrp.mp[i].to);
			i++;
		}
		rline = stv[j];
		j++;
	}
}

 
The initial loop goes through each line of source code in the subject file. The innermost loop iterates from the first replacement pair until the last replacement pair is processed. This process is repeated until all lines in the subject source code is processed.

 

Mr. Arch Brooks, Software Engineer, Brooks Computing Systems, LLC authored this article.

BCS Django Twitter Bootstrap


Django and the Twitter Bootstrap offers the ultimate environment for web development for multiple devices.

Create the project.

django-admin startproject yourAppName

Allow the appropriate access by updating the following in settings.py file.

ALLOWED_HOSTS = ['109.203.114.78', 'localhost', 'archbrooks.us']

Now configure the desired database.  Special imports are required for MySQL.

import pymysql
pymysql.install_as_MySQLdb()

Now include the database configuration parameters.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'YourDB',
        'USER' : 'YourUser',
        'PASSWORD' : 'Password',
        'HOSTS' : '',
        'PORT' : '',
    }
}

At this point I would start the server to check for errors.
python manage.py runserver 0.0.0.0:8000

The next step is to install the Twitter Bootstrap.
pip install django-twitter-bootstrap

The following is generated after sucessful install of bootstrap.
Enter root@server:~/django/nws# pip install django-twitter-bootstrap
Collecting django-twitter-bootstrap
  Downloading django-twitter-bootstrap-3.3.0.tar.gz (156kB)
    100% |████████████████████████████████| 163kB -276578bytes/s
Building wheels for collected packages: django-twitter-bootstrap
  Running setup.py bdist_wheel for django-twitter-bootstrap ... done
  Stored in directory: /root/.cache/pip/wheels/7b/b2/e7/93eebb9195c2f80c83ce543768b99629c3da5ec89fb81bfb1b
Successfully built django-twitter-bootstrap
Installing collected packages: django-twitter-bootstrap
Successfully installed django-twitter-bootstrap-3.3.0
code here

Now create the first application of the site.
django-admin startapp myapp

At this point I would start the server to check for errors.

python manage.py runserver 0.0.0.0:8000

If no errors were reported you are now ready to activate the first page of your site.

Modify the urls.py file for the application to reflect the following:

from django.conf.urls import include, url
from django.contrib import admin
from mws import views
 
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^admin/', include(admin.site.urls)),
]

 

Mr. Arch Brooks, Software Engineer, Brooks Computing Systems, LLC authored this article.

BCS Yii2 Skeleton

The basic web site installation should be modified to enable pretty url’s.

Modify config web.php to turn pretty url’s on.

'components' => [
    // ...
    'urlManager' => [
        'class' => 'yii\web\UrlManager',
        // Hide index.php
        'showScriptName' => false,
        // Use pretty URLs
        'enablePrettyUrl' => true,
        'rules' => [
        ],
    ],
    // ...
],

The next step is to place a .httpaccess file in the web directory.

RewriteEngine on
# If a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward it to index.php
RewriteRule . index.php

You should also update the cookie key in the config web.php file.

<?php
 
$params = require(__DIR__ . '/params.php');
$db = require(__DIR__ . '/db.php');
 
$config = [
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'components' => [
        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => 'AMBSecretKey',
        ],
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'user' => [
            'identityClass' => 'app\models\User',
            'enableAutoLogin' => true,
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => true,
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'db' => $db,
 
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
            ],
        ],
 
    ],
    'params' => $params,
];
 
if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = [
        'class' => 'yii\debug\Module',
        // uncomment the following to add your IP if you are not connecting from localhost.
        //'allowedIPs' => ['127.0.0.1', '::1'],
    ];
 
    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = [
        'class' => 'yii\gii\Module',
        // uncomment the following to add your IP if you are not connecting from localhost.
        //'allowedIPs' => ['127.0.0.1', '::1'],
    ];
}
 
return $config;

To complete the basic modifications change all references from “My Company” to something more suitable in the main.php file.

Below is the main.php with all the occurrences changed.

<?php
 
/* @var $this \yii\web\View */
/* @var $content string */
 
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use app\assets\AppAsset;
 
AppAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
    <meta charset="<?= Yii::$app->charset ?>">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?= Html::csrfMetaTags() ?>
    <title><?= Html::encode($this->title) ?></title>
    <?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>
 
<div class="wrap">
    <?php
    NavBar::begin([
        'brandLabel' => 'Brooks Computing Systems, LLC',
        'brandUrl' => Yii::$app->homeUrl,
        'options' => [
            'class' => 'navbar-inverse navbar-fixed-top',
        ],
    ]);
    echo Nav::widget([
        'options' => ['class' => 'navbar-nav navbar-right'],
        'items' => [
            ['label' => 'Home', 'url' => ['/site/index']],
            ['label' => 'About', 'url' => ['/site/about']],
            ['label' => 'Contact', 'url' => ['/site/contact']],
            Yii::$app->user->isGuest ? (
                ['label' => 'Login', 'url' => ['/site/login']]
            ) : (
                '<li>'
                . Html::beginForm(['/site/logout'], 'post')
                . Html::submitButton(
                    'Logout (' . Yii::$app->user->identity->username . ')',
                    ['class' => 'btn btn-link logout']
                )
                . Html::endForm()
                . '</li>'
            )
        ],
    ]);
    NavBar::end();
    ?>
 
    <div class="container">
        <?= Breadcrumbs::widget([
            'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
        ]) ?>
        <?= $content ?>
    </div>
</div>
 
<footer class="footer">
    <div class="container">
        <p class="pull-left">&copy; Brooks Computing Systems, LLC <?= date('Y') ?></p>
 
        <p class="pull-right"><?= Yii::powered() ?></p>
    </div>
</footer>
 
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>

These modifications should supply a reasonable base line for subsequent Yii2 development

Mr. Arch Brooks, Software Engineer, Brooks Computing Systems, LLC authored this article.

BCS Java Date Difference

There are may solution to Java challenges. Today our challenge surrounds calculating elapsed years, months, days, hours, minuets and seconds between two dates.

The primary workhorse for this task is JodaTime utility. Click on the Releases option and the Downloads sub option to download jars and utilities. Simply add the downloaded jar to tour Java project and you are ready for action.

package dtt;
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
import org.joda.time.Interval;
import org.joda.time.Period;
 
public class ft {
 
	public static void main(1.5.0/docs/api/java/lang/String.html">String[] args) {
 
		1.5.0/docs/api/java/text/SimpleDateFormat.html">SimpleDateFormat simpleDateFormat = new 1.5.0/docs/api/java/text/SimpleDateFormat.html">SimpleDateFormat("dd/M/yyyy hh:mm:ss");
 
		try {
 
			5+0%2Fdocs%2Fapi+Date">Date date1 = simpleDateFormat.parse("10/10/2016 11:30:10");
			5+0%2Fdocs%2Fapi+Date">Date date2 = simpleDateFormat.parse("13/11/2017 20:35:55");
 
			// obj.printDifference(date1, date2);
			printDifference(date1, date2);
 
		} catch (1.5.0/docs/api/java/text/ParseException.html">ParseException e) {
			e.printStackTrace();
		}
	}
 
	public static void printDifference(5+0%2Fdocs%2Fapi+Date">Date startDate, 5+0%2Fdocs%2Fapi+Date">Date endDate) {
 
		Interval interval = new Interval(startDate.getTime(), endDate.getTime());
		Period period = interval.toPeriod();
 
		1.5.0/docs/api/java/lang/System.html">System.out.println("  Start Date : " + startDate.toString());
		1.5.0/docs/api/java/lang/System.html">System.out.println("    End Date : " + endDate.toString());
		1.5.0/docs/api/java/lang/System.html">System.out.printf("Elapsed Time : " + "%d years, %d months, %d days, %d hours, %d minutes, %d seconds%n", period.getYears(),
				period.getMonths(), period.getDays(), period.getHours(), period.getMinutes(), period.getSeconds());
	}
}

The execution of the program is listed below.

Mr. Arch Brooks, Software Engineer, Brooks Computing Systems, LLC authored this article.

BCS Install Oracle JDK On Linux Mint

OpenJDK does not support JavaFX while Oracle JDK does contain support for FX.  Installation of Oracle JDK on Mint is required.

To proceed with installation of Oracle JDK issue the following command.

sudo apt-get update && apt-get remove openjdk*

Traverse to the location where JDK is stored.

cd ~/Downloads

Unzip the JDK with the following command.

tar -zxvf jdk-8u131-linux-x64.tar.gz

Create a permanent directory for the JDK.

sudo mkdir -p /opt/java

Next send the JDK to its permanent location by issuing the following command.

sudo mv jdk1.8.0_131 /opt/java

Install the JDK bu issuing the following command.

sudo update-alternatives --install "/usr/bin/java" "java" "/opt/java/jdk1.8.0_131/bin/java" 1

Set JDK Alternatives as follows.

sudo update-alternatives --set java /opt/java/jdk1.8.0_131/bin/java

Finally check the the version information.

$ java -version

You have successfully installed the Oracle JDK on Linux Mint.

Mr. Arch Brooks, Software Engineer, Brooks Computing Systems, LLC authored this article.

BCS Virtual Box On Mint

is computer software, firmware or hardware that creates and runs virtual machines. A computer on which a hypervisor runs one or more virtual machines is called a host machine, and each virtual machine is called a guest machine. The hypervisor presents the guest operating systems with a virtual operating platform and manages the execution of the guest operating systems. Multiple instances of a variety of operating systems may share the virtualized hardware resources: for example, Linux, Windows, and macOS instances can all run on a single physical x86 machine. This contrasts with operating-system-level virtualization, where all instances (usually called containers) must share a single kernel, though the guest operating systems can differ in user space, such as different Linux distributions with the same kernel.

Mr. Arch Brooks, Software Engineer, Brooks Computing Systems, LLC authored this article.