Monday, January 28, 2019

Java Variables, Conditionals, Loops, Functions, just a bit.

Java Data Types
import java.awt.*;

Public class example {

    boolean abool = true;
    char letter = 'A';
    byte abyte;
    short ashort;
    int aint = 0;
    long along = 123456000;
    Long anotherL = 123456000 ; // Unsigned 64 bits
    float afloat = 33.55f;
    double adouble = Math.PI;

    String astring = "This is a string.";
    Color acolor = Color.RED;

}
Conditionals
# Example conditionals
public class howold {
    public static void main (String[] args) {

        String name;
        int age;
        Scanner in = new Scanner(System.in);
        System.out.println ("Hello, Please enter your name and age.");
        name = in.nextLine();
        age = in.nextInt();
        System.out.println ("Hello, " + name + ", \n\tyou are " + age + " years old.");

        if (age < 3) {
            System.out.println ("Are you sure?");
        }
    }
}

# more examples
public class howold {
    public static void main (String[] args) {

        String s = "";
        if ( s == "string" ) {
            System.out.println ("This is a string.");
        } else if ( s == "not a string" ) {
            System.out.println ("This is not a string.");
        } else {
            System.out.println ("What is this?");
        }
    }
}
Exercise: Print different greetings for people at different ages.

Loops
# Example loops
class example {
    public static void main (String[] args) {
        for (String s : args ) {
            System.out.println ( s );
        }
    }
    String s = "";
    for (int i = 0; i <10; i++) {
        s += 'A';
    }
}

class testloops {
    // Do/whil (post-test) 
    // While (pre-test)
    // for (pre-test)

    public void loopwhile () {
        int loop_count = 3;
        while ( loop_count > 0 ) {
            System.out.println ( loop_count );
            loop_count--;
        }
    }
    
    public void loopdowhile () {
        int loop_count = 3;
        do {
            System.out.println ( loop_count );
            loop_count--;
        } while ( loop_count > 0 );
    }
}
Functions
# Example functions
    public static void main (String[] args) {
        thisfunc ( 3, "testfunc" );
    }

    public static void thisfunc ( int i, String s) {
        System.out.println ( i );
        System.out.println ( s );
    }
Exceptions
# Example exceptions
    public static void main (String[] args) {
        int first;
        if (args.length > 3) {
            try {
                first = Integer.parseInt (args[0]);
            }
            catch (NumberFormatException e) {
                System.err.println ("Error: too many arguments.");
                System.exit(1);
            }
        }
    }
}

Friday, January 18, 2019

C++ Editor and IDE.

What features should I care in IDE?
Code Editor - syntax, auto-completion, templates
Compiler - converts source code according to a language 
           understood by the computer OS system.
Debugger - make it easy to analyze and make changes in a program.
Do I have C++ Compiler installed?
gcc -version
cc -vresion
c++ -version
g++ -version
How do I download C++ Compiler?
https://www.oracle.com/technetwork/java/javase/downloads/index.html
Click to start!
Code::Block IDE
http://www.codeblocks.org/downloads
Click here to Start!
CodeLite IDE
https://downloads.codelite.org/
Click here to Start!
Editor Shortcuts
Eclipse IDE for C++
eclipse.org
Click to start!
NetBean IDE 8.2 for C++
https://netbeans.org/features/cpp/
Click here to Start!
Netbeans IDE
https:/netbeans.org
Click to start!
IDE ShortCuts

Friday, January 4, 2019

Java literals!

Numbers, Strings, and Boolean
# Example
boolean x = true;    // 1 bit
boolean x = false;   // 1 bit
byte b = 1;          // 1 byte
short sh = 1;        // 2 byte
int x = 1;           // 4 byte
long l = 1L;         // 8 byte
float f = 1f;        // 4 byte
double d = 1d;       // 8 byte
char ch = 'a';       // 2 byte unicode

String x = "string";

# each of the primitive type has a helper/wrapper class
Boolean x;
Byte b;
Integer x;
Long l;
Float f;
Double d;
Character ch;
Java cast/convert types
// widing number is automatic, narrowing is not
int i = 789;
long li = i;
short si = (short) i;
int b = 1024;
byte bt = b;               // error
byte bt2 = (byte) b;       // lose data that overflows
double d = 2.88888888;
int di = (int) d;          // lose decimals
Prefix vs Postfix Incrementing or Decrementing
i++
++i
j--
--j
Java print can mix types.
# Example
int a = 1;
int b = 2;
String s = "string";
char[] cstring = "this is a string".toCharArray();

System.out.print ( a );
System.out.print ( a,b );
System.out.print ( s );
System.out.print ( " The number is " + 123 );
System.out.println ( cstring );
Operators
# Example
int x = 0, y = 0, z = 0;
x = x + 1;
x += 1;
x -= 1; 
y = x / 3;
y = x % 3;
x *= y + z;
x = x * (y+z);
x /= y + z;
x = x / (y+z);
What do you think this will do?
x =+ 5
y =- 3
Java print allows you to mix different types.
int x = 0, y = 0;
x =+ 5;
y =- 3;
System.out.println( " x : " + String.valueOf(x) );
System.out.println( " x : " + Integer.toString(x) );
System.out.println( " x : " + x );
System.out.println( y );
x += 5;
y -= 3;
System.out.println( x );
System.out.println( y );

// System.out.println( " x : " , x ); // Error!! But it works in Python

First Java Program!

Hello!
public class hello {

        public static void main(String[] args) {
                System.out.println("Hello World!");
        }

}
Data types
import java.awt.*;
import java.util.Scanner;

public class hello {

        public static void main(String[] args) {
                System.out.println("hello");

                int i;
                double d;
                String s = "my string";
                boolean b;
                char c = s.charAt(0);
                String us = s.toUpperCase();
                Color mycolor = Color.RED;

                Scanner sc = new Scanner (System.in);
                System.out.print ("Enter anything: ");
                String ui = sc.next();
                System.out.print ("Enter a number: ");
                int userNumber = sc.nextInt();
                System.out.print ("Enter a floating number: ");
                double userFP = sc.nextDouble();

                System.out.println (s);
                System.out.println (us);
                System.out.println (ui);
                System.out.println (ui.contains ("xxx"));

        }
}
comments
// this is comments
/* this is comments for multiple lines
*/
Java IO
import java.io.*;
import java.util.*;
public class io {
        public static void main(String[] args) throws IOException {
                BufferedReader br = new BufferedReader(new FileReader("my.in"));
                PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("my.out")));

                // read in data from file
                int n = Integer.parseInt(br.readLine());
                int[] start = new int[n];
                int[] end = new int[n];
                for(int i = 0; i < n; i++) {
                        StringTokenizer st = new StringTokenizer(br.readLine());
                        start[i] = Integer.parseInt(st.nextToken());
                        end[i] = Integer.parseInt(st.nextToken());
                        System.out.println (start[i] + " / " + end[i]);
                }

        }
}

# my.in
# 2
# 1 2
# 3 4
import static
import static java.lang.System.*;

public class thisclass {
        public static void main(String[] args) {
                out.print( "print this" );
                // only possible with private method below
                println( " ... more xxx" ); 
        }
        private static void println(String str) {
                System.out.println(str);
        }
}

Python Standard Library.

Batteries Included
datetime
import datetime
datetime.date
datetime.time
datetime.datetime
datetime.datetime (year=2019, month=1, day=1, hour=0, minute=00, second=0)
# Click for more...
Python datetime library
decimal
# for floating point arithmetic

import decimal
decimal.Decimal
decimal.Decimal ('0.001')
d = decimal.Decimal ('0.001')
0.1+0.1+0.1
0.1+0.1+0.1 == 0.3
d + d + d == 0.003
d + d + d == decimal.Decimal('0.003')

decimal.getcontext()
dd = decimal.Decimal
four = dd('4')
four.sqrt()
dd('4').sqrt()
dd('3').sqrt()
decimal.getcontext().prec=50
dd('3').sqrt()
glob
# same as wildcard * in shell that expand names
glob.glob ('path_name' + '/*')
itertools
import itertools
for i in itertools.product ('xyz','1234'):
    print (i)
for i in itertools.permutations ([1,2,3]):
    print (i)
math, cmath and random
import math
math.e
math.pi
math.sqrt(25)
math.sqrt(55)
math.log(1024)
math.log2(64)
math.sin(math.pi/2)

# cmat support complex number and complex roots beyond quadroot.py
math.sqrt(-39)
cmath.sqrt(-39)
type (cmath.sqrt(-39))
cmath.polar (4+8j)

random.randrange (-10,1)
x = [ 1,2,3,4,5 ]
random.shuffle (x)
random.choice (x)
random.choice ('string')
os and shutil
statistics
import statistics as st
mylist = [ random.randrange(-5,6) for i in range(10) ]
mylist
# do it again and see what happens
st.mean (mylist)
st.median (mylist)
st.stdev (mylist)
sys
import sys
sys.modules
dir(sys)
sys.argv
for i, argv in enumerate (sys.argv):
    print ("arg {} is {!r}".format (i, argv))
sys.stdin
sys.stdout
sys.stderr
sys.stdout.writelines (sorted (sys.stdin.readlines () ))
# to stop ctrl-D
# or run sysstd.py < my.txt
subprocess
import subprocess as sp
p1 = sp.Popen (['cat','my.txt'], stdout=sp.PIPE)
p2 = sp.Popen (['sort'], stdin=p1.stdout, stdout=sp.PIPE)
pout, perr = p2.communicate()
out
err
turtle
import turtle
turtle.forward (100)
urllib, urllib.request
import urllib.request

x = urllib.request.urlopen('https://www.google.com/')
print(x.read())
webbrowser
import webbrowser
webbrowser.open ("http://www.google.com")
More...
Coming up...

Wednesday, January 2, 2019

Java Editor and IDE.

What features should I care in IDE?
Code Editor - syntax, auto-completion, templates
Compiler - converts source code according to a language 
           understood by the computer OS system.
Debugger - make it easy to analyze and make changes in a program.
Java Language Compiler (JDK) and Java Runtime Environment (JRE)
Java source code is converted into bytecode.
Bytecode is Java binary code understood by Java Runtime Environment Tool.
Java Runtime Environment Tool is called JVM.
Bytecode is run on JVM (Java Virtual Machine).
JVM is computer processor platform dependent.
Do I have Java installed?
javac -version
java -version
How do I download Java Compiler (JDK) and JRE?
https://www.oracle.com/technetwork/java/javase/downloads/index.html
Click to start!
Java Standard Edition, Micro Edition and Enterprise Edition (SE, ME and EE)
They consist of different development tools, deployment technologies and different class libraries.

Java SE - Also known as "Core Java", 
          used to develop stand alone application.
Java ME - Used to develop applications for small scale devices, 
          such as mobile phones.
Java EE - Also known as "Advance Java", 
          used to develop web application that run on a web server.
Java Bluej IDE
bluej.org
Click to start!
Java Eclipse IDE
eclipse.org
Click to start!
Java Intellij IDEA IDE
https://www.jetbrains.com/idea
Click to start!
Java Jdeveloper IDE
http://goo.gl/KvVixu
Click to start!
Java Netbeans IDE
https:/netbeans.org
Click to start!
Jshell
/help intro
/help
3
$1
4
$3
int x = 0;
1/2
1.0/2
/list
for (int i=0; i<3;i++) System.out.println("i : " + i);
void printHello (String name) { System.out.println("Hello "+ name );}
pr<tab>
printHello("amy")
Sys<tab>
/exit