Showing posts with label projects. Show all posts
Showing posts with label projects. Show all posts

August 10, 2014

Write a python program for creating virtual file system on Linux environment.

1 comment:

# Developer: Manish Raj (technoslab@gmail.com)
import shelve, time, sys

class File(object):

    def __init__(self, name, type, parent=None, text=''):
        self.list = []
        self.name = name
        self.type = type
        self.time = int(time.time())
        self.parent = parent
        self.text = text

    def is_file(self, name):
        for node in self.list:
            if node.name == name:
                return True
        return False

    def is_dir(self, name):
        if(self.is_file(name)) and self.get(name).type == 'dir':
            return True
        return False

    def get(self, name):
        for node in self.list:
            if node.name == name:
                return node
        
    def add(self, name, type, text=''):
        self.list.append(File(name, type, self, text))
             
    def remove(self, name):
        self.list.remove(self.get(name))
            
    def rename(self, name):
        self.name = name

    def copy(self, src, dest):
        src = self.get(src)
        self.add(dest, src.type, src.text)

    def stat(self):
        print 'Listing', self.name
        for node in self.list:
            print 'Name:', node.name, '; Created:', node.time, '; Type:', node.type
            
    def read(self):
        print 'Reading file:', self.name
        print self.text

class FileSystem(object):
    
    COMMANDS = ['ls', 'mkdir', 'chdir', 'cd', 'rmdir', 'create', 'read', 'rm', 'mv', 'cp', 'help', 'exit']
    
    def __init__(self):
        self.io = shelve.open('file.sys', writeback=True)
        if self.io.has_key('fs'):
            self.root = self.io['fs']
        else:
            self.root = File('/', 'dir')
        self.curr = self.root

    def mkdir(self, cmd):
        if len(cmd) < 2 or cmd[1] == '':
            print 'mkdir - make directory'
            print 'usage: mkdir <dir_name>'
        else:
            name = cmd[1]
            if self.curr.is_file(name) == False:
                self.curr.add(name, 'dir')
            else:
                print name, ' - already exists.';

    def chdir(self, cmd):
        if len(cmd) < 2 or cmd[1] == '':
            print 'chdir - change directory.'
            print 'usage: chdir <dir_name>'
        else:
            name = cmd[1]
            if name == '..':
                if self.curr.parent is not None:
                    self.curr = self.curr.parent
            elif self.curr.is_dir(name):
                self.curr = self.curr.get(name)
            else:
                print name, ' - invalid directory.'

    def rmdir(self, cmd):
        if len(cmd) < 2 or cmd[1] == '':
            print 'rmdir - remove directory'
            print 'usage: rmdir <dir_name>'
        else:
            name = cmd[1]
            if self.curr.is_dir(name):
                self.curr.remove(name)
                print 'Directory deleted.'
            else:
                print name, ' - invalid directory.'
                
    
    def rm(self, cmd):
        if len(cmd) < 2 or cmd[1] == '':
            print 'rm - remove file'
            print 'usage: rm <file_name>'
        else:
            name = cmd[1]
            if self.curr.is_file(name) and not self.curr.is_dir(name):
                self.curr.remove(name)
                print 'File deleted.'
            else:
                print name, ' - invalid file.'

    def ls(self, cmd):
        if(len(cmd) > 1):
            print 'ls - list stats'
            print 'usage: ls'
        self.curr.stat()

    def create(self, cmd):
        if len(cmd) < 2 or cmd[1] == '':
            print 'create - create a file'
            print 'usage: create <file_name>'
        else:
            name = cmd[1]
            self.curr.add(name, 'file', raw_input('Enter file context: '))
            
    def read(self, cmd):
        if len(cmd) < 2 or cmd[1] == '':
            print 'read - read a file'
            print 'usage: read <file_name>'
        else:
            name = cmd[1]
            if self.curr.is_file(name):
                self.curr.get(name).read()
            else:
                print name, 'invalid file'

    def mv(self, cmd):
        if len(cmd) < 3 or cmd[1] == '':
            print 'mv - rename a file'
            print 'usage: mv <old_name> <new_name>'
        else:
            old_name = cmd[1]
            new_name = cmd[2]
            if self.curr.is_file(old_name):
                self.curr.get(old_name).rename(new_name)
            else:
                print old_name, 'invalid file'

    def cp(self, cmd):
        if len(cmd) < 3 or cmd[1] == '':
            print 'cp - copy a file'
            print 'usage: cp <src> <dest>'
        else:
            src = cmd[1]
            dest = cmd[2]
            if self.curr.is_file(src):
                self.curr.copy(src, dest)
            else:
                print src, 'invalid file'
    
    def save(self):
        self.io['fs'] = self.root
        self.io.sync()
            
    def help(self, cmd):
        print 'COMMANDS: mkdir, ls, chdir, rmdir, create, read, mv, cp, rm, exit'

    def exit(self, cmd):
        sys.exit(0)

def main():
    fs = FileSystem()
    while True:
        cmd = raw_input('> ').split(' ');
        method = None
        try:
            method = getattr(fs, cmd[0])
        except AttributeError:
            print 'Invalid command. Type "help".'
        if method is not None and cmd[0] in FileSystem.COMMANDS and callable(method):
            method(cmd)
            fs.save()
        else:
            print 'Invalid command. Type "help".'
main()
Read More

February 23, 2013

Java transparent widget

9 comments:


Cool widget in java

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.io.File;
import java.net.Socket;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Scanner;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.WindowConstants;

public class Status {

    public static void main(String[] args) {
        final int w = 130;
        final int h = 500;

        Dimension x = Toolkit.getDefaultToolkit().getScreenSize();

        final JDialog d = new JDialog();
        d.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        d.setUndecorated(true);
        d.setSize(w, h);
        d.setBackground(new Color(0, 0, 0, 0));
        d.setBounds(x.width - w - 20, 20, w, h);
        d.setAlwaysOnTop(true);

        JLabel l = new JLabel();
        l.setBackground(new Color(0, 0, 0, 0));
        l.setForeground(new Color(255, 255, 255));
        try {
            l.setFont(Font.createFont(Font.TRUETYPE_FONT, l.getClass().getResourceAsStream("/consola.ttf")).deriveFont(Font.PLAIN, 13));
        } catch (Exception e) {
            l.setFont(l.getFont().deriveFont(Font.PLAIN, 13));
            e.printStackTrace();
        }

        l.setBorder(javax.swing.BorderFactory.createMatteBorder(5, 0, 0, 0, new Color(255, 255, 255)));

        l.setVerticalAlignment(l.TOP);
        l.setHorizontalAlignment(l.LEFT);
        d.add(l);
        d.setVisible(true);
        String user = System.getProperty("user.name");
        String os = System.getProperty("os.name");
        double ram = 0;
        try {
            Process p = Runtime.getRuntime().exec("wmic OS get TotalVisibleMemorySize /Value");
            Scanner scan = new Scanner(p.getInputStream());
            while (scan.hasNext()) {
                String temp = scan.nextLine();
                //System.out.println(temp);
                if (temp.startsWith("TotalVisibleMemorySize")) {
                    ram = Long.parseLong(temp.split("=")[1]);
                    //System.out.println("RAM :" + ram);
                    break;
                }
            }
        } catch (Exception e) {
        }


        d.addMouseMotionListener(new java.awt.event.MouseMotionListener() {

            @Override
            public void mouseDragged(MouseEvent e) {
                d.setBounds(e.getXOnScreen(), e.getYOnScreen(), d.getWidth(), d.getHeight());
            }

            @Override
            public void mouseMoved(MouseEvent e) {
            }
        });

        d.addMouseListener(new java.awt.event.MouseListener() {

            @Override
            public void mouseClicked(MouseEvent e) {
            }

            @Override
            public void mousePressed(MouseEvent e) {
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON2) {
                    System.exit(0);
                }
            }

            @Override
            public void mouseEntered(MouseEvent e) {
            }

            @Override
            public void mouseExited(MouseEvent e) {
            }
        });

        long itime = Calendar.getInstance().getTimeInMillis();

        while (true) {
            StringBuilder status = new StringBuilder();
            status.append("Current user: ").append(user);
            status.append("
------------------");
            Calendar c = Calendar.getInstance();
            status.append("
Time: ").append(c.get(Calendar.HOUR_OF_DAY)).append(":").append(c.get(Calendar.MINUTE)).append(":").append(c.get(Calendar.SECOND));
            status.append("
Date: ").append(c.get(Calendar.DATE)).append("/").append(c.get(Calendar.MONTH) + 1).append("/").append(c.get(Calendar.YEAR));
            status.append("
------------------");
            status.append("
OS: " + os);
            status.append("
Memory: ").append(new DecimalFormat("#.##").format(ram / 1024 / 1024)).append(" GB");
            status.append("
------------------");
            File[] f = File.listRoots();
            long total = 0;
            long free = 0;
            for (int i = 0; i < f.length; i++) {
                total = f[i].getTotalSpace();
                free = f[i].getFreeSpace();
                if (total > 0) {
                    long p = (free * 100 / total);
                    status.append("
").append(f[i].getAbsolutePath().replace(File.separator, "")).append(" ").append(total / 1024 / 1024 / 1024).append(" GB");
                    status.append("
").append(p).append("% free : ").append(free / 1024 / 1024 / 1024).append(" GB");
                }
            }
            status.append("
------------------");
            try {
                Socket s = new Socket("www.google.com", 80);
                s.getInputStream();
                s.setSoTimeout(500);
                s.close();
                status.append("
Internet: On");
            } catch (Exception e) {
                status.append("
Internet: Off");
            }
            status.append("
Uptime: ").append((c.getTimeInMillis() - itime) / 1000).append(" s");
            status.append("
------------------");
            //status.append("
Geek.Manish");
            status.append("");
            l.setText(status.toString());
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
            }
        }

    }
}
Read More

January 25, 2013

HTML, JavaScript Snake v1.2

12 comments:
Read More

December 16, 2012

Display random labels on blogspot blog

2 comments:
This Javascript snippet will retrieve random labels from a blogspot blog and display it in sidebar or anywhere else, useful if you've too many labels and only want show 'x' number of random labels on each page load.

Technology used:

Javascript, YQL, JSON feed

Usage:

- Configure and include the snippet and add label div to blog template/html.

View/Copy snippet:



Or Download: http://pastebin.com/raw.php?i=PkZY87yV
Read More

November 25, 2012

JSP, HTML basic snake game

2 comments:
Who doesn't like the "snake" game, right? I'm no exception. I did this basic game just for the fun.

Snake v1





To begin playing, select initial level and snake's length and then start the game.

Demo: http://techno-slab.appspot.com/snake.jsp

Source code: http://pastebin.com/tyYe1SsP
Read More

November 03, 2012

C Program To Add, Subtract or Multiply two Matrices

No comments:
- Add, Subtract or Multiply two Matrices
- Command line based
- Menu driven
- Uses Structs, functions, dynamic allocations etc.

Read More

October 18, 2012

[PHP] URL Shrinking script - download

1 comment:
Setup:

1. Create table, see table.sql
2. Edit configs in index.php
3. Upload

Demo:



Download:

http://www.2shared.com/file/QNbtMalj/short.html
Read More

August 31, 2012

[PHP] Mobile number trace script

8 comments:
A mobile number tracing script that can be easily integrated as a widget or as a standalone page.

Demo: http://technoslab.1x.net/trace



Read More

August 27, 2012

C program to accept length of three sides of a triangle and find out the type of triangle

No comments:
Read More

C program to calculate sum of numbers from 0 to 100 which are divisible by 4

1 comment:
Read More

C program to obtain five numbers from user and display them back in ascending order

1 comment:


Source uploaded to Pastebin.com

* Users Bubble Sort algorithm

Here's an animation from Wikipedia explaining Bubble sort. 


Read More

August 24, 2012

Easy to Integrate Way2SMS sender for Wapsites

3 comments:

  • Sends SMS from Way2SMS servers via ubaid.tk API
  • Easy to Integrate
  • Single file source
  • Clean interface
Read More

August 20, 2012

Basic Command Line Calculator source in C

1 comment:
I'm officially learning C now and this is a small program I put together just to practice what I learned. Have fun!
Read More

May 22, 2012

MyBB plugin - IP history

11 comments:
Information:
Displays a list of recent IP addresses that were used to access forum from your account. It  also displays time alongside.

Purpose:
Keep track of your own IP.
Find who used your account in case someone accesses it illegally.

Technologies used:
PHP, MySQL, MyBB and JSON.

Screenshot:

Installation notes:
- Upload ip_history.php to MYBB_ROOT/inc/plugins
- Go to Admin panel - Plugins - Install and activate ip_history plugin
- Done
Read More

April 30, 2012

How to send email from a Java program via Gmail's SMTP server

No comments:
This Java function uses your Email, Password to send a Message to other Email address via Gmail's SMTP server.









Download JavaMail Library: http://www.oracle.com/technetwork/java/javamail/index-138643.html
Extract the Zip Archive
Import mail.jar into your project



Download
Read More

April 20, 2012

Way2SMS desktop application

13 comments:

Why use it?

It's a simple portable Java application that you can place on your desktop and simply click to send quick text messages to near and dear ones. It does not use any third party API services so your login credentials as safe as they are with you because this application sends every request directly to way2sms's server.



It is a Java application so you must have JRE installed on your PC to run it.

Download: http://www.2shared.com/file/Cq5HUbDB/way2smsApp.html

Here's the source in case you want to check it out. http://pastebin.com/raw.php?i=T4rprvS8
Read More

April 01, 2012

How to use PHP Built-in webserver

1 comment:
PHP 5.4 supports a built-in web server which can be used for testing purpose which is good because we can test scripts quickly without having to install Apache.
This post aims to explain how to start, use and stop this web server.

1. Download and extract PHP 5.4.0 on your system. Follow this guide if you are an XAMPP user.

2. Open console ( Start -> Run -> cmd on Windows ) and navigate to PHP's current directory.

 

3. Now execute following command to start the build-in server:
php -S localhost:5555

Here we are telling PHP to start local server on port 5555


If everything works fine you'll see a message saying "PHP development server has started".
PHP will also output errors and warnings. ( In my case DLL for zip extension if missing )

Now lets see if our server is listening and responding to requests.

4. Create a simple index.php in Document Root. ( F:\Installs\Xampp\php\ in my case )

5. Open your favorite browser. I use Firefox.

6. Go to this URL: http://localhost:5555/index.php

7. You should see something like this.


Congratulations! The Built-in webserver is working properly and responding to requests and we can now test our script even without installing Apache on our Systems. Note that this built-in PHP server should not be used in production but only for testing.
Read More

March 29, 2012

PHP script - retrieve email from your Gmail account

1 comment:
This script can be used to retrieve recent emails from your Gmail account. It was developed in hurry and is meant to provide a sort of conceptual base for more advanced scripts/programs.
Usage:
Just declare some variables in the top section of the script and run it. You can also extend it to do advance stuffs like read and automatically delete spam mails, create auto responders etc.
Requirement: 
Your server must have imap extension.
DOWNLOAD 
Do inform me if you use it or released an extended version of this script. :)
Read More

March 10, 2012

Post to your Google plus stream with a bookmarklet

2 comments:
With this bookmarklet, you can post to your Google plus stream about current page.







[Drag me to bookmark toolbar]
Read More

March 08, 2012

Download Vatikag.com download portal script

9 comments:


Planning to host a download portal ?







Vatikag CMS is a simple but powerful content management system designed primarily to quickly create and maintain file download portals. It sports exciting features like automatic thumbnail creation, image watermarking, mobile optimized view etc. The CMS is also heavily search engine optimized to boost your rankings and traffic.


Check out this CMS in action on vatikag.com

PS:
* This is not a clone but the actual script.
* The source was released by it's author on his website.

Download the first version of this popular CMS: http://www.4shared.com/zip/13GQMvLh/vcms.html
Read More