Caesar cipher variation in C


Introduction
Caesar cipher is a simple substitution cipher where each letter in the plain text is replaced with a letter a fixed number of places down the aplhabet.

Example:
If the number of places to shift is 3, the letter A would be converted to ltter D. Using the same number of shifts the letter x wud be replaced with letter a. if we change the number of shift to 2 A wud be C and X wud be Z.

Using the shift of 3 for the plin text below
THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.
Will result in the following cipher text
WKH TXLFN EURZQ IRA MXPSV RYHU WKH ODCB GRJ.

Problem:
IMPLEMENT A CAESAR CIPHER.

Input:
Number of shifts and the plain text. Input will terminate with negative number of shifts.
Output:
Corresponding cipher text. ONly letters will be converted. Special characters will be ignored and output will be as is.

Solution:

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

int ascii(char a)
{
    return a;
}

int main()
{
    char output[200];
    int read=-1, i, k=0, key = 0, out = 0;
    char *buffer = NULL;
    size_t len;

    while(scanf("%d", &key) && key != -1) {

       /* Reset variable */
       memset(&output, '', sizeof(output));
       memset(&buffer, '', sizeof(buffer));
       i = 0;
       k = 0;
       read = -1;

       getchar();

       read = getline(&buffer, &len, stdin);

       if(-1 != read) {
          while(buffer[i] != '') {
             if(buffer[i] >= ascii('A') && buffer[i] <= ascii('Z')) {
                 out = buffer[i++] + key;
                 if(out > ascii('Z'))
                      out = out - ascii('Z') + ascii('A') - 1;
                 output[k++] = out;
             }
             else if(buffer[i] >= ascii('a') && buffer[i] <= ascii('z')) {
                 out = buffer[i++] + key;
                 if(out > ascii('z'))
                      out = out - ascii('z') + ascii('a') - 1;
                 output[k++] = out;
             }
             else
                 output[k++] = buffer[i++];
          }
       }
       printf("Output : %s\n", output);
    }
 free(buffer);
 return 0;
}

Compile OSv in Ubuntu 12.04.2


OSv is an opensource operating system for the cloud. For more details checkout https://github.com/cloudius-systems/osv.

  1. apt-get install build-essential libboost-all-dev genromfs autoconf libtool ant qemu maven libmaven-shade-plugin-java

    Theres no maven-shade-plugin in ubuntu, its libmaven-shade-plugin-java.

  2. Following errors were encountered on doing
     make mode=debug

    Always use V=1 make as verbose make will give us an insight into why make failed.

  3. Unable to locate tools.jar. Expected to find it in /usr/lib/jvm/java-6-openjdk-amd64/lib/tools.jar

    This error occurs because JRE is installed instead of JDK. Install openjdk-6-jdk.

  4. cc1: error: unrecognized command line option '-std=gnu++11'
    cc1: error: unrecognized command line option "-Wno-maybe-uninitialized" [-Werror]

    This is because C++11 support is not there. C++11 support starts from g++ 4.8. Install g++-4.8.

  5. cc1: error: argument to '-O' should be a non-negative integer
    cc1: error: unrecognized command line option "-Wno-maybe-uninitialized" [-Werror]

    Similarly update gcc to 4.8 or later versions

  6. org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
     INFO: I/O exception (java.net.ConnectException) caught when processing request: Connection timed out

    This is because of proxy(applicable only if you are running behind proxy) . Configure maven proxy.

  7. [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.0:compile (default-compile) on project api: Fatal error compiling: invalid target release: 1.7 -> [Help 1] 

    Set JAVA_HOME variable properly

  8. ./gradlew --daemon build
    
    Downloading http://services.gradle.org/distributions/gradle-1.7-bin.zip
    
    Exception in thread "main" java.net.ConnectException: Connection timed out
        at java.net.PlainSocketImpl.socketConnect(Native Method)
        at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
        at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
        at java.net.Socket.connect(Socket.java:579)
        at java.net.Socket.connect(Socket.java:528)
        at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
        at sun.net.www.http.HttpClient.openServer(HttpClient.java:432)
        at sun.net.www.http.HttpClient.openServer(HttpClient.java:527)
        at sun.net.www.http.HttpClient.<init>(HttpClient.java:211)
        at sun.net.www.http.HttpClient.New(HttpClient.java:308)
        at sun.net.www.http.HttpClient.New(HttpClient.java:326)
        at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:996)
        at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:932)
        at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:850)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1300)
        at org.gradle.wrapper.Download.downloadInternal(Download.java:63)
        at org.gradle.wrapper.Download.download(Download.java:49)
        at org.gradle.wrapper.Install.createDist(Install.java:51)
        at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:129)
        at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:48)

    This is because of proxy(applicable only if you are running behind proxy) . Configure gradle proxy.

  9. 'hda' uses a qcow2 feature which is not supported by this qemu version: QCOW version 3
    qemu-nbd: Failed to bdrv_open '<location>/osv/build/debug/usr.img': Operation not supported
    Traceback (most recent call last):
      File "scripts/imgedit.py", line 139, in <module>
        with nbd_file(img) as f:
      File "scripts/imgedit.py", line 65, in __init__
        raise Exception('Qemu terminated with exit code %d' % self._process.returncode)
    Exception: Qemu terminated with exit code 1
    qemu-system-x86_64: -drive file=<location>/osv/build/debug/usr.img,if=none,id=hd0,aio=native,cache=none: 'hd0' uses a qcow2 feature which is not supported by this qemu version: QCOW version 3
    qemu-system-x86_64: -drive file=<location>/osv/build/debug/usr.img,if=none,id=hd0,aio=native,cache=none: could not open disk image <location>/osv/build/debug/usr.img: Operation not supported

    Get latest qemu, its better to compile from source. Worked fine on installation of qemu 1.7.0 .

  10. Yup thats it. Now from you osv folder run
     scripts/run.py -d

Problems with gdb

As mentioned, after adding add-auto-load-safe-path scripts/loader.py to ~/.gdbinit file. Executing

gdb build/debug/loader.elf

gave following output

 /.gdbinit:1: Error in sourced command file:
Undefined command: "add-auto-load-safe-path".  Try "help".
Reading symbols from /osv/build/debug/loader.elf...done.
Traceback (most recent call last):
  File "/osv/scripts/loader.py", line 602, in 
    timer_state_expired = gdb.parse_and_eval('sched::timer_base::expired')
gdb.error: No type "timer_base" within class or namespace "sched".

This is because add-auto-load-safe-path command is support only on gdb version greater than 7.5, as > gdb 7.5 is not available in repository. You need to compile gdb from source.

Gradle behind proxy


1. Open ~/.gradle/gradle.properties, if not present create one.

2. Copy following for http proxy

systemProp.http.proxyHost=
systemProp.http.proxyPort=
systemProp.http.proxyUser=
systemProp.http.proxyPassword=
systemProp.http.nonProxyHosts=localhost

   Update values accordingly. Replace http with https for https proxy

 

Source : http://www.gradle.org/docs/current/userguide/build_environment.html

 

Maven behind proxy


1. Open ~/.m2/settings.xml file, if not present create one.

<settings xmlns=”http://maven.apache.org/SETTINGS/1.0.0&#8243;
  xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
  xsi:schemaLocation=”http://maven.apache.org/SETTINGS/1.0.0
                      http://maven.apache.org/xsd/settings-1.0.0.xsd”&gt;
  <localRepository/>
  <interactiveMode/>
  <usePluginRegistry/>
  <offline/>
  <pluginGroups/>
  <servers/>
  <mirrors/>
  <proxies>
    <proxy>
      <id>myproxy</id>
      <active>true</active>
      <protocol>http</protocol>
      <username></username>
      <password></password>
      <host></host>
      <port></port>
      <nonProxyHosts>localhost</nonProxyHosts>
    </proxy>
  </proxies>
  <profiles/>
  <activeProfiles/>
</settings>

2. Update the settings.xml file according to your system.

Source: https://maven.apache.org/guides/mini/guide-proxies.html

Android to Ubuntu file transfer


Connecting my android phone to Ubuntu using usb cable automatically mounted the device using MTP. But interestingly i couldnt find any of my files in phone. Googling showed me that we need MTP support to work properly.

1. Install go-mtpfs program.

2. The program automatically creates /media/MyAndroid folder. Mount your device

go-mtpfs /media/MyAndroid

Browse, copy, enjoy!!

3. Once done unmount using

fusermount -u /media/MyAndroid

 

Tested on

OS : Ubuntu 12.04.2

Phone : Samsung Galaxy S2

Andoird: 4.1.2

 

Source: https://github.com/hanwen/go-mtpfs

Set apt-get proxy in Ubuntu 12.04


It took me a while to figure out how to set proxy under Ubuntu 12.04

  1. Create 99mysettings file under /etc/apt/apt.conf/ if not preset
  2. Add the following line
          Acquire::http::proxy "http://<username>:<password>@<proxy host>:<port no>";

Don’t forget to add ; at the end else you will get

Extra junk at end of file

Amazing things scanf can do


While getting input from stdin in C, most of the time we end up taking the full string into a character array and do manipulation on it. scanf lets you do many manipulation while getting input itself. eg, Student ID will be mostly an combination of numbers and characters like 98FA220, if the structure is known before

scanf(“%2d%2s%3d”, &year, branch, &id);

Year = 98

Branch = FA

Id = 220

While getting space separated input, % will read only till space. Hence while reading input like “scanf can do amazing things” into a character array like this

scanf(“%s”, sentence);

sentence will contain only scanf

Either we end up using gets or looping with getchar(), but theres setscan provided in scanf. It lets you set what to scan.

int i;

float x;

char name[50];

scanf(“%2d%f%*d %[0123456789]”, &i, &x, name);

giving * between %d will ignore numbers, can be used with other format specifiers also

with input

56789 0123 56a72

i = 56

x = 789.00

0123 are ignored (assignment suppression)

name = 56

what to scan can be set by specifying the same within [ ], thats why name = 56, because only numbers within 0-9 are taken as input and assigned to name.

Now to read till newline character, do the following

scanf(“%[^\n]s”, sentence);

Input : scanf can do amazing things

sentence = scanf can do amazing things

^ is more like saying read input till that character is encountered.

 

Source : http://pubs.opengroup.org/onlinepubs/009695399/functions/scanf.html

Easiest way of commenting set of lines


While programming you might add dozens of lines just for debugging purposes, or there are cases when you want to comment a set of lines. Its pretty cumbersome with most text editors, with vim its just few keystrokes away.

In one of my previous post i mentioned about substitute command in vim.

Do the following

1. Say of the total program you want to comment from line 25 to 30

2. Press ESC and type :

3. vim by default doesnt show line numbers,

:set nu

will show line numbers

4. Once line numbers which are to be commented are noted down, do the following

:25,30s/^/<language specific comment>

in C give :25,30s/^/\/\/

in python give :25,30s/^/#

Command Dissection

25,30 specifies the set of line you want to comment (replace according to your needs)

^ specifies line start

In words it means, for each line from 25,30 substitute each lines starting with \\ or #

ENJOY!

getchar() explained


getchar() shows interesting outputs.

Check out this code snippet

1 #include<stdio.h>
2 int main()
3 {
4  char a,b;
5  a = getchar();
6  b = getchar();
7  printf(“a = %c b = %c”, a, b);
8  return 0;
9 }

Output

d
a = d b =

On giving input as d, 2nd getchar() is never executed and output prints a = d and b =  blank.

Why?

getchar() function works with buffered input. That is, getchar() gets its input from input buffer. Now instead of printing character, lets print ascii values.

Add  printf(“\na = %d b = %d”, a, b);  after line 7,

Output

d
a = d b =
a = 100 b = 10

ASCII value 100 corresponds to ‘d’ and ASCII value 10 corresponds to ‘\n’, does that mean ENTER keys ASCII value is 10? Interestingly, it varies according to the operating system.

In Windows – Its Carriage Return + Line feed (CRLF)

In Unix, Linux, Mac – Its Line Feed

Carriage Return – ‘\r’ – 13

Line Feed – ‘\n’ – 10

The above code snippet being executed on linux b gets value 10.

How to make second getchar() function to get input from user?

Its obvious that only way to make variable b = value entered by the user is by clearing input buffer. With buffer cleared, getchar() waits for input from the user.
fflush wont work with input buffer.

while((c = getchar()) != '\n' && c != EOF);

will clear input buffer.

Now on executing

Output

d
f
a = d b = f
a = 100 b = 102

As you can see, b gets ‘f’ given by user.

 

Source