uthc

My Experience in Programming

In avaluating any language script or prog
I look at how to separate blk code  first to debug
Python is uses tab indent used in Makefile for code blk separation and it hard to follow
Other language like C or Java use {} for  code blk and all my TextPad editor  provide brace match to jump from open { to close } quite easily
So it's so easy to folloe code blk under some statement like if for while ...
Next blk comment to comment out suspicious code block for debugging
Then how to print out for debugging purpose
I use only Textpad not IDE fot all languages
How to deal with Array for multi values holder
and how to use function in passing aray arg and returm array
Matrix is 2D array
In all languages like C Java treat matrix as array of array
All but C#
matrix[r][c] return item at index at row r and col c
So C# creator did the worst job !!??
The best language for matrix is Java, even C is hard to use for matrix
I cannot use C function return matrix using malloc
but Java is quite easy
///////////////////////////////////////////////////////////
public static int[][] matr(int rr, int cc)
{
int [][] mm= new int [rr][cc];
int r, c;
for(r=0; r<rr; r++)
{
System.out.printf("\n RRRRRRRRRRRRRRRRRRRRR |%d| #######################\n", r
);
for(c=0; c<cc; c++)
{
mm[r][c]=r*(rr+1)+c;
System.out.printf("%d, ", mm[r][c]);

}
}
return mm;
}

or just return array from Java method

return new int[]{year, month, day};

That's it To easy with Java ;-)


Java

int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
int nrow=
matrix.length;
int ncoll= matrix[0].length;
for(r=0; r<=nror; r++)
for(c=0; r<=ncol; c++)
System.out.printf("%d, ", matrix[[r][c])
);
 

So Python is certainly not of my choiceper its lack of blk statement
Both Java script and Java return Array very easy
Matlab also return multi var quite easy
just like function [u, v ]=abc( x, y, z)
and tab ident like make file hard to trace blk code cover by some control statement like for, while  if else elseif switch . . .

First thing comes first
I start programing in Fortran with pencil & paper in 1974
and found it's very comfort per my Math back ground
I don't like Python using tab indent like make file hard to follow blk of statement
So I like all script lang :Perl Bash JavaScript MLbut Python I like perl most even at a price to pu $ in front of all var but any way I don't ming using $ especially in helping the poor
All info herein canbe easily found by googling butthe following 1 cases  likely happnen
1) Adveritise with Malware
2) Most are unnecessirily too complicated toshow off the author can do thing quite complicated for scaring purpose While I truely believe

the simplest is the best the hardest to achieve

That's why I have this presentation
Would U plz kindly to email me any err in this content and recommend me the simpler implement

My MatLab Prog


Actually Iused free open Octave[OT] rather ML as ML cost few thousand USD to use while Octave is fully MLcompatible
ML creator MathWorks refused to make ML for Linux
So Linux guy created Octave to respond and we have MLfully compat Octave first created for Linux but eventually expanded to Wndw
Both were based on Linear package for matrix ops and on Javs for graphic plot
Both require JRE (Java Run Engine)) to run
ML is script language run by interpreter, not prog lang run by
Between 2 consecutive session old varvaluesare reused so it wise to put
clear on the top to ensure nosuch thing occur
ML use % for comment while OT use  #
Bck comment
%{
%}
#{
#}
ML does not require semi colon at end of statement
But semicolons used to supress value printed out
So it's easy to check var values either not put semicolon at the end of statement
Ot just put var name
xyz=12345 # 12345 not printed out
. . .

xyz # 42345 printed out


Plot

clear
x= 0:0.01: 2*pi;
figure
y_s =  sin(x);
y_c = cos (x );
plot(x, y_s, 'r*', x, y_c, 'b*'), grid; # grid for grid
title('Sin Cos') #title must be below plot ie naming after plotting
# set plot propeties like
set(gca, 'linewidth', 4, 'fontsize', 22, 'fontweight', 'bold' )
# legend just put all plot in order, it auto to display properly in order
  h = legend ('sin', 'cos','location', 'NorthEastOutside'); #Follow order in plot
#
NorthEastInside is default location , i.e if not using 'location' at all
 set (h, 'fontsize', 20, 'fontweight', 'bold');

pause( 2 ); # to keep OT open in 2secs for looking at plotfile:///D:/__D_WK/ML/Plot/sincos.png

3-d mesh Plot

tx = ty = linspace (-8, 8, 41)';#'
[xx, yy] = meshgrid (tx, ty);
r = sqrt (xx .^ 2 + yy .^ 2) + eps;
tz = sin (r) ./ r;
mesh (tx, ty, tz), grid;
title('3D plot mesh');
set(gca, 'linewidth', 4, 'fontsize', 22, 'fontweight', 'bold' )

pause(22)
Prg/mesh.jpg

mesh
file:///D:/__D_WK/ML/Plot/mesh.png


Array: Vector Matrix within [] idexed with () from 1 not 0

Print Out disp or fprintflike C printf with %c %d %f


FileIO

clear
x = 0:.1:1;
A = [x; exp(x)];

fileID = fopen('exp.txt','w');
fprintf(fileID,'%6s %12s\n','x','exp(x)');
fprintf(fileID,'%6.2f %12.8f\n',A);
fclose(fileID);



Elapsed Time with tic toc

Quite easily
tic
pause(1)
toc

Expense Sum

I frequently keep track my my expense on Amazon using my son Amzn card and put in M file to payback at ssa my_pay day
month start
xx ={
1.234 % when what

2.345 % when what
3.456 % when what
];
sum(xx)



Statements


clear
x=5
if 0<x<10 # blk till elseif
y=4*x
elseif 10<x<40 # blk till else
y = 10*x
else # blk till end
y = 500
end
I

switch n
case -1
disp(n)
fprintf('case %d', n)

disp('negative one')

case 0
disp(n)
fprintf('case %d', n)

case 1
disp(n)
fprintf('case %d', n)

otherwise
disp('other value')
end

clear
format long
pi # 3.141592653589793

format short with only 4 decimal digits
pi # ans = 3.1416
ML blk statement is from a statement to another or end

end can be used for blk or last index of Array
V=1:10;
V(end) #10
exit # exit right here for debugging purpose

Matrix Ops M [r,c]*M[c, n]

2 Matrices must have col = row of the one in multiply

Dot Ops

The best contribution of ML is DOT op, not DOT prodof 2 vector
lear
U=1:2;
V=3:4;
dot (U,V) # scalar 11=3*1+2*4=11dot prod of 2 vec
U.*V # Vector [3, 8=[1*3, 2*4] ele*ele


Function of single return y=abc(x, y, z) multi return [xx, yy]=abc(x, y, z) must ended with end Otherwise 2 func in the same file causing err of nested func


Sfu
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


function y = ss (x, b, a)
% y = ss (x,b, a) Note order per usage l
ikelihood, x first incase only ss(x) b 2nd incase ss(x, b) a last as optional used or not use(a=1
#if ss(a,x, b) then ss(x) causes err 'x' not found
#{
#}
switch (nargin)
case 1
y= 1./(1.+exp(-x));
return
a=-1;
b=0;

case 2
a=-1;
otherwise
a=-a;

end
x=a*(x-b);
y= 1./(1.+exp(x));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


For

for n=1:10
disp(n)
end

  pause( 2 ); # to keep OT open in 2secs for looking at plot
sincos
%




My C Programming


Why do I have to use more than 1 file
Just bcz I have to use printf a lot to readback for verification
and I use additional C file namely _VV.c compose of printf for all kind of types like string, char, str, double, namely str_vv(), int_vv(), dble_vv
This very file used in all my main C app
So I have 2 at minimum and occasionally 2 more for FileIO and Time called _FF.v and _TT.c
Likely I have at least 1 _VV.c and 2 additional _FF.c _TT.c
I started as a HW guy but trained myself SW to move on my responsible HW indecently rather waiting for SW availability
To me tomorrow is too late waiting for good or bad equally both uncomfortable
It turned out I could do SW better than SW guys
The secrete is adding HW stuff into HW is a serious action not like adding SW stuff
Per that culture my SW code is lean  only, of no fat so very neat and compact
In addition I have strong logical thinking built over years with math in high school and college where the simplest is the best and hardest to achieve
Messy math solution is absolutely not allowed at all Similarly messy code, aka Spaghetti code is absolutely not allowed
At one time I came across a story to train HW for SW job due to the shortage of SW suys At the end newly trained SW guys outperformed original SW guy
In additional a setup/hold time specs must be met for a proper  a read/write ops

In 12 years working at Symmetricom I wear both GW/SW hat(embedded Linux)




Make file should be used for muliple files
But it's so hard to use so I do my own way using #include
In the file inlude  __VV01.v Note _ in front for inc file
ifndef MAIN_VV // included only once

#define MAIN_VV main // main_vv if not used this varies per diff file
int MAIN_VV()
{
. . .
return 0;
}
#endif
In the main file XXX.c to ibclude  __VV01.v all inc file start with _ using #include as usual with H file
#include "fullpathto/_VV01.v" as  as usual with H file
.
.
.
int main()
{
.
.
.
}

 
In  decades since 2000
I have used cygwin with bash in place of junk DOS BAT
It come with GCC and perl
All C/Perl/Bash  in this notes using GCC from Cygwin32 running on my Win7-64b As Cygwin 64 is worse than Cygwin32 just copied ober from Win7-32 used in decade ago
This Cygwin32 can be gotten upon request as a ziped file just unziped and can be probably used on Win 10 just simply add cygwin/bin to the env Path

Brief on some popular programming Language

Compile Language"C[Functional] C# Java[Objected Oriented]

C is simple but powerful used in Linux kerl with million code line
Its simplicity help programmer focus on the main task not distracted by language complexity like C++/ Java
Java and C# look similar where
public static void main
All static vars must be used in main
Otherwise a constructor must be used Iprefer simple approach using static
Recently I worked on C drug monitor using time intensively
C Time is very confusing with overwhelming info like time() ascii time  time struct time
I just use number of seconds from time(0) aith struct time on local time to get DateTime
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
  time_t tt= time(0);
struct tm tm = *localtime(&tt);
sprintf(STR, "%d/%02d/%02d @ %02d|%02d|%02d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);


Elapsed Time [ET]


Getting done is only half of a success , theother half is how long
That's why I payvery serious to EP in all languages C/Java/C#
Perl/Python/Bash


Perl ET

 use Time::HiRes qw(usleep gettimeofday tv_interval);
$t0 = [gettimeofday];
sleep(1);
$elapsed = 1000*tv_interval($t0);
print"$elapsed mSec\n";

Bash ET

mS0=$(date +%s%N | cut -b1-13)
sleep 0.1
mS=$(date +%s%N | cut -b1-13)
(( et=mS - mS0 ))
echo "$et mSec"

Bash ET Sec even simpler just simply using $SECONDS

start=$SECONDS
sleep 1 # put some real task here instead of sleeping

duration=$(( SECONDS - start ))
echo "DURATION[$duration]"



Java ET

import java.util.*;
import java.lang.*;
import java.io.*;
import java.lang.Thread;


/* This is a simple Java program.
FileName : "HelloWorld.java". */
public class ET01
{
static long tt00=0;
////////////////////////////////////////////////////////
static int tt()
{
// static int y;
// return ++y;
return 1;
}
////////////////////////////////////////////////////////
static void wait_mili(int nn)
{
try
{
Thread.sleep(nn);
}
catch (Exception e)
{
}
} //wait_mili
////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////
static int NN=50;
static int cnt=0;

static long tt01;
static int tic_mili()
{
tt01 = System.currentTimeMillis();
int ett=(int)(tt01-tt00);
tt00 = System.currentTimeMillis();
return ett;

}
///////////////////////////////////////////////////////////////////

// Your program begins with a call to main().
// Prints "Hello, World" to the terminal window.
public static void main(String args[])
{
tic_mili();
wait_mili(NN);

int et=tic_mili();

System.out.printf("<%d>wait_mili(%d)<%d>mSec\n", cnt, NN, et);
} // main
} // class







FileIO

#include <stdio.h>

int main()
{
FILE *fp;
char ch;
char filename[33] = "d:/tmp/qik.txt";
char *content = "This text is appeneded later to the file, using C programming.";

/* open for writing */

printf("\nContents of %s -\n\n", filename);


fclose(fp);

fp = fopen(filename, "a+");// appnd & read
if(!fp)
{
printf("<<ERR>%s\n", "123456789\n", filename);
}

/* Write content to file */
fprintf(fp, "%s\n", "qwertyuiop\n");

fclose(fp);

fp = fopen(filename, "r");
}


//////////////////////////////////////////////////////////////////////
#include <stdio.h>// printf
#include <stdlib.h> // malloc
#include <time.h>
//#include <time.h>
char * _sec2dt(time_t tt) // convert sec to datetime str yyy/mo/dd @hh|mi|se
{
char *STR=(char *) malloc(55);
// time_t tt= 1691177032;
struct tm tm = *localtime(&tt);
sprintf(STR, "%d/%02d/%02d @ %02d|%02d|%02d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
return STR;

}
//////////////////////////////////////////////////////////////////////////
int main(int argc, char *argv[])
{
int tt=time(0); // num of seconds Unix Epoch since midnight January 1st, 1970 at UTC
char*dt=_sec2dt(tt);
printf("|%s| %s %s [GCC-%s]\n",argv[0], __DATE__, __TIME__, __VERSION__);

printf("DT{%s]\n", dt);
}

class Ex00
////////////////////////////////////////////////////////////////////////////////////////////////////////////
{
    static String Hello="Hello World";
    public void Ex00() // contrutor in case not static var
    {
//        System.out.printf("%s\n", Hello);

    }
///////////////////////////////////////////////////////////////////////////////////////////////
    public static void main(String[] args)

    {
        System.out.printf("%s\n", Hello);
//Ex00 ex00= new Ex00();
}
}




Script Language: Perl JavaScript MatLab



1974 I started programming with pencil& paper in Fortran at Tek Uni now known as https://hcmut.edu.vn/t

My 2nd language was Pascal in 1991 at UTS AUSTR
I love Math and it enhance my programming greatly and quikly
Over years
I learn C C++ C# Java Java Script Perl Python MatLab
To me the simplest is the best per my math bck grnd where simplification is a must
In Calculus Integration is very challenging especially in Trigonometry
And Simplification of Trigonotric Expression make the job quite easy and quite elegant
 
C appears to me as the best language per its simplicity and popular, but powerful
Is simplicity help me focus on the task not distracted by the code complexity
I have used C since 1994 mainly fin embeded SW
Recently I used C in desk top App to  build my daily use like drug monitor  mainly using text processing
I discover new feature in C as SW App like C reating a nonvolatile Array on HDD with offset of async binary FileIO as array index
I doubt if any serious SW guy see the diff between SW App and SW Embedded mainly for acessing  HW  Device
To copy File Rd/Wr File of a text File HTML of 1.55MB

Brief on Text processing by some prog lang

Switch statement does simply a lot to replace multi is else

Unfortunately Swich support only simple type like number not string
Java does support string switch nut not C
So for a remedy in C I use first char str[0]in str for str switch in C
I simplifies my C code in string a lot


T_P_rgx.htm1.55 MB (1,626,159 bytes)
C cpy File in   [25]mSec using 1024 buf 2048 buf in 16msec but bigger buf no impact
Perl File T_P_rgx.htm(59800)--> P01_T_P_rgx.html 5.704 mSec
BASH copy FileT_P_rgx.htm-->B_T_P_rgx.htm = 31 mS
 Java |./T_P_rgx.htm|(59801)-->|./J01_T_P_rgx02.htm| in <172> millisec
I attempted using C save text file as bin file but the speed not much improve
vs txt only just a bit quicker but not enought to makeup for the complexity in dealing with binary vs text
There're 2 ways in C FileIO for txt
For Red/Wr HTML file of 1.5M
157 mSec with Single char
193 mSec with 2 char
Number of Char
Time in mSec
1char
157
2char
193
3 char
110
4
100
5
64
6
57
7
50
8
46
9
43
10
33
11
39
12
38
13
36
14
36
15
35
16
33
17
33
18
32
19
31
20
31
21
30
22
30
23
32
24
32
25
32
26
32
27
32
28
32
29
32
30
32
31
32
32
32
33
32
34
32
35
32
36
32

single char

char c;

	while(c=fgetc(F_RD)!=EOF)
{
fputc(c, F_WR);
}

or

multiple char

#define MAX 0x1000

char tmp[MAX]
;

	while(fgets(tmp, MAX, F_RD))
{
// strcat(STR, tmp);

fputs(tmp, F_WR);
}
}

Perl is the fastest in only 6  mSec even faster than BASH Cygwin OS
Java is the slowest
The reason is Perl allows both Read/Write using Array only once read 1 write
$in_f = "${bf}.txt"; #  pd21-2 
$out_f = "_${bf}_01b.htm";
open(O_F, ">$out_f") ||
print"<ERR>>to make  $out_f \n";

open(IN_F, $in_f) ||
print"<ERR>>to GET  $in_f \n";

@AA00=<IN_F>;
print O_F $ss_htm; #string =array of char
close(O_F);

Time in C

Time in seconds should be be usedTo monitor drug taking
#include <time.h>
Struct tm is used to get DateTime from seconds
struct tm{
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;
};
It's simple to use second as time stamp
int tt=time(0);// save as drug taking
int diff= ime(0)-tt;
dd=sec/3600/24;//d
hr=sec/3600; // hr
sec-= hr*3600; //sec
mi=sec/60; //mi
Hr_Mi_Se[2]=se=sec-mi*60;
In reading text file to get time
<<NP>> 1691122058}
char *ret=strchr(str, ' ');
int tt=atoi(ret);
int dif = time(0)-tt;==> Dy Hr Mi Se


From TT ==>yyyy/mm/dd via struct tm
har * _ss_DT(time_t tt)
{
struct tm *TT = localtime(&tt);
TT->tm_year+=1900;
TT->tm_mon+=1;

char * str=(char *)malloc(55);
//void ST_VV(char *mm, struct tm *TT)
sprintf(str, "%d/%d/%d @ %d|%d|%d", TT->tm_year, TT->tm_mon, TT->tm_mday,
TT->tm_hour, TT->tm_min, TT->tm_sec);
return str;
}



Brief on Math processing by some Prg Lang

I I created aMath processing  benmarch to copute PI values using a huge number of Taylor deries of inverse Trigonometric arctan of tan
It's been quite known
tan( Pi/4)=1 ==>Pi=4*Atan(1)
cos(-1)=Pi
But as seen below Acos has factorial result in huge number at large number so cannot be used
I used 2 billion terms of Atan using both double of 8 bytes size and float of 4 bytes size  number in C C++ C# Java and Perl
Atan
acos

C[DBLE] 44 digit <116.143>Sec
C pi(2000000000)SZ|8|<116.143>Sec PI=3.1415926585050568675683280162047594785690310000000000000
C[FLOAT] 22 digit <114.786>Sec
C pi(2000000000)SZ|4|<114.786>Sec PI=3.1415967941284179687500000000000000000000000000000000000
CPP[FLOAT]24 digit <304.966>Sec
C pi(2000000000)SZ|4|<304.966>Sec PI=3.1415967941284179687500000000000000000000000000000000000
CPP [DBL] 44 <325.152>Sec
C pi(2000000000)SZ|8|<325.152>Sec PI=3.1415926585050568675683280162047594785690310000000000000




CPP[FLT]
C pi(2000000000)SZ|4|<304.966>Sec PI=3.1415967941284179687500000000000000000000000000000000000
CPP [DBL]
C pi(2000000000)SZ|8|<325.152>Sec PI=3.1415926585050568675683280162047594785690310000000000000


JAVA [FLT] PI(200000000) <30.788000>Sec

JAVA [DBL] PI(200000000) <30.549000>Sec
 PI [3.1415926485894077000000]


C# [FLT]
 PI(2000000000) <60>Sec== 3.141597

C# [DBL]
 PI(2000000000) <62>Sec== 3.14159265850518





Summary in cpmputing Pi with 2 billion terms of Atan using double IN C C++ C# JAVA

No Time Diff between using float and double
C/CPP report decimal digit 22|44 24|44 in [C]116 sec [C++]325 sex
But Java report 21/17 anormally  with more digits for float !! in 30sec
C# 8/16Perl in 980sec
Surprisingly Java is fastest per info from my SW partner with Java day 1 His 1st lang was Fortsns like mine in early 1960s with punchcard on main frame at at NASA-Goddard Space Flight Center in Greenbelt, MD. as s an  co-op student from  VA Tech.
that Java is very good in collecting gargage[memory release and seflf optimizedduring the run ??





C Array

 #include <stdio.h>
#include <stdlib.h>
int * getArr()
{
int * nn5=(int *)malloc(5*sizeof(int));
nn5[0]= 1;
nn5[1]= 2;
nn5[2]= 3;
nn5[3]= 4;
nn5[4]= 5;
return nn5;
}
int main()
{
int i=0;
int *NN= getArr();// no need storage like int NN[5] as it already allocated in function
printf("[%d]= %d\n", i++, NN[i]);
printf("[%d]= %d\n", i++, NN[i]);
printf("[%d]= %d\n", i++, NN[i]);
printf("[%d]= %d\n", i++, NN[i]);
printf("[%d]= %d\n", i++, NN[i]);
}



C# Array

using System;
namespace Hello
{
public class HelloWorld
{
static int [] getArr()
{
int [] Arr={-1, 3, 4, 5, 6};
return Arr;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////

public static void Main(string[] args)
{
int i=0;
int [] B=getArr();
Console.WriteLine ("{0}={1}", i, B[i]);
Console.WriteLine ("{0}={1}", i++, B[i]);
Console.WriteLine ("{0}={1}", i++, B[i]);
Console.WriteLine ("{0}={1}", i++, B[i]);
Console.WriteLine ("{0}={1}", i++, B[i]);
}
}
}



Java Array

public class Arr0
{

///////////////////////////////////////////////////////////////////////////////////////////////
static int[] getArr()
{

return new int[]{1, 2, 3, 4, 5};
} // getArr
///////////////////////////////////////////////////////////////////////////////////////////////

public static void main(String[] args)

{
int[] b=getArr();

for(int i=0; i<b.length;i++)
{
System.out.printf("[%d ] %d\n", i, b[i]);

}
}
}


Java Script JS

It's quite easy return Ary from  JS function just return using [ . . .]
function getArr()
{
return [u, vm x, y, z];
}
JavaScript run by Web Browser Chrome or FireFox either internal inside HTM or external via link
It is inter preted language with no type declared for variable
All variables are either char string or number in double
Its style very similar to C
All statements must be ended with ;
Blk stement wrapped within
{
. . .
}
A function is created  like below
function getArr(x, y, z)
{
return [ q, w, e, r, t, y, u, i];
}

External JS

<script src="_xyz.jss"></script>

Internal

<html>
<head>
<title><title>
<style>
. . .
</style>

<script>
. . .
</script>
</head>
<body>


Perl


Perl is interpreted language very powerful in text processing using excellent Regular Expression
IIts style very similar to C
All statements must be ended with ;
Blk stement wrapped within
{
. . .
}
All var must be pecedded with $
All function aka dubroutine has no arg ()
sub abc
{
$str= @_[0]; // 1st arg
$ln= @_[1];
$new= @_[2];

abc 1 2 3 // passing args to sub abc






  1. C progrm