Sunday, March 17, 2013

C++ program to find prime numbers in a given range

Write a C++ program to print all the prime numbers with in the given range



#include<iostream>
#include<iomanip>
using namespace std;

int main(){
    int num,i,count,n;
    cout << "Enter max range: ";
    cin >> n;
    for(num = 1;num<=n;num++){
         count = 0;
         for(i=2;i<=num/2;i++){
             if(num%i==0){
                 count++;
                 break;
             }
        }
       
         if(count==0 && num!= 1)
              cout << num << setw(3);
    }
 system("pause");
   return 0;
}


C++ Tutorial | Learn C++ programming



---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------




---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------



Program in C++ to find the prime number in given range
Write a C++ program to find prime numbers between 1 to 100
Prime numbers in a range - C++
Program to find the prime numbers between a given range
Write a program to print all the prime numbers with in the given range
C++ program to find prime numbers between two numbers
C++ program to find sum of prime numbers
C++ Program to Find Prime Numbers in a given Range

C++ Program to Find Perfect Number

C++ program to check whether a number is not a perfect number or not


#include<iostream>
#include<iomanip>
using namespace std;
int main(){
  int n,i=1,sum=0;
  cout<<"Enter a number: ";
  cin >> n;
  while(i<n){
         if(n%i==0)
               sum=sum+i;
              i++;
  }
  if(sum==n)
         cout << i  <<  " is a perfect number";
  else
         cout << i << " is not a perfect number";
  system("pause");
  return 0;
}

C++ PROGRAM TO CHECK WHETHER A NUMBER IS A PERFECT NUMBER





---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------




---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------



Computing whether is a perfect number - C++
c++ - deciding if a number is perfect or prime
Find out the perfect number using c++ program
C++ Program to Find Perfect Number
C++ program to check if no. is perfect number or not
Program to Find the Given Number is Perfect Number or not in C

C++ program to convert decimal number into binary


Program to convert decimal to binary in C++



/* 
program : Decimal to binary. 
description : to convert decimal number between 0 to 255 to binary  */
# include <iostream>
#include <math.h>
using namespace std ;
int main()
{
unsigned short int x=0,b=128 ,z=0,a=8 ;
cout<<"please enter the number between 0 and 255 \n";
cin >> x;
if (x>255)
cout<<" out of range ";
else
{
cout << x <<" converted to binary number :" ; 
 while (a!=0)
 {
  z=x&b ;
  if (z==128)
  cout << "1" ;
  else
  cout << "0";
  x=(x << 1);
  a-- ;
}
}
cout<<"\n";
system("pause");
return 0 ;
}




---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------

---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------

C++ Program for Decimal to Hexadecimal Conversion

Convert decimal to hexadecimal (C++)



/* program : Decimal to hexadecimal. 
description : to convert decimal number between 0 to 255 to hexadecimal  */

#include <iostream>
using namespace std;

int main(void)
{
int mynum;
cout << "\nEnter a number: ";
cin >> mynum;
cout.unsetf(ios::dec);
cout.setf(ios::hex | ios::showbase);
cout << "In hex: " << mynum;
cout.unsetf(ios::hex);
cout.setf(ios::oct);
cout << "\nIn Octal: " << mynum;
cout.unsetf(ios::oct | ios::showbase);
cout.setf(ios::dec);
system("pause");
return 0;
}


---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------

---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------

Saturday, March 16, 2013

How to connect two Client IP to the same mongodb using c++ Drivers


I am trying to make a client with mongo c++ drivers to connect to the database. I successfully tested the client for the localhost.The code I used for that is below.

Now I want to have the database and clients on different machines for example client on IP 10.1.2.56 and the mongodb on IP 10.1.2.57

I changes should I make in the code to achieve that. I tried to change the line

    c.connect("localhost"); //"192.168.58.1");

To


     c.connect("10.1.2.57"); //"192.168.58.1");

But that does not work
The error says "caught can't connect to server 10.1.2.57:27017 " I tried to ping the IP 10.1.2.57 and it give me the response also .


   #include <iostream>
    #include "mongo/client/dbclient.h"
    
    // g++ src/mongo/client/examples/tutorial.cpp -pthread -Isrc -Isrc/mongo
 -lmongoclient -lboost_thread-mt -lboost_system -lboost_filesystem -L[path to
 libmongoclient.a] -o tutorial
    //g++ tutorial.cpp -L[mongo directory] -L/opt/local/lib -lmongoclient 
-lboost_thread-mt -lboost_filesystem -lboost_system -I/opt/local/include 
 -o tutorial
    
    using namespace mongo;
    
    void printIfAge(DBClientConnection& c, int age) {
        auto_ptr<DBClientCursor> cursor = c.query("tutorial.persons", QUERY( "age" << age ).sort("name") );
        while( cursor->more() ) {
            BSONObj p = cursor->next();
            cout << p.getStringField("name") << endl;
        }
    }
    
    void run() {
        DBClientConnection c;
        c.connect("localhost"); //"192.168.58.1");
        cout << "connected ok" << endl;
        BSONObj p = BSON( "name" << "Joe" << "age" << 33 );
        c.insert("tutorial.persons", p);
        p = BSON( "name" << "Jane" << "age" << 40 );
        c.insert("tutorial.persons", p);
        p = BSON( "name" << "Abe" << "age" << 33 );
        c.insert("tutorial.persons", p);
        p = BSON( "name" << "Methuselah" << "age" << BSONNULL);
        c.insert("tutorial.persons", p);
        p = BSON( "name" << "Samantha" << "age" << 21 << "city" << "Los Angeles" << "state" << "CA" );
        c.insert("tutorial.persons", p);
    
        c.ensureIndex("tutorial.persons", fromjson("{age:1}"));
    
        cout << "count:" << c.count("tutorial.persons") << endl;
    
        auto_ptr<DBClientCursor> cursor = c.query("tutorial.persons", BSONObj());
        while( cursor->more() ) {
            cout << cursor->next().toString() << endl;
        }
    
        cout << "\nprintifage:\n";
        printIfAge(c, 33);
    }
    
    int main() {
        try {
            run();
        }
        catch( DBException &e ) {
            cout << "caught " << e.what() << endl;
        }
        return 0;
    }


I found the Answer of the above question

Earlier the mongod was running on the defined port and path on the Mongodb server side 
 
So I stoped the Mongodb by following command

    $ sudo stop mongodb

and once again started the server with the default defined path by the following command

    $ sudo mongod --dbpath /data/db --port 27017 

and then tried the above code in c++ and this time it connected to the remote server.

How to Install Crypto++ Library with the Eclipse IDE on UBUNTU12.10 OS.

C++ - How to install Cryptopp /  Crypto++ Library with the Eclipse IDE on UBUNTU12.10 OS.


Install Crypto++ library with Ubuntu with the following command

$ sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils

Now make a empty new C++ project in Eclipse IDE
Then add the libraries in the Eclipse ide by following instruction.
Right click the project hello and go to properties.
Then go to

 Tool Settings->Cross G++ Linker ->Libraries-> and do the settings as Shown in picture


And then try the following program for crypto++

#include <iostream>
#include <iomanip>

#include "modes.h"
#include "aes.h"
#include "filters.h"

int main(int argc, char* argv[]) {

    //
    // Key and IV setup
    //AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-   
    //bit). This key is secretly exchanged between two parties before communication   
    //begins. DEFAULT_KEYLENGTH= 16 bytes
    byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
    memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
    memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );

    //
    // String and Sink setup
    //
    std::string plaintext = "Now is the time for all good men to come to the aide...";
    std::string ciphertext;
    std::string decryptedtext;

    //
    // Dump Plain Text
    //
    std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
    std::cout << plaintext;
    std::cout << std::endl << std::endl;

    //
    // Create Cipher Text
    //
    CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );

    CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
    stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() + 1 );
    stfEncryptor.MessageEnd();

    //
    // Dump Cipher Text
    //
    std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;

    for( int i = 0; i < ciphertext.size(); i++ ) {

        std::cout << "0x" << std::hex << (0xFF & static_cast<byte>(ciphertext[i])) << " ";
    }

    std::cout << std::endl << std::endl;

    //
    // Decrypt
    //
    CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );

    CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
    stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
    stfDecryptor.MessageEnd();

    //
    // Dump Decrypted Text
    //
    std::cout << "Decrypted Text: " << std::endl;
    std::cout << decryptedtext;
    std::cout << std::endl << std::endl;

    return 0;
}
.
And Run the program the program should work perfectly.

Sunday, March 3, 2013

FileSystemModel.java File to be used with jTree


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import java.io.File;
import java.util.Iterator;
import java.util.Vector;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

/**
 *
 * @author ProgrammingKnowledge
 */
public class FileSystemModel implements TreeModel {

    private File root;
    private Vector listeners = new Vector();

    public FileSystemModel(File rootDirectory) {
        root = rootDirectory;
    }

    @Override
    public Object getRoot() {
        return root;
    }

    @Override
    public Object getChild(Object parent, int index) {
        File directory = (File) parent;
        String[] children = directory.list();
 /*       for (int j = 0; j< children.length; j++ ){
            System.out.println(children[j]);
        }       */
        
        return new FileSystemModel.TreeFile(directory, children[index]);
    }

    @Override
    public int getChildCount(Object parent) {
        File file = (File) parent;
        if (file.isDirectory()) {
            String[] fileList = file.list();
          
            if (fileList != null) {
                return file.list().length;
            }
        }
        return 0;
    }

    @Override
    public boolean isLeaf(Object node) {
        File file = (File) node;
        return file.isFile();
    }

    @Override
    public int getIndexOfChild(Object parent, Object child) {
        File directory = (File) parent;
        File file = (File) child;
        String[] children = directory.list();
        for (int i = 0; i < children.length; i++) {
            if (file.getName().equals(children[i])) {
                return i;
            }
        }
        return -1;

    }

    @Override
    public void valueForPathChanged(TreePath path, Object value) {
        File oldFile = (File) path.getLastPathComponent();
        String fileParentPath = oldFile.getParent();
        String newFileName = (String) value;
        File targetFile = new File(fileParentPath, newFileName);
        oldFile.renameTo(targetFile);
        File parent = new File(fileParentPath);
        int[] changedChildrenIndices = {getIndexOfChild(parent, targetFile)};
        Object[] changedChildren = {targetFile};
        fireTreeNodesChanged(path.getParentPath(), changedChildrenIndices, changedChildren);

    }

    private void fireTreeNodesChanged(TreePath parentPath, int[] indices, Object[] children) {
        TreeModelEvent event = new TreeModelEvent(this, parentPath, indices, children);
        Iterator iterator = listeners.iterator();
        TreeModelListener listener = null;
        while (iterator.hasNext()) {
            listener = (TreeModelListener) iterator.next();
            listener.treeNodesChanged(event);
        }
    }

    @Override
    public void addTreeModelListener(TreeModelListener listener) {
        listeners.add(listener);
    }

    @Override
    public void removeTreeModelListener(TreeModelListener listener) {
        listeners.remove(listener);
    }

    private class TreeFile extends File {

        public TreeFile(File parent, String child) {
            super(parent, child);
        }

        @Override
        public String toString() {
            return getName();
        }
    }
}
IT Certification Category (English)640x480

Partner Sites

VideoToGifs.com

EasyOnlineConverter.com

SqliteTutorials.com


Top Online Courses From ProgrammingKnowledge

Python Course http://bit.ly/2vsuMaS
Java Coursehttp://bit.ly/2GEfQMf
Bash Coursehttp://bit.ly/2DBVF0C
Linux Coursehttp://bit.ly/2IXuil0
C Course http://bit.ly/2GQCiD1
C++ Coursehttp://bit.ly/2V4oEVJ
PHP Coursehttp://bit.ly/2XP71WH
Android Coursehttp://bit.ly/2UHih5H
C# Coursehttp://bit.ly/2Vr7HEl
JavaFx Coursehttp://bit.ly/2XMvZWA
NodeJs Coursehttp://bit.ly/2GPg7gA
Jenkins Course http://bit.ly/2Wd4l4W
Scala Coursehttp://bit.ly/2PysyA4
Bootstrap Coursehttp://bit.ly/2DFQ2yC
MongoDB Coursehttp://bit.ly/2LaCJfP
QT C++ GUI Coursehttp://bit.ly/2vwqHSZ