<?php

require_once(__DIR__ . '/vendor/autoload.php');

\Illuminate\Support\Facades\Facade::setFacadeApplication(new Illuminate\Foundation\Application());

try {
    $res = \Illuminate\Support\Facades\Http::post($url);
    print_r($res->json('data');
} catch (\Exception $e) {
    error_log('[ERROR] ' . $e->getMessage());
    error_log($e->getTraceAsString());
}

run this comand inside the vm

ssh -L <vm_ip>:<vm_port>:<vpn_internal_ip>:<vpn_internal_port> <vm_user>@<vm_host>
# Example
ssh -L 10.10.10.11:8080:10.10.186.35:80 user@10.10.10.11

run this comand on your local

ssh -f -L <vm_port>:<vpn_internal_ip>:<vpn_internal_port> <vm_user>@<vm_host> -N
# Example
ssh -f -L 8080:10.10.186.35:80 user@10.10.10.11 -N

And now you can access 10.10.186.35:80 using 10.10.10.11:8080 on your local browser.


// PART 1
function PART_1 () {
	console.log('PART 1')
	console.log(`There is a list of data users in tree diagram structurized and sorted by level called as "Title", but the level was \nunneccesarry because it was pre-defined as a constant data on every users.\nThe task is to make a function to find parent of given element's name that have specific title on it's parent. ( e.g. 'HM', CS1 -> SF -> HM3 )`);
	console.log()
	
	var user = (title , id , parentId) => {
		return { title , id , parentId, children: [] }
	}
	var users = []
	users.push(user('M','M1','0'))
	users.push(user('HM','HM1','M1'))
	users.push(user('HM','HM2','HM1'))
	users.push(user('HM','HM3','HM1'))
	users.push(user('HM','HM4','HM1'))
	users.push(user('HM','HM5','HM1'))
	users.push(user('SF','SF1','HM3'))
	users.push(user('SF','SF2','HM3'))
	users.push(user('SF','SF3','HM5'))
	users.push(user('SF','SF4','HM5'))
	users.push(user('CS','CS1','SF1'))
	users.push(user('CS','CS2','SF2'))
	users.push(user('CS','CS3','SF3'))
	users.push(user('CS','CS4','SF4'))

	function list_to_tree(list,keys=['id','parentId','children']) {
	  var map = {}, node, roots = [], i;
	  
	  for (i = 0; i < list.length; i += 1) {
	    map[list[i][keys[0]]] = i; // initialize the map
	    list[i][keys[2]] = []; // initialize the children
	  }
	  
	  for (i = 0; i < list.length; i += 1) {
	    node = list[i];
	    if (node[keys[1]] !== "0") {
	      list[map[node[keys[1]]]][keys[2]].push(node);
	    } else {
	      roots.push(node);
	    }
	  }
	  return roots;
	}

	// console.log(JSON.stringify(list_to_tree(users),null,2))
	function searchTree(element, word, key=['id','children']){
		if (element[key[0]] == word) {
			return element;
		} else if (element[key[1]] != null) {
			var i;
			var result = null;
			for(i=0; result == null && i < element[key[1]].length; i++){
				result = searchTree(element[key[1]][i], word);
			}
			return result;
		}
		return null;
	}

	var tree = list_to_tree(users);
	var search = searchTree(tree[0],'CS4');

	const REF_TITLE = 'HM'
	
	// I want to get the LEAF <REF_TITLE> by input the <CHILD_NAME> or id or else
	var firstOccurence = true

	// I want to get the ROOT <REF_TITLE> by input the <CHILD_NAME> or id or else
	// var firstOccurence = false

	while (true) {
		try {
			if (!search) throw new Error('user not found')
			else if (search.parentId === '0' && search.title !== REF_TITLE) throw new Error('not found')
			if (search.title === REF_TITLE) {
				if (firstOccurence) {
					console.log(search);
					break;
				} else {
					if (search.parentId === '0') {
						console.log(search);
						break;
					} else {
						var tmpSearch = searchTree(tree[0],search.parentId);
						if (tmpSearch.title === REF_TITLE) {
							search = searchTree(tree[0],search.parentId)
						} else {
							console.log(search);
							break;
						}
					}
				}
			} else {
				search = searchTree(tree[0],search.parentId)
			}
		} catch (err) {
			console.error(err.message);
			break;
		}
	}
	console.log('\n\n')
}


// PART 2
function PART_2 () {
	console.log('PART 2')
	console.log(`This task is pretty simple, just making a summary of the data and doing a little bit of Math inside.`)
	console.log()
	var MAX_ORDERS = 100;
	var MULTIPLY_BY = .05;
	var status = {
		'D': 'DRAFT',
		'O': 'OK',
		'P': 'PENDING',
		'C': 'CANCEL',
	}

	var Item  = (itemName, itemPrice) => ({ id: GENID(), itemName, itemPrice });
	var Items = [];
	var ItemByName = (itemName) => Items.find((d)=>d.itemName.includes(itemName))

	const generateRandomPrice = () => (Math.floor(Math.random()*30)*1000+15000)
	Items.push(Item('night stand',generateRandomPrice()));
	Items.push(Item('window',generateRandomPrice()));
	Items.push(Item('sponge',generateRandomPrice()));
	Items.push(Item('television',generateRandomPrice()));
	Items.push(Item('electrical outlet',generateRandomPrice()));
	Items.push(Item('cookie jar',generateRandomPrice()));
	Items.push(Item('measuring tape',generateRandomPrice()));
	Items.push(Item('cat',generateRandomPrice()));
	Items.push(Item('ottoman',generateRandomPrice()));
	Items.push(Item('deodorant',generateRandomPrice()));
	Items.push(Item('letter opener',generateRandomPrice()));
	Items.push(Item('sunglasses',generateRandomPrice()));

	var User = (name) => ({ id: GENID(), name })
	var Users = [];
	var UserByName = (name) => Users.find((d)=>d.name.includes(name))

	Users.push(User('John'))
	Users.push(User('Maria'))
	Users.push(User('Abdoel'))
	Users.push(User('Kevin'))
	Users.push(User('Samuel'))
	Users.push(User('Vhee'))

	var Sales = (status, itemName, user) => ({ status, itemName, user });
	var SalesOrders = [];

	var getRandomStatus = () => {
		var keys=Object.keys(status);
		var index = Math.floor(Math.random()*keys.length)
		return keys[index];
	}
	var getRandomItem = () => {
		var index = Math.floor(Math.random()*Items.length)
		return Items[index];
	}
	var getRandomUser = () => {
		var index = Math.floor(Math.random()*Users.length)
		return Users[index]
	}

	for (let i = 0; i < MAX_ORDERS; i++) {
		SalesOrders.push(Sales(
			getRandomStatus(),
			getRandomItem().itemName,
			getRandomUser().name,
		))
	}
	let SalesOrdersByUsers = {}
	for (let Order of SalesOrders) {
		var user = UserByName(Order.user);
		var item = ItemByName(Order.itemName);

		if (user && item && Order.status === 'O') {
			if (!SalesOrdersByUsers[user.id]) SalesOrdersByUsers[user.id] = { name: user.name, totalBonus: 0, items: {} };
			if (!SalesOrdersByUsers[user.id].items[item.id]) {
				SalesOrdersByUsers[user.id].items[item.id] = {
					itemName: item.itemName,
					itemPrice: item.itemPrice,
					amount: 1,
					bonus: item.itemPrice * MULTIPLY_BY,
				}
			} else {
				SalesOrdersByUsers[user.id].items[item.id].amount++;
				SalesOrdersByUsers[user.id].items[item.id].bonus+=item.itemPrice * MULTIPLY_BY;
			}
			SalesOrdersByUsers[user.id].items[item.id].bonusString=IN_CURRENCY(SalesOrdersByUsers[user.id].items[item.id].bonus)
			SalesOrdersByUsers[user.id].totalBonus += SalesOrdersByUsers[user.id].items[item.id].bonus;
		}
	}
	function printSummary(name){
		var list = Object.values(SalesOrdersByUsers);
		if (name) {
			console.log('Summary of',name)
			list = list.filter((d)=>d.name.includes(name))
		}
		for (let user of list) {
			console.log(`${user.name}, total bonus: ${IN_CURRENCY(user.totalBonus)}`)
			for (let item of Object.values(user.items)) {
				console.log('-',item.amount, item.itemName, item.bonusString, ` (item price: ${IN_CURRENCY(item.itemPrice)})`)
			}
			console.log()
		}
	}
	function printSummaryOf(name){

	}

	printSummary()
	// printSummary('Abdoel')
	// console.log(SalesOrders.filter(d=>d.status === 'O').length)
	console.log('\n\n')
}

PART_1()
PART_2()

// HELPER
var GENID = () => '_'+Math.random().toString(36).substr(2,8); // Generate ID
var IN_CURRENCY = (n) => Intl.NumberFormat('id').format(n);   // NUMBER TO CURRENCY FORMAT

# CONFIG 
username=yourusername
password=yourpassword
hostname=domain.tld
port=22
sockport=80
vpnsource=https://www.vpnjantit.com/

# SETTING BROWSER PROXY USING SOCK4
IP  : 127.0.0.1
PORT: 80

$ cat `which sshtunneling`
# Content of sshtunneling custom-command
  export `cat /tmp/sshtunneling.conf`
  echo "username : $username"
  echo "password : $password"
  echo "server   : $server"
  echo "port     : $port"
  echo "sockport : $sockport"
  param=$1
  if [[ "$1" == "connect" ]]; then
    ssh -f -N -M -S /tmp/sshtunnel_$username -D $sockport $username@$server -p$port
  elif [[ "$1" == "quit" ]]; then
    ssh -S /tmp/sshtunnel -O exit $server -p$port
  elif [[ "$1" == "config" ]]; then
    su `whoami` -c 'subl /tmp/sshtunneling.conf'
  else
    echo "====== help ========"
    echo "sshtunneling connect"
    echo "sshtunneling quit"
    echo "sshtunneling config"
  fi

# Connecting
$ sshtunneling connect
  # prompted for remote password (paste from password in the config)

    Unfortunately some network did not have internet connection except you log in to their instance. Before you can even reach the login page, the site you are trying to reach are requesting data to fonts.googleapis.com that mean require any internet connection. This process will stuck and wait until reach the timeout (limit). 

    The other case are when you are try to developing a website with your local environment without charge any internet / data connection. And the last that always hearth-bleeding are waiting for the DNS resolver to solve this issue when they cannot understand what is fonts.googleapis.com domain. 

    Last but not least, you can try to download specific fonts and put it on your web folder or you can just using default fonts that are available without requesting from the external sites. With this concern, I hope your site are very fast to load and not causing any issues because of "unimportant thing" that you copy from the internet.



    I am currently using NPM for developing ReactJS and I just test sample code from git. Eventually when I try to install packages for the first time its work normally, because of some reason I try to upgrading some package and reinstall it but the installation process looks hang.

The package that I try to reinstall is react-scripts. Here is some advice from StackOverflow:

  • Try to remove package-lock.json (https://stackoverflow.com/questions/50522376/npm-install-hangs-on-loadidealtreeloadalldepsintoidealtree-sill-install-loadid)
  • Try to using unix command line (e.g. git bash). (https://stackoverflow.com/questions/64290462/npx-create-react-app-takes-too-long-every-time)
  • Try to using `npm install <package> --verbose` to know the progress
Walkthrough:
    I just try install using verbose and hang after checking several packages. I find the pattern which different between the package that pass the check and package that hang, it was the status code (HTTP Response), package that pass check will response with status code 304 (Not Modified) and for the hang one there is no response. I search some solution on StackOverflow and found this 'https://stackoverflow.com/questions/45433130/npm-install-gets-stuck-at-fetchmetadata' that lead me to checking the npm installation registry domain (registry.npmjs.org) which is the global config of my npm registry.

Figure out:
    I try the url of hang package in the browser, for the first time it return ERR_NETWORK_CHANGED that I know because of DNS Server not correctly response my request. After that I try to ping to make sure my connection and it was fine.

Resolve:
    After several test and check, I try to add static route to my hosts list that direct to the npm registry url. I add this line  at the end of file /etc/hosts.
104.16.20.35 registry.npmjs.org
This is the end because when I try install again (with verbose) it was really smooth and the log is show that not only response with status code of 304, it also show the status code of 200.

How to Scan Nmap Ports

To scan Nmap ports on a  remote system, enter the following in the terminal:

sudo nmap 192.168.0.1

Replace the IP address with the IP address of the system you’re testing. This is the basic format for Nmap, and it will return information about the ports on that system.

In addition to scanning by IP address, you can also use the following commands to specify a target:

To scan a host:

nmap www.hostname.com

To scan a range of IP addresses (.1 – .10):

nmap 192.168.0.1-10

To run Nmap on a subnet:

nmap 192.168.0.1/13

To scan targets from a text file:

nmap –iL textlist.txt

Note: The developers at nmap.org provide a test server that you can experiment on, located at scanme.nmap.org. You can use this to test your Nmap utility.

Scan a Single Port, All Ports, or Series

Nmap commands can be used to scan a single port or a series of ports:

Scan port 80 on the target system:

nmap –p 80 192.168.0.1

Scan ports 1 through 200 on the target system:

nmap –p 1-200 192.168.0.1

Scan (Fast) the most common ports:

nmap –F 192.168.0.1

To scan all ports (1 – 65535):

nmap –p– 192.168.0.1 

Other Types of Nmap Port Scans

Different types of scans can be performed:

To scan using TCP connect (it takes longer, but is more likely to connect):

nmap –sT 192.168.0.1

To perform the default SYN scan (it tests by performing only half of the TCP handshake):

nmap –sS 192.168.0.1

To instruct Nmap to scan UDP ports instead of TCP ports (the –p switch specifies ports 80, 130, and 255 in this example):

nmap –sU –p 80,130,255 192.168.0.1

Run a fast scan on the target system, but bypass host discovery. (Host discovery uses ping, but many server firewalls do not respond to ping requests. This option forces the test without waiting for a reply that may not be coming):

nmap –Pn –F 192.168.0.1 

The nmap utility can be used to detect the operating system of a particular target:

nmap –A 192.168.0.1

It can also be used to probe for the services that might be using different ports:

nmap –sV 192.168.0.1

Note: The –sV option can be tuned to be more or less aggressive in its scan. Use the ––version-intensity 2 option to specify the level of testing. Replace the number 2 with a number from 0 (light testing) to 9 (run all probes). The more intense the testing, the longer the scan will take.

Common Ports

Here is a brief list of standard ports and their designations:

  • 21 – FTP
  • 22 – SSH
  • 25 – SMTP (sending email)
  • 53 – DNS (domain name service)
  • 80 – HTTP (web server)
  • 110 – POP3 (email inbox)
  • 123 – NTP (Network Time Protocol)
  • 143 – IMAP (email inbox)
  • 443 – HTTPS (secure web server)
  • 465 – SMTPS (send secure email)
  • 631 – CUPS (print server)
  • 993 – IMAPS (secure email inbox)
  • 995 – POP3 (secure email inbox)

 

sudo add-apt-repository ppa:eivnaes/network-manager-sstp
sudo apt-get update
sudo apt install network-manager-sstp sstp-client


Source: https://askubuntu.com/questions/1231162/sstp-vpn-on-ubuntu-20-04-cant-install-sstp-network-manager-plugin

Below is deprecated! But I can learn something.

Download sourcenya di: https://sourceforge.net/projects/sstp-client/files/sstp-client/

sudo make install

sudo sstpc <IP_ADDRESS> --user <USERNAME> --password <PASSWORD> --log-level 0 --cert-warn --tls-ext --uuid <UNIQUE_ID/DOMAINNAME> --save-server-route

Check connection using ifconfig, interfacename will be like ppp0

sudo route add default gw <IP_GATEWAY>


 Buka network sharing & internet setting

Change adapter options

Realtek RTL8812AU - Linux (Ubuntu, Kali | Debian)

Source: https://github.com/gnab/rtl8812au

# clone the drivers from git
git clone https://github.com/gnab/rtl8812au.git

# goto folder
cd rtl8812au/

# create the driver from the sources
make

# Check the driver
insmod 8812au.ko # (Sometimes error "File exists"

# copy to lib
cp 8812au.ko /lib/modules/$(uname -r)/kernel/drivers/net/wireless/

# ?
depmod

# add autoload the driver on boot
echo 8812au | tee -a /etc/modules

# Optional
reboot
echo -e "\nHidden=true\n" | sudo tee --append /etc/xdg/autostart/tracker-extract.desktop /etc/xdg/autostart/tracker-miner-apps.desktop /etc/xdg/autostart/tracker-miner-fs.desktop /etc/xdg/autostart/tracker-miner-user-guides.desktop /etc/xdg/autostart/tracker-store.desktop > /dev/null

gsettings set org.freedesktop.Tracker.Miner.Files crawling-interval -2  # Default: -1
gsettings set org.freedesktop.Tracker.Miner.Files enable-monitors false # Default: true

tracker reset --hard   

React Native run attached android on usb, create file path-to-app/android/local.properties with this:

sdk.dir = /Users/USERNAME/Library/Android/sdk

Option 1:

sudo apt update && sudo apt install android-sdk

The location of Android SDK on Linux can be any of the following:

  • /home/AccountName/Android/Sdk

  • /usr/lib/android-sdk

  • /Library/Android/sdk/

  • /Users/[USER]/Library/Android/sdk

Option 2:

  • Download the Android Studio.

  • Extract downloaded .zip file.

    The extracted folder name will read somewhat like android-studio

To keep navigation easy, move this folder to Home directory.

  • After moving, copy the moved folder by right clicking it. This action will place folder's location to clipboard.

  • Use Ctrl Alt T to open a terminal

  • Go to this folder's directory using cd /home/(USER NAME)/android-studio/bin/

  • Type this command to make studio.sh executable: chmod +x studio.sh

  • Type ./studio.sh

Samba Connection

First to know that it's too difficult to share folder and files between host OS windows with macOS guest in virtualbox using default sharing feature in virtualbox consider macos is non-free or non-community stuff. I do second option that is using samba.

  • Change connection on virtualbox into Bridge mode
  • Activate your sharing folder on windows host os, use default folder (Public) locate on C:\Users\Public
  • Go to macOS and open Finder app
  • Click menu Go and choose connect to server
  • Check the windows ip address
  • Insert samba url smb://<ip_address>/Users/Public
  • Insert credential access like username and password (windows account)

Second option using bash command to mount the Public folder into specific path on macOS. Make sure you already create folder as mount point.

#!/bin/bash
mount_smbfs //<username>@<ip_address>/Users/Public </path/to/folder>

# example:
# make mount point folder
## mkdir /Users/mymacOS/Desktop/shared
# connect
## mount_smbfs //mypc@192.168.1.70/Users/Public /Users/mymacOS/Desktop/shared
#!/bin/bash
umount </path/to/folder>

# example
## umount /Users/mymacOS/Desktop/shared

Change the variable with your own.

String DataType

// reverse()
String.prototype.reverse = function(){
  return this.toString().split('').reverse().join('');
}

// Without default javascript function
String.prototype.reverse = function(){
  var self = this.toString();
  var result = "";
  for(i=self.length-1;i>=0;i--){
  	result+=self[i];
  }
  return result;
}
// Test
console.log("Hello World!".reverse());
// output: !dlroW olleH


//

Array DataType

// toObject()
//

Object DataType

// 
//

Date DataType

// toLocale(),toString(), format(type)
//

Time DataType

// toDate(format="Y-m-d H:i:s")
//

Coming soon

//
//

ReactJS Templates

npx create-react-app my-app --template cra-template            # default
npx create-react-app my-app --template cra-template-typescript # typescript
npx create-react-app my-app --template cra-template-pwa        # add serviceWorker

More info search for cra-template-*.


ReactJS Modules

npm i express                # express http server
# const express = require("express");
# const app = express();

npm i bootstrap              # add bootstrap
# import "bootstrap/dist/css/bootstrap.min.css";

Base 64

# File access permission
<Files .htaccess>
order allow,deny
deny from all
</Files>
# Redirect
Redirect /path/to/web/file.html /path/to/web/target/file.html