Arlon's CSUMB Intro to Operating Systems CST-334 Module 1 Learning Journal #1/#25 for the week Wed 06/23-Tues 06/29, year 2021

Arlon's CSUMB Intro to Operating Systems CST-334 Module 1 Learning Journal #1/#25 for the week Wed 06/23-Tues 06/29, year 2021

This week I learned and practiced to use awk and bc the calculator program in bash in a few different ways to do calculations with floating point numbers - pure bash just does integers apparently - I won't demonstrate here yet because the homework isn't due quite yet. I made a lot of examples, took notes on them and saved them with explanations so all this is knowledge I've gained - I actually use shell scripts in real life, myself. I like the book a lot - well - I also find it quite readable - I would like more code examples - but it's okay, I know where to get them (read on). But I have learned a lot from the book in general about some of the specifics of how operating systems work.

We are learning bash right now and as I said in the discussion, I can definitely say why bash scripts and scripts in general are good and very helpful to learn to use.

I have one bash script I use as a wrapper for Java programs (and I think I could use it with C, too) so the entire program is in one file (for me that's the most convenient way to carry a working program as a unit forward as a working example through time - I know you can break programs up and put things in different files but if you put the entire program in one file you can't break it by moving or changing external dependencies.

[Will post if anyone wants it - Windows NT or bash shells, either one (two different scripts)]

I have another bash script I use to automate the remote desktop connection commands:

#!/bin/bash
/home/knoppix/additions/scripts/Remote/2020/0WOL/WOL.sh
echo ssh username:
read vnc_username_here
un_fn=/home/knoppix/additions/scripts/Remote/2020/API/temp/username
echo $vnc_username_here > $un_fn
echo IP Address to SSH into:
read ip_address_for_vnc_ssh_here
ip_fn=/home/knoppix/additions/scripts/Remote/2020/API/temp/ip_address
echo $ip_address_for_vnc_ssh_here > $ip_fn
sh ./additions/scripts/Remote/2020/1RunVNCServer/runVNCserver.sh
echo Local Port to SSH through:
read local_port_for_ssh_vnc_here
local_port_fn=/home/knoppix/additions/scripts/Remote/2020/API/temp/local_port
echo $local_port_for_ssh_vnc_here > $local_port_fn
terminator -x sh ./additions/scripts/Remote/2020/2sshtunnel/sshTunnel.sh &
sh ./additions/scripts/Remote/2020/3vncviewer/vncviewer.sh
read -n 1 -s -r -p "Press any key to continue"

There's obviously a bunch of sub-scripts it calls - if anyone wants I can put them up somewhere.

I have another to initiate mounting network shares:

sudo mkdir /media/share0
sudo chown knoppix:knoppix /media/share0
sudo mount -t cifs //192.168.1.[the ip]/[share] /media/share0 -o username=share_user_name,uid=$(id -u),gid=$(id -g),password=1234
ln -s /media/share0 /home/knoppix/share0
message="all_done"
espeak $message;xcowsay $message;cowsay $message;

I have another I made to automate adding virtual hosts to apache:

[that one is long and complicated, but I'll share it if anyone wants it]

I have another I install into operating system boot sequence for starting server services and also for basically boot time entertainment:

# Arlon's typical boot script
# uses cowsay, xcowsay, fortune, lolcat, cmatrix, openssh-server, apache2, mysql, lxterminal, espeak
# ie to get all these, say, if you are using debian:
# sudo apt update;sudo apt install cowsay xcowsay fortune lolcat cmatrix openssh-server apache2 mysql lxterminal espeak # that would install all of those programs, if possible
# (apt being for debian, it could be yum if it's CentOS or ...um ...I forget the other ones... However your system installs stuff, that's the list.)
#
# start the database server for the web server:
# sudo service mysql start
# start the web server for practice web development:
# sudo service apache2 start
#
fortune | cowsay -e"><" -Tj | lolcat
#
#replace  knoppix with username, run as root:
runuser -l knoppix -c "cowsay -f gnu -p -t 'Hi' | lolcat;fortune | cowsay -f tux -p -T~ | lolcat;fortune | cowsay -f dragon-and-cow -e'oo' | lolcat"
runuser -l knoppix -c "fortune | cowsay -f dragon-and-cow -e'><' -Tj | lolcat"
#
sleep 3
#
#note: cowsay:
#to see all the cows do
# cowsay -l
#( "-l" for list)
#
# sudo service ssh start
# /path/to/mount/network/shares/script
#cmatrix #or #aafire #to not load desktop, only terminal
chromium https://accountblaster.com
chromium --incogneto https://accountblaster.com
# sh /home/knoppix/additions/settings/screen-layout/x205ta/big/x205ta-big-screen-only.sh # maybe set a certain screen size for whatever computer you're on
# sh /home/knoppix/additions/settings/screen-layout/virtualbox-medium/virtualbox-medium-0.screen-layout.sh # maybe set a certain screen size for whatever computer you're on

#fix the time zone
# sh /home/knoppix/additions/scripts/Actions/fix-time-zone.sh # I dunno mine's always resetting itself to New York for some reason.

#demo some example programs:
# sh /home/knoppix/additions/scripts/Actions/custom/0/example-programs.sh # call other script files

# gcc ./example_c_program.c # compile a program
# ./a.out
# g++ ./example_cpp_program.cpp # compile a c++ program
# ./a.out
# rm ./a.out
# javac ./example_java_program.java # compile a Java program
# java example_java_program # run a java program
# rm ./example_java_program.class # delete java class file for that program from current working directory
# rm ./*.class # delete all class files in current working directory

# sleep 5
xcowsay Hi Your Name Here
# sleep 3
# open terminal with specific user (replace 'crab' with username)
# sudo runuser -l crab -c "DISPLAY=:0 lxterminal &"

# xcowsay "add boot scripts at /home/knoppix/additions/scripts/Actions/custom/0/hi/secondary-script.sh"	# call other scripts


#uncomment these lines to see what they do:
#xcowsay --image=/home/knoppix/additions/graphics/bog-creature.png Hi Your Name Here #and replace the image file name bog-creature.png with an image you have in your file system

# open terminal with specific user (replace 'crab' with username) and subsequently run the cmatrix program
#sudo runuser -l crab -c "DISPLAY=:0 lxterminal -e cmatrix &"

espeak "I'm ready, good luck"

You can use Windows NT batch language for scripting too. I have a windows batch script that dumps a folder hierarchy of files into one folder keeping the folder names as part of the new file names.

Another reason you will want to make a script is - almost like a view in MySQL - it simplifies what you're doing, layers in - so you run the script instead of a long command or couple commands, and that gives you more control over fast entry of what you want done. At some point you're going to be running a script with a bunch of parameters and find it's easier to run the script with a script, etc. You can make scripts clickable - one click vs typing for like five minutes - you'll come across stuff that just takes a long time to type - long filenames - even with tab-tab - they still take a long time to get out.

I did get some good practice with C this week at a website I've known about for quite a few years now, formerly CodeFights and now CodeSignal, there is a code 'Arcade' you can solve challenges and advance to harder problems, in any or all languages of your choice. Each challenge solved lets you see hundreds if not thousands of other solutions by expert to beginner programmers that have already solved each problem, programmers from around the world, in all languages. So I've already gone through a lot of the 'Arcade' they have in JavaScript, some in Java, a little in Perl, a little in C++, and now a little in C too. The hello world one is a good game of how many languages can you make it work in. But then, so you go past that, and solve it, and then you can see other people solutions, in C if you want, or any language, and the solutions are ranked so you can look at the good ones first. For me, I know JavaScript and Java pretty well, but not C, hardly at all. So I can solve things in JavaScript and then see the C solution, or try the C solution if I want without seeing anyone else's too. Then hit 'test' and if it looks like you got the algorithm correct, hit 'submit' - and go through a bunch of examples that way, real problems, real simple, actual simple solutions you can figure out or see how someone more proficient did it. The site was really hopping a few years back with traffic, it used to have live coding tournaments and live interview practice but for whatever reason they lost traffic and so there's no live tournaments there anymore - but the Arcade is still there, and, just doing all the examples there - in whatever language you're learning - is super, super helpful for learning. I know, because I used it a lot to learn a lot of JavaScript at one point, it helped me advance past what I knew to what a lot of other people around the world know too, in a simple and fun way. You can 'codefriend' me there, my name at codesignal is 'Arlon A'.

And I don't know - but I would like to know - the answer to the C pointer variable question - which is - "In C programming, a pointer declaration tells us the type of data to which it should point. Examining a variable's contents, can we tell if the variable is a pointer?" I think the answer is - no - but I'm not sure. I did get a lot of practice with C this week, but I'm throwing it around like Java - what I'd like to know is - first of all, the answer to that question, but also, what are the pitfalls - where are the memory leaks going to show up? I constructed a starter framework from two paradigms I found - inner nested structs, and function pointers - building an api when the struct is instantiated. This renders a hierarchical program paradigm, but I pretty much made up the paradigm by combining other paradigms I found, and I have no idea if something like this is 'bad' for leaking memory, or what, since I literally know hardly anything about C, just that I got this far with this document (actually this is abridged, you can make this as big as you want!) and it all compiles and it looks like I could use it to build a huge hierarchical program with the paradigm:

/** Arlon's C Framework - made with function pointers and nested structs.

It's a struct based program hierarchy - struct t6 defines the program heirarchy - struct t6 t5 creates and runs it. Main calls 'program' which initialilzes and calls the structs.

I learned Java for a reason, and I love hierarchical program paradigms because of how logical your programs can be - which translates to quick logical developement.

This is my current incarnation of this, partly influenced by research listed below, reading these pages, but mostly influenced by my drive to use such a paradigm for my programs.
In my experience if you don't figure out a good program structure paradigm as soon as possible your program could become a mess down the road, making it hard to maintain, and subsequently fragile.

These pages helped me figure out how to make this structure but didn't actually show directly on any of the pages, not the way this program is structured - they just helped show me how I could, and I put all the pieces together:

Google Search: c add function to struct:
https://www.google.com/search?q=c+add+function+to+struct&oq=c+add+function+to+struct&aqs=chrome..69i57.4263j0j7&sourceid=chrome&ie=UTF-8
"No, you cannot define a function within a struct in C. You can have a function pointer in a struct though but having a function pointer is very different from a member function in C++"
..."In C it is not allowed to define a method inside a struct ."

I don't mind, and that's what I went with, adding the functions in upon instantiation! They say you can't, I say, but you can!

Can I define a function inside a C structure? [duplicate]
https://stackoverflow.com/questions/12642830/can-i-define-a-function-inside-a-c-structure#:~:text=No%2C%20you%20cannot%20define%20a,to%20the%20containing%20struct%20instance.&text=In%20C%20it%20is%20not,a%20method%20inside%20a%20struct%20.

Define functions in structs
https://stackoverflow.com/questions/9871119/define-functions-in-structs

Example of how you actually CAN:
https://ideone.com/kyHlQ

This page shows exactly HOW you can:
Anonymous functions using GCC statement expressions
https://stackoverflow.com/questions/10405436/anonymous-functions-using-gcc-statement-expressions

Further encouragement and confirmation this would be doable was found on these pages:
C Nested Structure
https://fresh2refresh.com/c-programming/c-nested-structure/#:~:text=C%20Nested%20Structure,-Prev%20Next&text=Nested%20structure%20in%20C%20is,variable%20to%20access%20the%20data.

Google search: c inner struct:
https://www.google.com/search?q=c+inner+struct&oq=c+inner+struct&aqs=chrome..69i57.2599j0j7&sourceid=chrome&ie=UTF-8

Nested structure in c
https://stackoverflow.com/questions/35869873/nested-structure-in-c

Nested Structures in C
https://overiq.com/c-programming-101/nested-structures-in-c/

Nested Structure in C
https://www.javatpoint.com/nested-structure-in-c

What are nested structures in C language?
https://www.tutorialspoint.com/what-are-nested-structures-in-c-language

My blog from a few weeks ago which had a good example of console colors, but in Java:
https://arlonscsumb.blogspot.com/2021/04/arlons-csumb-java-software-design-cst_13.html

None of those are references I took any code from, just knowledge and C programming language paradigm understanding. In addition NONE of those pages show exactly how you can program in C with a hierarchical paradigm like I show here:
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/*	What the include files have/do:
string.h
  (I forgot what exactly this one does already) (I'm brand new to C - the first thing I want to know is how to program it in a hierarchical way - this program is where I am with that)
stdio.h
  printf()
stdlib.h
  rand()
time.h
  time()
*/
int program(){
  
  struct t6{  /* struct based program hierarchy - struct t6 defines the program heirarchy - struct t6 t5 creates and runs it.*/
    int (*add)(int param1, int param2);
    struct inner0{}inner0_0;
    struct inner1{}inner0_1;
    struct inner2{
      struct inner3{}inner0_3;
      struct codeFights{
        struct cF0{
          int (*add)(int param1, int param2);
          int (*centuryFromYear)(int year);
          int (*checkPalindrome)(char * inputString);
        }cF00;        
      }codeFights_0;
      struct colors{
        struct console{
          struct gnulinux{
            struct ansi{  /*  color, random, reset: */
              char * (*color)(int color);
              char * (*random)(int bg);
              char * (*randomFG)();
              char * (*randomBG)();
              char * (*reset)();
            }ansi;
          }gnulinux;
        }console;
      }colors;
    }inner0_2;
    struct program{
      struct data{}data;
      struct state{}state;
      struct api{
        struct tricks{
          struct codeFights2{
            int (*adjacentElementsProduct)(int * inputArray,int sizeOfInputArray);  /*largest contiguous product in an array of two contiguous elements, ie [1,2,3] the answer is 6, [1,4,3,2] the answer is 12. */
           }codeFights2;
        }tricks;
        struct mo{
          int (*zero)();
          int (*one)();
          int (*two)();
        }mo;
      }api;
      struct init{          
        int (*zero)();
      }init;
    }program;
  };
  struct t6 t5={  /* struct based program hierarchy - struct t6 defines the program heirarchy - struct t6 t5 creates and runs it.*/
    ({  int add_implementation_ (int x, int y) { return x + y; }  add_implementation_; })  /*  A trivial example or template function - add two numbers.*/
    ,{  /*inner0 */  }
    ,{  /*inner1 */  }
    ,{  /*inner2 */{  /*inner3 */  },{  /*codeFights */{  /*cF0 */
      ({  int add_implementation_ (int x, int y) { return x + y; }  add_implementation_; })  /*  A trivial example or template function - add two numbers.*/
      ,({  int centuryFromYear_implementation_ (int year) { return 1+(year-1)/100; }  centuryFromYear_implementation_; })  /*  A nearly trivial example or template function - century from year. 2021->21, 1999->20, etc.*/
      ,({  int checkPalindrome_implementation_ (char * inputString) {       
          // printf("Line 127 checkPalindrome_implementation_");printf(inputString);
          int lengthHere(char * inputString){
            printf("Line 129: %d",(int)sizeof(inputString));
            printf("Line 130: %d",(int)sizeof(* inputString));
            return (int)sizeof(inputString)/sizeof(* inputString);
          }    //    int lengthHere(char * inputString)
          for(int i=0;i < strlen(inputString)/2;i++)
              if(!(inputString[i]==inputString[strlen(inputString)-1-i]))
                return 0;
          return 1; 
      }  checkPalindrome_implementation_; })
    }}
    ,{  /*colors */  {  /*console */  {  /*gnulinux */  {    /*ansi */
        ({  char * color (int color) { 
          // return "\u001b["+color+"m"; // There are a few ways to change colors (google search console color codes) - not exactly sure what the differences are - I just try and see what works.
          char buffer[55];
          // snprintf(buffer,55,"\\u001b[%dm",color);//How to concatenate string and int in C?//https://stackoverflow.com/questions/5172107/how-to-concatenate-string-and-int-in-c
          snprintf(buffer,55,"\033[0;%dm",color);//How to concatenate string and int in C?//https://stackoverflow.com/questions/5172107/how-to-concatenate-string-and-int-in-c
          // printf("%s\n",buffer);printf("<-Line 145");
          // printf("%s",buffer);printf("<-Line 146");
          // printf("\\u001b46mAqua BG? -Line 147");
          char * answer=buffer;// This doesn't work without this line even though - I thought pointers were arrays?
          return answer;
        }  color; })
        ,({  char * random (int bg) { 

          time_t t;srand((unsigned) time/*time.h*/(&t));  //  2 line random number example
          printf("Line 154: %d",(int)(1+rand()%2));//prints a random number1-2

          int base=30;
          if(bg>0)base+=10;
          printf("Line 158: rand 1-2: %d base: %d",(int)(1+rand()%2),base);//prints a random number1-2
  
          int color=base+(int)(rand()%8/*stdlib.h*/);//random 0-7
          // return "\u001b["+color+"m"; 
          char buffer[55];
          // snprintf(buffer,55,"\\u001b[%dm",color);//How to concatenate string and int in C?//https://stackoverflow.com/questions/5172107/how-to-concatenate-string-and-int-in-c
          snprintf(buffer,55,"\033[0;%dm",color);//How to concatenate string and int in C?//https://stackoverflow.com/questions/5172107/how-to-concatenate-string-and-int-in-c
          // printf("%s\n",buffer);printf("<-Line 165");
          // printf("%s",buffer);printf("<-Line 166");
          // printf("\\u001b46mAqua BG? -Line 167");
          char * answer=buffer;// This doesn't work without this line even though - I thought pointers were arrays?
          return answer;
        }  random; })
        ,({  char * randomFG () { 
          return t5.inner0_2.colors.console.gnulinux.ansi.random(0); // code reuse, random foreground
        }  randomFG; })
        ,({  char * randomBG () { 
          return t5.inner0_2.colors.console.gnulinux.ansi.random(1); // code reuse, random background
        }  randomBG; })
        ,({  char * reset () { 
          /* This is from my Java colors example: - different color codes
            String color(int what){return "\u001b["+what+"m";}
            String c(int what){return color(what);}
            String reset(){return color(0);}
            String randomBG(){return color(40+(int)(8*Math.random()));}
            String randomFG(){return color(30+(int)(8*Math.random()));}
           */
          // return "\u001b["+color+"m"; 
          char buffer[55];
          // snprintf(buffer,55,"\\u001b[%dm",color);//How to concatenate string and int in C?//https://stackoverflow.com/questions/5172107/how-to-concatenate-string-and-int-in-c
          snprintf(buffer,55,"\033[0m");//How to concatenate string and int in C?//https://stackoverflow.com/questions/5172107/how-to-concatenate-string-and-int-in-c
          // printf("%s\n",buffer);printf("<-Line 189");
          // printf("%s",buffer);printf("<-Line 190");
          // printf("\\u001b46mAqua BG? <-Line 191");
          char * answer=buffer;// This doesn't work without this line even though - I thought pointers were arrays? I literally guessed this line out of thin air - this wasn't working without this line!!
          return answer;
        }  reset; })
     }}}}}
    ,{  /*program */
      {  /*data*/}
      ,{  /*state*/}
      ,{  /*api*/
        {  /*tricks*/
          {  /*codeFights2*/
            ({  int adjacentElementsProduct (int * inputArray,int sizeOfInputArray) {  /*largest contiguous product in an array of two contiguous elements, ie [1,2,3] the answer is 6, [1,4,3,2] the answer is 12. */
              int sz(int * inputArray){return sizeof(inputArray)/sizeof(* inputArray);}
              int biggest=inputArray[0]*inputArray[1];
              printf("\nLine 205: The initial value for biggest: %d",biggest);
              printf("\nLine 206: sz(inputArray): %d",sizeOfInputArray);
              for(int i=1;i<sizeOfInputArray-1;i++)
                if(inputArray[i]*inputArray[i+1]>biggest)
                  biggest=inputArray[i]*inputArray[i+1];              
              return biggest;
            }  adjacentElementsProduct; })
          }
        }
        ,{  /*mo*/  
           ({  int zero () { //t5.program.api.mo.zero();
            
            int add(int param1, int param2) {	// just adding two numbers together
              return param1+param2;
            }
          
            struct trouble{  //  good trouble - try to make something big!
              int (*add)(int param1, int param2);
              // int add(int param1, int param2) {
                // return param1+param2;
              // }  //  I never did figure out how to define with the functions already in them but if I define then I can instantiate with functions for some reason.
            };
                        
            //struct add #0
            struct trouble t1={add};
            printf("Line 230: trouble t1.add(1,2):%d\n",t1.add(1,2));
            
            //struct add #1 annonymous add
            struct trouble t2={
              ({  int add_implementation_ (int x, int y) { return x + y; }  add_implementation_; })
             
            
            };
            printf("Line 238: trouble t2.add(1,3):%d\n",t2.add(1,3));
            
            //struct add #2 annonymous add locally defined
            struct t4{int (*add)(int param1, int param2);};struct t4 t3={

              ({  int add_implementation_ (int x, int y) { return x + y; }  add_implementation_; })
            
            };
            printf("Line 246: trouble t3.add(1,4):%d\n",t3.add(1,4));

            return 1; 
          }  zero; })
          ,({  int one () { //t5.program.api.mo.one();
            printf("\nLine 251: t5.inner0_2.codeFights_0.cF00.centuryFromYear(2021): %d\n",t5.inner0_2.codeFights_0.cF00.centuryFromYear(2021));
            printf("\nLine 252: t5.inner0_2.codeFights_0.cF00.centuryFromYear(1998): %d\n",t5.inner0_2.codeFights_0.cF00.centuryFromYear(1998));
            printf("Line 253: t5.inner0_2.codeFights_0.cF00.checkPalindrome(\"abba\"): %d\n",t5.inner0_2.codeFights_0.cF00.checkPalindrome("abba"));
            printf("Line 254: t5.inner0_2.codeFights_0.cF00.checkPalindrome(\"abbcs\"): %d\n",t5.inner0_2.codeFights_0.cF00.checkPalindrome("abbcs"));
            printf("%sLine 255: Hello? \n",t5.inner0_2.colors.console.gnulinux.ansi.color(46)); // 46 is aqua color background
            printf("%sLine 256: Hello in a Random Color? \n",t5.inner0_2.colors.console.gnulinux.ansi.randomFG());
            printf("Line 257: Hello?");
            printf("%sLine 258: Color Reset? \n",t5.inner0_2.colors.console.gnulinux.ansi.reset());
            return 1; 
          }  one; })
          ,({  int two () { //t5.program.api.mo.two();
             
            //....(Next test branch...)
        
            return 1; 
          }  two; })
        }
      }
      ,{  /*init*/
          ({  int zero () { //t5.program.init.zero();
          
            // t5.program.api.mo.zero();
            t5.program.api.mo.one();
            // t5.program.api.mo.two(); // ...(next test branch)
            
            return 1; 
          }  zero; })      
      }
    }
  };
  t5.program.init.zero();
  
}
int main(){
  program();
}  // (Yes, this all compiles and runs as expected - the question is - does it cause any memory holes? Or anything bad? (It’s inner structs with function pointers - this is C))

Comments

Popular posts from this blog

Service Learning Journal 56, Friday week 8 CST-462s Race,gender, Class in the Digital World

Arlon's CSUMB Intro to HTML CSS JavaScript Node PHP and Web Programming CST-336 Modules 8 Learning Journal #8/#48 for the week Wed 12/15-Tues 12/21, year 2021

52