Saturday 19 August 2017

Understanding the execution of if-else block using fork

Here is a brief explanation on how both if/else gets execute in case of forking and piping example. Consider the below example:

[code]
#include <stdio.h>
#include <unistd.h>
int main() {
  pid_t pid;
  pid = fork();
  if(pid == 0) {
    printf("Hi Coding-Scripting");
  }
  else {
    printf("Bye.! Coding-Scripting");
  }
  return EXIT_SUCCESS;
}
[/code]

Explanation:

Whenever the call to fork() function is made, it replicates the whole code written down below the fork. So, now the two processes are created child process, with PID =0, and parent process with PID = X. So, the child execute the if block and exits, and after that parent executes the else block and exits. In this manner, both the if-else blocks will get execute.

[firefox] View Source in your favorite editor



To view source code of any website in your favorite source editor:
You can do this by changing 2 hidden preferences.
- Type about:config into the location bar and press enter.
- Accept the warning message that appears, you will be taken to a list of preferences
- In the filter box type view_source
- Double-click on view_source.editor.external to change its value to true.
- Double-click on view_source.editor.path and set it to C:\Program Files\Notepad++\notepad++.exe (if Notepad++ is stored elsewhere change that to where it is stored or you can choose any editor of your preference)

Cheers,

Friday 11 August 2017

PHP script to convert string into 1337 characters

A very basic PHP code, for leet users, that will convert your string into leet characters.



[php]
<?php
/**
* PHP code to convert your string to leet characters.
*/
$input =  strtolower($argv[1]);
$output = "";
$count = strlen($input);
for ($i=0;$i<$count;$i++) {
  switch ($input[$i]) {
    case "a" : $output .= "4";
               break;
    case "b" : $output .= "8";
               break;
    case "c" : $output .= "(";
               break;
    case "d" : $output .= "|)";
               break;
    case "e" : $output .= "3";
               break;
    case "f" : $output .= "|\"";
               break;
    case "g" : $output .= "6";
               break;
    case "h" : $output .= "|-|";
               break;
    case "i" : $output .= "1";
               break;
    case "j" : $output .= "_/";
               break;
    case "k" : $output .= "|<";
               break;
    case "l" : $output .= "|_";
               break;
    case "m" : $output .= "|\\/|";
               break;
    case "n" : $output .= "|\\|";
               break;
    case "o" : $output .= "0";
               break;
    case "p" : $output .= "|*";
               break;
    case "q" : $output .= "0_";
               break;
    case "r" : $output .= "12";
               break;
    case "s" : $output .= "5";
               break;
    case "t" : $output .= "7";
               break;
    case "u" : $output .= "|_|";
               break;
    case "v" : $output .= "\\/";
               break;
    case "w" : $output .= "\\/\\/";
               break;
    case "x" : $output .= "><";
               break;
    case "y" : $output .= "`/";
               break;
    case "z" : $output .= ">_";
               break;
    case " " : $output .= " ";
               break;
    default : $output .= $input[$i];
              break;

  }
}
echo $output;
?>
[/php]

Firefox shortcuts to make your life easier

Search in your opened tabs, enter the % in URL bar



Find Links As You Type ' (apostrophe)
Find Text As You Type /
Open Manage Bookmarks Window Ctrl+B
Add Page to Bookmarks Ctrl+D
Reload Ctrl+R
Force Reload (not from cache) Ctrl+Shift+R
Location Bar Ctrl+L
Move to Next/Previous Link or Form Element in a Web Page Tab/Shift+Tab
Full Screen (toggle) F11
Zoom Text Smaller Ctrl+- (minus sign)
Zoom Text Larger Ctrl+= (plus sign)
View Page Source Ctrl+U

Introduction to applescript

Hi Everyone,

Lets start with some intro of apple script.



Open your apple script editor and enter the text below.

[code]
display dialog "Hello, coding-scripting!"
[/code]

compile and run, a display box will appear with text "Hello, user".

Now to listen to your name, you need to enter below code

[code]
Say "Hello, coding-scripting!"
[/code]

Cool, isnt it.

Now to repeat any command (looping), you have to use repeat command, use the below code, to display the dialog box twice.

[code]
repeat 2 times
display dialog "Hello, coding-scripting!"
end repeat
[/code]

To produce a beep, you need to use beep command.

[code]
beep
[/code]

To beep multiple times, just enter the number (the time you want to produce beep)

[code]
beep 5
[/code]

To set a variable, you need to use set command.

[code]
set myName to "coding-scripting!"
display dialog myName
[/code]

Okay, now how to concatenate the text, we need to use & operator

[code]
set myName to "coding-scripting!"
display dialog "Hello, " & myName
[/code]

Displaying a text box, to grab input from user.

[code]
set myName to the text returned of (display dialog "Enter your name." default answer "" buttons {"Enter"})
display dialog "Hello, " & myName & ". Welcome to coding-scripting!"
[/code]

Mathematical operations for variables :

[code]
set number1 to 5
set number2 to 5
set number3 to number1 + number2
display dialog number3
display dialog "Thanks for reading my tutorial."
[/code]

Creating loop and displaying multiple messages :

[code]
set myMessage to {"Hello user!", "Welcome to coding-scripting!"}
set x to 1
repeat 2 times
    display dialog (item x of myMessage)
    set x to (x + 1)
end repeat
[/code]

While and if else structure

[code]
set a to true
set b to 0
repeat while x
    if a > 5 then
        set b to false
    else
        set b to b + 1
    end if
end repeat
[/code]

Thanks for reading my tutorial.

Compare two files for duplicate entries using bash and php

Hi Friends,

Need to compare two files and searching for different entries in them. Here is the solution.

Create a new file named cmp.sh and put it in a folder.



[code]
#!/bin/bash
uniq temp1 > sort_temp1
sort sort_temp1 > sort1.txt
uniq temp2 > sort_temp2
sort sort_temp2 >> sort1.txt
sort sort1.txt > sort_dup.txt
cat sort_dup.txt | uniq > sort.txt
echo "Elements present in file temp1 not in file temp2"
php index.php 1
echo "Elements present in file temp1 not in file temp2"
php index.php 2
[code]
Save it.

Now, we need to create a php file named index.php in same folder.
[php]
<?php
$handle = @fopen("sort.txt", "r");
if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle, 4096);

//======================================
if($argv[1] == 1)
{
$handle1 = @fopen("sort_temp1", "r");
if ($handle1) {
$test = 1;
while (!feof($handle1)) {
$buffer1 = fgets($handle1, 4096);
if ($buffer==$buffer1)
$test = 0;
}
if ($test == 1)
echo $buffer;
}
fclose($handle1);
}

if($argv[1] == 2)
{
$handle2 = @fopen("sort_temp2", "r");
if ($handle2) {
$test = 1;
while (!feof($handle2)) {
$buffer2 = fgets($handle2, 4096);
if ($buffer==$buffer2)
$test = 0;
}
if ($test == 1)
echo $buffer;
}
fclose($handle2);
}
//========================================

    }
    fclose($handle);
}
?>
[/php]
Save the file in same folder. Add your both files need to compare, with the name temp1 and temp2.

Run the cmd.sh script and it will give you the desired result.

Hope it helps.

Use pipelining to speed up your Firefox browser

If you have a broadband connection (and most of us do), you can use pipelining to speed up your page loads. This allows Firefox to load multiple things on a page at once, instead of one at a time (by default, it’s optimized for dialup connections). Here’s how:



    Type “about:config” into the address bar and hit return. Type “network.http” in the filter field, and change the following settings (double-click on them to change them):

=>    Set “network.http.pipelining” to “true”
=>    Set “network.http.proxy.pipelining” to “true”
=>    Set “network.http.pipelining.maxrequests” to a number like 30.

This will allow it to make 30 requests at once.
Also, right-click anywhere and select New-> Integer. Name it “nglayout.initialpaint.delay” and set its value to “0″. This value is the amount of time the browser waits before it acts on information it receives.

count twitter followers using PHP

Hi Members,

If you need to find the number of followers of particular username without logging in to the twitter, then this script will be helpful for you.



Run the script in cli mode and it will give you twitter count.

How to run:
[code]
$ php twitter_follower.php
<follower count>
[/code]

Save the below code as file named twitter_follower.php and  run as instructed above :

[Code]
<?php
$username = "coding-scripting";
$url = "https://twitter.com/$username";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($ch);
curl_close($ch);
$pattern = "/followers_count&quot;:(\d+),&quot;/";
if(preg_match($pattern, $data, $count)) {
$followers = $count[1];
print $followers;
}
?>
[Code]

In case of any issue, let me know in comments.

Thanks

Boot process of linux




I know you always get amazed, and curious to know how your linux box starts, So lets have a quick look at it.

So, How does a Linux Box boot :

The computer either powered on or reset, the BIOS gets executed.

BIOS: Basic Input Output System. Its is a set of firmware and software, traditionally stored in a EEPROM (Electrically Erasable Programmable Read Only Memory) chip. That EEPROM is CMOS (Complementary Metal Oxide Semiconductor) which requires a battery to keep the settings saved.
The BIOS performs two tasks:

1. POST (Power on Self-Test): BIOS detects and initialize the connected hardware on various ports and PCI. It also checks whether the hardware is working from its basic level.
2. Run Controller: After POST, BIOS checks for the boot sectors in respective media according to boot priority saved in BIOS itself.

Boot Sector: A 512 byte starting sector of Hard disk, Floppy or CD/DVD which contains boot information.
A hard disk contains a boot sector called MBR (Master/main boot record) which is 512 Byte starting sector which holds boot loader,
Where 446 Bytes are used to contain a boot loader, next 64 Bytes are used to contain partition (primary) information and next 2 Bytes contains magic numbers. Magic number checks the validation status of MBR.
By default DOS MBR is used in a hard disk which can be overwrite with Linux Boot Loader like LILO & GRUB.
GRUB is new boot loader which overcomes the limitations of LILO, so here I am going to explain GRUB.

GRUB: (Grand Unified Boot Loader) an intelligent boot loader which supports chain boot loading (A responsibility of also booting another OS'es like Windows, DOS, FreeBSD etc.).Being large in size, GRUB boots in stages :

Stage 1: It is presented into MBR and loads the next stage boot loader. It refers partition table for an active partition and after finding active partition it checks other partitions to ensure that whether they are inactive.
Stage 1.5: The stage 1.5 contains drivers & modules to understand a file system. When stage 1.5 boot loader is loaded, it is able to load the stage 2 boot loader located at ext2 or ext3 file system partition as it is able to read a file system.
Stage 2: The task at this stage is to loads the Linux kernel & initial RAM disk. With stage 2 loaded GRUB display a list of available kernels (defined in /boot/grub/grub.conf).
User can select a kernel and also some additional kernel parameters can be used there. User can use a command line shell for greater manual control over the boot process.
Kernel: The loaded kernel is not much executable kernel. It is a compressed kernel image. It gets control from stage 2 boot loader. Typically it is zImage (compress image less than 512KB) or a bzImage (big compressed image more than 512KB). The kernel is now decompressed through a call to a C function called decompress kernel.
During the boot of kernel, the initial RAM disk which was loaded by stage 2 boot loader is copied into RAM and mounted. This provides temporary root file system in RAM and allow kernel to fully boot without having mount to any physical disk. Initrd also provides the needed modules to access a list of hardware interface. After the kernel is booted, the root file system is pivoted (The process of overcoming by initrd to root file system) and initrd root file system in unmounted and the real root is mounted now.
Init : After kernel is booted and initialized, the kernel starts the first process called init ('/sbin/init', '/etc/init', '/bin/init' or '/bin/sh). The init program reads it's configuration from the 'inittab' file that is located in the 'etc' directory.This file is where run levels come into existence. A runlevel is a software configuration that allows only a selected group of processes to exist. Red Hat Linux Runlevels are:

0-halt
1 - Single User Mode
2 - Multi User mode
3 - Full Multi User Mode 4-NotUsed
5-X11
6-Reboot
A inittab file overview:
------------------------------------------------------------------------||
1.   | id:3:initdefault:
2.   | si::sysinit:/etc/init.d/rcS
3.   | l0:0:wait:/etc/init.d/rc 0
4.   | l1 : S1:wait:/etc/init.d/rc 1
5.   | l2:2:wait:/etc/init.d/rc 2
6.   | l3:3:wait:/etc/init.d/rc 3
7.   | l4:4:wait:/etc/init.d/rc 4
8.   | l5:5:wait:/etc/init.d/rc 5
9.   | l6:6:wait:/etc/init.d/rc 6
10. | ca:12345:ctrlaltdel:/sbin/shutdown -h now
11. | su:S016:respawn:/sbin/sulogin
12. | 1:2345:respawn:/sbin/agetty tty1 9600
13. | 2:2345:respawn:/sbin/agetty tty2 9600
14. | 3:2345:respawn:/sbin/agetty tty3 9600
15. | 4:2345:respawn:/sbin/agetty tty4 9600
16. | #5:2345:respawn:/sbin/agetty tty5 9600
17. | #6:2345:respawn:/sbin/agetty tty6 9600
_____________________________________________||

Here in file:
The first line tells the default runlevel, in which mode the system will boot. 3 stands for full Multi User Mode.

The Second line tells about the scripts that are needed to be run for each runlevel. There is also a line specifying a script to run before all the others, like setting up localnet and mounting filesystems.

The Line 3rd to 9th describe the scripts associated to 0 to 6 runlevels. When the system boots, default runlevel associated scripts runs.

10th Line describes Alt+ctrl+del action. 11th line describes switching user script.
Many of the entries are also specified with 'respawn'. This parameter tells init to continually execute this program whenever the previous one exits. When one logs out, init respawns the getty process to allow another login.

The directories /etc/init.d/rc (0-6) contains services scripts. The service which gets automatically start on system boot is named as starting from 'S' and which is disabled by default or by user is named as starting from 'K'.Immediately following the identifier is a two digit number that indicates the order it is to be executed. The scripts are actually run in alphabetical order, so the lower numbered scripts are run first.

Finishing Up: Once init finishes with the startup scripts, it runs a getty process on each terminal specified in inittab. Getty is what you see when you are logging in.
Once you enter your username, the getty process runs login, which in turn asks for your password.


Using Applescript to open multiple tabs

Hi,

After starting the machine, we feel to open Mozilla/Safari for browsing our favorite websites. So, we need to open the each tab again and again and enter the url or click on bookmark of our favorite website. This task can be make simpler by using AppleScript.



Here is the code

[code]
tell application "Safari"
open location "http://coding-scripting.blogspot.co.in"
open location "http://www.google.com/"
open location "http://www.nokia.com/"
open location "http://www.yahoo.com/"
end tell
[/code]

In same manner, you can use Firefox application, if you are firefox lover. Just replace Safari with Firefox.

Code to generate 32 random ascii characters

Hi,

It is a code to generate random 32 ASCII characters, you can modify it according to your need. You can use it for generating Passwords, encrypting passwords and many more things.



[code]
#include<iostream>
#include<cstdlib>
#include<ctime>

using namespace std;

int main (int argc, char *argv[])
{
char st[31];
int temp;
srand(time(0));
for (int c=0;c<32;c++)
{
for(int i=1;i<2;i++)
{
temp=0;
while(temp<32 || temp>126)
   temp = rand()%126;
st[c] = temp;

}
}
cout<<st;
return 0;
}
[/code]

Secure coding practices for C scanf



This section contains about the secure coding practices which helps to make your code secure, reliable and fast.

1. Avoid using scanf():

Why => It leads to buffer overflow.
How to protect => use with %ms, and free. to allocate the space dynamically.

Source:

Mark's blog


#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
    char *str;
    printf("Enter your name:\n");
    scanf("%ms", &str);

    printf("Hello %s!\n", str);
    free(str);
    return 0;
}

Thanks

SMART Drive monitoring tool



The new disks coming in market are S.M.A.R.T. ( Self-Monitoring, Analysis and Reporting Technology ) enabled. It monitors your disk and alerts you if the disk is about to fail , helpful to prevent data loss. There are many factors you find in SMART array :-

Some of them are as follows :

Read Error Rate => Lower the value good it is.
Reallocated Sectors Count => Lower the value good it is.
Reported Uncorrectable Errors => Lower the value good it is.
Current Pending Sector Count => Lower the value good it is.

and many more.

Tools to monitor and easily generate the report, prefer to use your vendor tool, or else you can use :

Ubuntu : GSmart
Windows : HD Tune

In case, if you lost your data, try spinrite, it may recover it.


Friday 23 June 2017

Hello World program without using any semi colon in C

Question: Write the hello world program . . . Without using any semi-colon's ";" ?
Answer:

#include <stdio.h>

void main()
{
if(printf("Hello World")) { }
}

Monday 1 May 2017

Reduce image size

Sometimes, you need to fill an application form, but the size of your image is
too large, as per the mentioned size on the application. So, you can use imagemagick
utility of ubuntu, and get the desired size for your image.

To reduce the image size, you can run either of the below command.


$ convert  -resize 50% source.png dest.jpg and 

$ convert  -resize 1024X768  source.png dest.jpg

Saturday 15 April 2017

Easter Egg: How to activate YouTube dark theme mode

After coming back home from office, we prefer to watch some videos on YouTube to get relax. But the white theme of YouTube is straining your eyes. So, YouTube introduced the dark theme for us. Now, enjoy your videos in dark room with dark mode. :)

This is found by reddit user.

Steps to activate dark mode:

1. Update your chrome browser to the latest one.
2. Open youtube.com.

Before dark theme:


3. Right click on anywhere on the screen, and choose inspect element. Or you can open the developer console using the key combination of Ctrl+Shift+I or CMD+Shift+I


4. Once it is opened, select the console tab in your developer console. and enter the below string.

document.cookie="VISITOR_INFO1_LIVE=fPQ4jCL6EiE"

5. Once entered, you will get below response.


6. Next step, is to reload your page, and the option to select "Dark mode" will become visible on your youtube account. when you click on gear icon(settings), on right top of your page.



7. Toggle it on, by selecting it. Once the dark mode is ON, then YouTube is available in dark mode and look like this:


Hope you enjoy this dark mode. Now, we dont need lights off add on anymore for YouTube. If you are facing any trouble in enabling it, feel free to comment or write to me.

Happy Easter.!!!

Monday 20 March 2017

How to write in bold using ncurses in C

To use ncurses in your program, you first need to install ncurses. Once installed, write the below code:

#include <ncurses.h>
#include <stdio.h>
#include <stdlib.h>

int main() {
  int ch;
  initscr();
  raw();
  keypad(stdscr, TRUE);
  noecho();
  printw("Type any character to see it in bold\n");
  ch = getch();
  if (ch == KEY_F(1))
    printw("F1 Key pressed");
  else {
    printw("The pressed key is ");
    attron(A_BOLD);
    printw("%c", ch);
    attroff(A_BOLD);
  }
  refresh();
  getch();
  endwin();
  return EXIT_SUCCESS;
}

To compile it, use the ncurses library using
$ gcc file.c -lncurses

Once compiled, it will generate a executable named a.out

Type any character to see it in bold
The pressed key is A

If you need any help installing ncurses, write in comment section.

Thursday 16 March 2017

Generating password using openssl for your unix accounts

There is a need when you need to create an account using password hash, follow below steps to simply create password hash.

$ openssl passwd -1
Password: <your pass>
Verifying - Password: <your pass>
Hash will appear here as an output

openssl is the command to generate password
passwd is an argument and -1 represents here that we want unix kind of hash from passwords as an output. There are other options too, like md5, crypt.

For example, you can use:

$ openssl passwd -crypt
or,
$ openssl passwd -md5

You can also provide the salt, to enhance the security

$ openssl passwd -crypt -salt (yourSalt)

This salt is required to decrypt the password.

You can also use python crypt function to create encrypted hashes:


# PASS="strongpass" python -c "import crypt; import os; print crypt.crypt(os.environ['PASS'], 'salt')"&
# ps fauxwww | grep 'python -c'

In this manner, the password will not appear in ps output.

To hide from history, you can disable and enable the history using following option
set +o history
# PASS="strongpass" python -c "import crypt; import os; print crypt.crypt(os.environ['PASS'], 'salt')"&
set -o history

So, go ahead and generate your hashes.

RAINBOW ROSE in shell script

To gift your friend, you can send him/her a rainbow rose by using below shell script

#!/bin/bash
RED='\033[1;31m'
GREEN='\033[1;32m'
CYAN='\033[0;36m'
YELLOW='\033[1;33m'

printf "${RED}    .--.---.\n"
sleep 1;
printf "   ( ${CYAN}\'--'/${RED} )\n"
sleep 1;
printf "  ( ${CYAN}'..-...'${RED} )\n"
sleep 1;
printf "   '.${CYAN}'-._.'${RED}.'\n"
sleep 1;
printf "    <'${CYAN}-.,.${RED}->\n"
sleep 1;
printf "${GREEN}       \`\\(  ${YELLOW}  _\n"
sleep 1;
printf "${GREEN}        < \ ${YELLOW} / \ \n"
sleep 1;
printf "       ${YELLOW}__${GREEN} \\\\\\ $YELLOW|_/\n"
sleep 1;
printf "      /  \ ${GREEN}\\\\\\ \n"
sleep 1;
printf "      ${YELLOW}'--'.${GREEN}\\\\\\ ${YELLOW}>\n"
sleep 1;
printf "${GREEN}            \\\\\\   \n"
printf "\n"
printf "${CYAN}RAI${RED}NBOW${GREEN} ${RED}ROSE${RED} FOR ${CYAN}YOU${CYAN} ${GREEN}MY${YELLOW} FRIEND\n"

And it will look like this: