Wednesday, December 26, 2018

Fundamentals of Webassembly

I was reading more on the WebAssembly last week.wrote about JavaScript in the last post, I don't know whether I have given wrong feeling that we should not study JavaScript at all. I did not meant that.In fact we should study JavaScript to understand more on the internals and browser JS engines .

The only thing I meant , we are in need finding alternative ways for more robust/new languages to replace JS drawbacks.

Web Assembly + Rust can offer some of the replacement for JS drawbacks. read more https://webassembly.org/


I don't know I know good enough to write this post, but still writing..


How to start with Web Assembly + Rust:


You can read webassembly+ rust on  https://rustwasm.github.io/book/why-rust-and-webassembly.html


In Ubuntu Linux machine probably we need the below steps to run webassembly with rust:

1. You need Rust tool chain: rustc, rustup and Cargo   . read the below link for rust tool chain - https://www.rust-lang.org/tools/install


2. wasm-pack - is a one shop for building testing Rust+webassembly applications.
 read about wasm-pack here https://rustwasm.github.io/wasm-pack/installer/

  wasm-pack has prerequisite for  Rust and npm. Since we installed rust in the above step, we only need npm to install ( if you haven't installed)

npm is a package manager for JavaScript. You can install it from https://www.npmjs.com/get-npm


You can get a project template with following ..

Clone a project template with this command:

cargo generate --git https://github.com/rustwasm/wasm-pack-template

you can follow below steps from the document to start with it .. https://rustwasm.github.io/book/game-of-life/hello-world.html




How to access Document elements(DOM ) using Webassembly+Rust

We need wasm_bindgen and web_sys libraries to access the DOM elements with Rust. You can read more about web_sys here -https://rustwasm.github.io/wasm-bindgen/api/web_sys/






Code: lib.rs

extern crate wasm_bindgen;
extern crate web_sys;

mod utils;

use wasm_bindgen::prelude::*;

use wasm_bindgen::JsCast;
use web_sys::{Document, Element, HtmlElement, Window};


#[wasm_bindgen(start)]
pub fn run() {
    using_web_sys();
}


fn using_web_sys()-> Result<(),JsValue>{
use web_sys::console;

console::log_1(&"Hellowrld to console using websys".into());

let window = web_sys::window().expect("no global window exists");
let document = window.document().expect("no document  found");

let body  = document.body().expect("document should have a body");


let val = document.create_element("p")?;

    val.set_inner_html("Hello from 121Rust!");
val.set_attribute("id","p1");
body.append_child(&val);
        let element = document
.get_element_by_id("p2").expect("no p2 element found");

let element1 = document
.get_element_by_id("p1").expect("no p1 element found");


let att = element.text_content().expect("no element text found");

let att1 = element1.text_content().expect("no element text found");
console::log_1(&att.into());

console::log_1(&att1.into());
    Ok(())

}

cargo.toml:

[package]
name = "na-rust-web"
version = "0.1.0"
authors = ["naveen "]

[lib]
crate-type = ["cdylib", "rlib"]


[dependencies]
cfg-if = "0.1.2"
wasm-bindgen = "0.2.29"
#web-sys = { version = "0.3.6", features = ['console'] }

# The `console_error_panic_hook` crate provides better debugging of panics by
# logging them with `console.error`. This is great for development, but requires
# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for
# code size when deploying.
console_error_panic_hook = { version = "0.1.1", optional = true }

# `wee_alloc` is a tiny allocator for wasm that is only ~1K in code size
# compared to the default allocator's ~10K. It is slower than the default
# allocator, however.
#
# Unfortunately, `wee_alloc` requires nightly Rust when targeting wasm for now.
wee_alloc = { version = "0.4.2", optional = true }

[dev-dependencies]
wasm-bindgen-test = "0.2.29"


[dependencies.web-sys]
version = "0.3.4"
features = [
  'Document',
  'Element',
  'HtmlElement',
  'Node',
  'Window',
  'console',
]
profile.release]
# Tell `rustc` to optimize for small code size.

opt-level = "s"




 











Monday, December 3, 2018

Fundamentals of JavaScript

Last weekend I went to "JavaScript Fundamentals" boot-camp . It was a good class and nice introduction  for people who are new to programming. But my goal was to refresh some of the basics of JavaScript that I haven't tried for long time and want to learn some new things in JavaScript.

Two interesting and new things I learned  from the class are :

1.  80 to 90% of the Internet/Website is running with JavaScript.  Leading browsers in the market ( IE,Mozilla,Google Chrome) can execute only 3 things ( HTML,CSS and JAVASCRIPT).

If you consider Web as language (Analogy), then we can consider  HTML = 'noun' , CSS = "style"  and JavaScript = "Verb". I am ok with this analogy .

All frameworks of other languages like  Django(python web framework) , React( JS framework), Ruby Rails are translating their native language to JS as the browser can  understand only Javascript/html/css.

2. It ( JS applications) can be easily vulnerable and exploited by the malicious  inputs . ( The instructor did not mention/told this ). It was a basic programming boot-camp, so I won't expect him to say this.

But when I saw some of the examples  mentioned are so scary !!!.







We can use "typeof" operator to restrict the input types . But its all on developer's head.

Some of the questions : How  "+" operator can work on number and string ?
It can pass anything to a function and function won't check the type and JS will return something(what ever it like) !!,  its fully developers responsibility to understand the inputs and validate the types of the input before passing.

I think, you can read through below links for more :

https://codeburst.io/top-10-javascript-errors-from-1000-projects-and-how-to-avoid-them-2956ce008437

https://www.pixelstech.net/article/1354210754-10-design-flaws-of-JavaScript

https://whydoesitsuck.com/why-does-javascript-suck/


But I believe, JavaScript is a highly paid programming language and a language still showing/have  deficiency of programmers because 80%t to 90% Websites are running with JS.

If you want to build some fancy and interactive web pages , you need javascript. because the browsers can understand only JavaScript.

That made me research a little bit on Web browser engines, looks like it was just a race for JavaScript engines from 2006 to 2010 between leading web browsers(Microsoft IE, Google Chrome, Opera,Mozilla) . Read more https://en.wikipedia.org/wiki/JavaScript_engine

Just because JavaScript was the only thing making websites interactive and fancy!!. (There would be  some other benefits why browser engines using JS engines). So whoever(browser) can execute the JS quick ,they are the best ( I believe this hold true even today). But serious drawbacks of JavaScript are ignored and that made the internet even worse.

We really need the web to be more secure and trusty , without compromising the performance( I am ok with compromising performance if we get security). So the point is, we really needed an alternative for JavaScript or something can write a good JS for us. Since the 80% of the Web is running with JS, the browsers are not going to switch to some other language engines quickly.

I am not sure how will be internals/architecture  of the browser in next  10 years .I wish there would be more type and memory safe languages engines and they should replace JS engines. People/developers should write those type and memory  safe languages for the browser engines.

I was reading through WebAssembly for last a few months.The JavaScript boot-camp was an eye-opening for me to read more on WebAssembly + Rust again because....


Why  Rust and Web Assembly ?

https://rustwasm.github.io/book/why-rust-and-webassembly.html



WebAssembly -  Its not compromising performance and allows to write type safe + memory safe low languages

Rust - Featuring
  • zero-cost abstractions
  • move semantics
  • guaranteed memory safety
  • threads without data races
  • trait-based generics
  • pattern matching
  • type inference
  • minimal runtime
  • efficient C bindings

But one thing even concerning me is web assembly compiling the C,C++ or Rust to JavaScript that eventually going to run in the browser.. so again JS is going to run in engines. Will this actually solve the JavaScript issues ? I am not sure.


Looking for your comments and thoughts!






Monday, November 26, 2018

Algorithms - sorting algorithms implementation in Rust programming langage

It's important for programmer to do deep dive into algorithms some point of time. but I never tried to do that. As ECE( electronics) branch never needed algorithms in their curriculum, i nicely ignored algorithms . But become unavoidable thing for any kind of application development/programming . its becoming essential to have some ideas or ready made algorithms or approaches in hand to start with some innovative ideas to convert as applications.  So thought of refreshing the algorithms from basics.

If you are learning new language , and trying to solve/implement those basics algorithms , that would be the ideal way to learn them.

And here we are trying to solve/implement some algorithms or problems through Rust programming language.

1. Merge function - https://davnav.github.io/rustgeeks/rust_merge_sortedvectors.html
2.Insert Sort - https://github.com/davnav/rustgeeks/blob/master/rust_insertsort.md
3. Longest string - https://davnav.github.io/rustgeeks/rust_LongestString.html

Tuesday, November 20, 2018

A new documentation started with Algorithms/problem solutions with Rust programming language


Rust for Geeks:


The problems/algorithms can be Easy,Medium or Hard. If you are newbie to programming , you might have noticed most of the schools/colleges start with “C Programming “ language.
But as an alternative , I would recommend, start with Rust programming language. As you all know C was early computer language and created on 1989. Computer programming languages were evolving over the years.So in a way we can say Rust programming languages evolved over 30 years programming language researches. So its better to start with Rust programming language if you are beginning. But you can learn C/other languages also.

so visit my new github page:

Thursday, September 27, 2018

what to do after reading the Rust tutorials !!

if you have read through most of the concepts in Rust and want to build something in Rust, i would suggest below website to start with...

https://mattgathu.github.io/writing-cli-app-rust/

Wednesday, September 26, 2018

multiple termnial at the same screen - Ubuntu

I started using multiple screen in my office to do multiple tasking. I thought it was not going to save my time  and efficiency. But I experienced that it was highly improving my work efficiency. I was able to finish my tasks quickly without much tiring when doing multi-tasking.

But when i reach home and open the laptop, its highly difficult for me switch between screens.

So I was searching for a tool where i can create multi-terminal on the same screen.

you can use terminator

the installation is simple

apt-get install terminator

open a terminal and type
$terminator 

you will get a terminal open by terminator , then you can split it using ctrl +shift +o





Monday, August 6, 2018

Rust on Amazon EC2

Amazon EC2 is very popular nowadays. So wanted to try something with EC2., not sure how much its going to cost me .Usually I stop amazon experiments when I reach the credit card page. :-)

This time really wanted to try what is EC2.

I took the basic plan and lauched a Ubuntu server and installed Rustc, cargo and gcc.

Its really exciting to login to remote machine and experiment some really  installation and programming as we do in our local machine.


Tuesday, July 17, 2018

managed to write a file from terminal input - Rust

My Text editor program in Rust programming language managed to get input characters from screen terminal as created a file once program ends.

Read the code here
https://github.com/davnav/RustEditor/blob/master/main.rs


If I started writing this in C, i would have end up in "Segmentation fault". But even though Rust compiler makes you learn the syntax and new concepts ( mutation,scope,borrow etc) . But once we managed to compile the code, the program produces the output as we expected.(won't go to the buffer overflows or pointer problems)

Terminal is not pointing to left most position when I hit enter, looks like I need to handle this manually.




I have not build any 'struct' for 'Editor' or 'Rows'. Not sure much syntax for 'struct' in Rust.  Reading more this now.


 I think I can move to the 'text viewer' pages in the below documentation.
https://viewsourcecode.org/snaptoken/kilo/04.aTextViewer.html

Monday, July 9, 2018

Finally refreshed the terminal screen

It was always a big question in me that all schooling/engineering  programming  courses( C or assembly)  teach Fibonacci series or some tough logic program ( something like for a given number 'N' search the subset bla bla .. ) . But when I looked at the computer , I wondered how they build these screens/commands and applications.. is it with Maths ?  is it with Fibonacci series /prime numbers? (They are not, it made up of simple logics.. but its like a 'building blocks' game)

My expectation from computer classes was  to build some screens or applications ,  ( but generally I got bored with theory . there was my fault too , i admit ) . Computer applications/commands  did not look like mathematical problem ,But computer subjects seems to me as  mathematics subject. ( I know they really need maths, when we deep dive).

But as a beginner, I misunderstood that someone who knows deep maths can only do something with computer .. but actually that is not the case.

Whatever programs I studied/taught to  do something with stdin ( standard input) or stdout( standard /the screen), are something like 'reverse string' or 'search character', but they did not generate any motivation to build some real world applications, rather I got scared even to attempt/read big programs, thinking it might require big logical algorithms that my brain can't digest.  but as student I always wanted to build something like 'vi' (editor) or some commands or something having windows (not Microsoft windows) screen. At least I wanted to know how these functionalities are coming in the screen.
When I build some functionality that actual 'vi' editor has , I feels like I am writing programs as a professional (Really its not the case)

Having said all these story :-)  as a hobby project , I am  trying to build an editor based on the documentation https://viewsourcecode.org/snaptoken/kilo/03.rawInputAndOutput.html

I am learning lot of things when I wanted my program to do some functionality that 'vi' editor does.

More over I am trying to build this in Rust language  which is a new generation  computer programming language , capable of replacing 'C' language. Every system programmers should try to learn it as per http://web.stanford.edu/class/cs140e/

:-)


My text editor draft , just refreshed the screen :-)
https://github.com/davnav/RustEditor



The clear screen functionality can be easily built with below code, but it was never known to me ( as I know only Fibonacci ... :-) )

// Refresh the screen by writing "x1b[2J" byte to screen
io::stdout().write(b"\x1b[2J");
println!();

// align the cursor to the left top by writing  "\x1b[H" byte to screen
io::stdout().write(b"\x1b[H");



but be aware , Rust compiler is ruthless :-) . it makes us read the documentation thoroughly.










Wednesday, July 4, 2018

do we need to take care 'String' type carefully ?

When I tried to do something with "Strings" in C programming language, either it won't give the desired result or I end up in 'Segmentation fault'. Lot of books in C show "Strings" manipulating with pointers. I like C in the sense  that we can access the characters with the memory where they sit. But when  I compile the full program, it compiles without any error , but finally  when I run it , normally I endup in "Segmentation fault".


So thought of learning some string manipulation/Methods in Rust Programming language.

https://doc.rust-lang.org/std/string/struct.String.html#method.from




Friday, May 25, 2018

Rust-lang learning continuation...

I tried to start again to read on the Rust-Lang tutorials . I thought , i can start with web development in Rust. Usually I directly jump to advanced side of a language and stop it in a few days :-).  Most of the languages I tried that way are ok to start, But Rust is a little more difficult .

For Rust , directly jumping to web development is really tough without understanding the basics. But I am not going to change that method.( really its like ,going back and forth )


Rocket is similar to Flask or Django .. but Rust syntax is killing me.. I can't blame Rust, as it is trying implement safe code.  Rust compiler is so rude, seems like  it won't allow me to compile a single program :-)

Todays learning:




&'static str

"This basically reads as "a reference to a string slice with the lifetime of static", which means that the string has a lifetime of the global scope"

& is familar symbol for programmers, it is used to reference a variable. Generally to get the address of variable .

just refreshed here - https://www.cs.fsu.edu/~myers/c++/notes/references.html

But what is  ' symbol , this is something new to me. it is the lifetime. other programming languages have the scope of the variable. But those languages compilers are not always smart enough to understand the scope of the variables or in other words Rust-lang push to define the life time of the variables for each functions. ( From this, I hope compiler can do the garbage collection by itself)

read more: https://www.quora.com/What-is-the-meaning-of-in-Rust









Sunday, January 21, 2018

Crates and Modules in Rust Language

I was trying to jump into Rust programming language through Rocket web framework. I know it might be a tough attend to directly start with Rocket without much understanding on the Rust syntax.

I believe I have a minimum understanding on Rust syntax and I thought let learn it reverse way , whenever something comes strange or unknown ,let go reverse and goto the basics.

 So, with that strategy when I jump to Rocket , I came across lot of new things.. Ofcourse Rust has lot of new syntax , terminologies. But since I had some prior knowledge on Flask,Django web frameworks, I did not stunt by the folder structures and initial quick start steps.

but it is really fun learning it in reverse way, lot of new things to understand.

One thing was Crates and Modules. It not a new idea, but it a new term and building it in Rust is quite easy.

We have a good documentation from these from Rust developers.

As per my understanding,

If you know python, we will be using packages there. Similar way we can use Crates to build modules and import them into our program.

I hope below documentation will be enough to read through it and try it.

https://doc.rust-lang.org/book/first-edition/crates-and-modules.html

https://rustbyexample.com/attribute/crate.html

Saturday, January 20, 2018

Books reading as a Hobby

First of all, I haven't read any book completely apart from normal curricular. But I read online computer articles and blogs very seriously last a few years. I am finding it as a brain taking process.But its worth reading those technical articles and understanding them. Mostly I follow youtube, I need some demo to start with something rather than just reading and understanding.

I don't know I need take other books like literature,fiction,philosophy as well or stick with (focus) more on the technical stuff alone. I bit confused , but i believe now its essential for me to start reading some other(non technical books) as well ( because not sure how to spend time).

But I know, diverting the focus from technical articles and blogs will be disaster for me.