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:
Because Retro is cool!

Source:

Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Snake v1.2</title>
  5. <script type="text/javascript">
  6.  
  7. /**
  8. * @author Manish Raj
  9. * @version 1.2
  10. * @website http://www.technoslab.in/
  11. */
  12.  
  13. window.onload = function(){
  14.  
  15. // Constants
  16. var KEY_UP = 38;
  17. var KEY_LEFT = 37;
  18. var KEY_DOWN = 40;
  19. var KEY_RIGHT = 39;
  20. var DIR_UP = 38;
  21. var DIR_LEFT = 37;
  22. var DIR_DOWN = 40;
  23. var DIR_RIGHT = 39;
  24.  
  25. // Play ground width and height
  26. var ground_width = window.innerWidth;
  27. var ground_height = window.innerHeight;
  28.  
  29. // Snake configurations
  30. var snake_width = 15;
  31. var snake_audio = new Audio("b.ogg");
  32. var snake_speed = 100;
  33. var snake_initial_length = 1;
  34. var snake_color = '#FFFFFF';
  35. var food_color = '#FFFFFF';
  36.  
  37. var game_level = 0;
  38. var speed_increment = 10;
  39. var game_score = 0;
  40.  
  41. var body = document.getElementsByTagName('body')[0];
  42.  
  43. var set_style = function(element, styles){
  44. for (var key in styles){
  45. element.style[key] = styles[key];
  46. }
  47. }
  48.  
  49. set_style(body, {
  50. 'padding' : '0px',
  51. 'margin' : '0px'
  52. });
  53.  
  54. // Snake ground
  55. var snake_ground = document.createElement("div");
  56. set_style(snake_ground, {
  57. 'background' : '#000000',
  58. 'display' : 'block',
  59. 'width' : ground_width + 'px',
  60. 'height' : ground_height + 'px',
  61. 'margin' : '0px;',
  62. 'padding' : '0px',
  63. 'position' : 'relative',
  64. 'overflow' : 'hidden'
  65. });
  66.  
  67. // Add snake ground
  68. body.appendChild(snake_ground);
  69.  
  70. // Food block
  71. var food = document.createElement("div");
  72.  
  73. var food_position = [0,0]
  74.  
  75. var boundary = 50;
  76. var max1 = ground_width - boundary;
  77. var max2 = ground_height - boundary;
  78. var min1 = snake_width + boundary;
  79. var min2 = snake_width + boundary;
  80.  
  81. var map_food_position = function(){
  82. food_position[0] = Math.floor((Math.random() * (max1 - min1) + min1)/min1) * min1;
  83. food_position[1] = Math.floor((Math.random() * (max2 - min2) + min2)/min2) * min2;
  84. }
  85.  
  86. map_food_position();
  87. set_style(food, {
  88. 'background' : food_color,
  89. 'display' : 'block',
  90. 'width' : snake_width + 'px',
  91. 'height' : snake_width + 'px',
  92. 'position' : 'absolute',
  93. 'left' : food_position[0] + 'px',
  94. 'top' : food_position[1] + 'px',
  95. 'border' : '2px solid #000000'
  96. });
  97.  
  98. // Add food block to ground
  99. snake_ground.appendChild(food);
  100.  
  101. // Game stats
  102. var game_stat_right = document.createElement('div');
  103. set_style(game_stat_right, {
  104. 'display' : 'block',
  105. 'position' : 'absolute',
  106. 'right' : '10px',
  107. 'top' : '10px',
  108. 'font' : 'bold 25px Arial',
  109. 'color' : '#FFFFFF'
  110. });
  111.  
  112. var game_stat_left = document.createElement('div');
  113. set_style(game_stat_left, {
  114. 'display' : 'block',
  115. 'position' : 'absolute',
  116. 'left' : '10px',
  117. 'top' : '10px',
  118. 'font' : 'bold 25px Arial',
  119. 'color' : '#FFFFFF'
  120. });
  121.  
  122. // Add game stats to ground
  123. snake_ground.appendChild(game_stat_right);
  124. snake_ground.appendChild(game_stat_left);
  125.  
  126.  
  127. // Snake
  128. var snake = new Array();
  129.  
  130. // Define first two blocks or elements of snake
  131. snake[0] = [Math.floor((Math.random() * (max1 - min1) + min1)/min1) * min1, Math.floor((Math.random() * (max2 - min2) + min2)/min2) * min2];
  132. for(var i = 1; i <= snake_initial_length; i++){
  133. snake[i] = [snake[0][0] - i * snake_width, snake[0][1]];
  134. }
  135.  
  136. // Set initial direction to right
  137. var snake_direction = DIR_RIGHT;
  138.  
  139. // Variable to track game position
  140. var game_over = false;
  141.  
  142. // Loop for as long as needed
  143. var game_loop =
  144. function(){
  145. if(!game_over){
  146.  
  147. move_snake({keyCode : snake_direction});
  148. window.setTimeout(game_loop, snake_speed - speed_increment * game_level);
  149. }else{
  150. var gameover_dialog = document.createElement("div");
  151. set_style(gameover_dialog, {
  152. 'display' : 'block',
  153. 'position' : 'absolute',
  154. 'width' : '400px',
  155. 'height' : '100px',
  156. 'font' : 'bold 25px Arial',
  157. 'color' : 'orangered',
  158. 'background' : '#DDDDDD',
  159. 'left' : '50%',
  160. 'top' : '50%',
  161. 'marginLeft' : '-200px',
  162. 'marginTop' : '-50px',
  163. 'z-index' : '99',
  164. 'textAlign' : 'center'
  165. });
  166. gameover_dialog.innerHTML = 'GAME OVER!';
  167. gameover_dialog_button = document.createElement('button');
  168. set_style(gameover_dialog_button, {
  169. 'display' : 'block',
  170. 'margin' : 'auto',
  171. 'font' : 'bold 15px Merienda',
  172. });
  173. gameover_dialog_button.innerHTML = 'Click To Play Again';
  174. gameover_dialog_button.onclick = function(){
  175. document.location.reload(false);
  176. }
  177. gameover_dialog.appendChild(gameover_dialog_button);
  178. body.appendChild(gameover_dialog);
  179. gameover_dialog_button.focus();
  180. }
  181. }
  182.  
  183. window.setTimeout(game_loop, snake_speed);
  184.  
  185.  
  186. // Add keyDown event handler
  187. document.onkeydown = function(e){
  188. move_snake({keyCode : e.keyCode});
  189. };
  190.  
  191. // Move snake according to direction
  192. var move_snake = function(e){
  193.  
  194. // Ignore keyDown events if game is over
  195. if(game_over){
  196. return null;
  197. }
  198.  
  199. // Prevent snake from moving in reverse direction
  200. if(snake_direction == DIR_UP && e.keyCode == KEY_DOWN){
  201. return null;
  202. }
  203.  
  204. if(snake_direction == DIR_RIGHT && e.keyCode == KEY_LEFT){
  205. return null;
  206. }
  207.  
  208. if(snake_direction == DIR_LEFT && e.keyCode == KEY_RIGHT){
  209. return null;
  210. }
  211.  
  212. if(snake_direction == DIR_DOWN && e.keyCode == KEY_UP){
  213. return null;
  214. }
  215.  
  216. // If one of the four navigation keys was pressed
  217. if(e.keyCode == KEY_UP || e.keyCode == KEY_LEFT || e.keyCode == KEY_DOWN || e.keyCode == KEY_RIGHT){
  218.  
  219. // Store position of last block, will be used when adding new tail block i.e. when snake's head eats food block
  220. var last_x_position = snake[snake.length - 1][0];
  221. var last_y_position = snake[snake.length - 1][1];
  222.  
  223. // Update every element to move to position of block ahead
  224. for(var i = snake.length - 1; i > 0 ; i--){
  225. snake[i][0] = snake[i-1][0];
  226. snake[i][1] = snake[i-1][1];
  227. }
  228.  
  229. // If UP key was pressed ( basically released )
  230. if(e.keyCode == KEY_UP){
  231. snake[0][1] -= snake_width;
  232. snake_direction = DIR_UP;
  233. }
  234.  
  235. // If LEFT key was pressed
  236. if(e.keyCode == KEY_LEFT){
  237. snake[0][0] -= snake_width;
  238. snake_direction = DIR_LEFT;
  239. }
  240.  
  241. // If DOWN key was pressed
  242. if(e.keyCode == KEY_DOWN){
  243. snake[0][1] += snake_width;
  244. snake_direction = DIR_DOWN;
  245. }
  246.  
  247. // If RIGHT key was pressed
  248. if(e.keyCode == KEY_RIGHT){
  249. snake[0][0] += snake_width;
  250. snake_direction = DIR_RIGHT;
  251. }
  252.  
  253. // Wrap the snake at right egde
  254. if(snake[0][0] > ground_width){
  255. snake[0][0] = 0;
  256. }
  257.  
  258. // Wrap the snake at bottom edge
  259. if(snake[0][1] > ground_height){
  260. snake[0][1] = 0;
  261. }
  262.  
  263. // Wrap the snake at left edge
  264. if(snake[0][0] < 0){
  265. snake[0][0] = ground_width;
  266. }
  267.  
  268. // Wrap the snake at top edge
  269. if(snake[0][1] < 0){
  270. snake[0][1] = ground_height;
  271. }
  272.  
  273. for(var i = 1; i < snake.length; i++){
  274. if(snake[0][0] == snake[i][0] && snake[0][1] == snake[i][1]){
  275. game_over = true;
  276. }
  277. }
  278.  
  279. }
  280.  
  281. // If snake's head has approached a food block
  282. if(Math.abs(snake[0][0] - food_position[0]) < snake_width && Math.abs(snake[0][1] - food_position[1]) < snake_width){
  283.  
  284. // Add a new tail block
  285. snake[snake.length] = [last_x_position, last_y_position];
  286.  
  287. game_score++;
  288. if(game_score != 0 && game_score%10 == 0 && game_level != 10){
  289. game_level++;
  290. }
  291.  
  292. // Play the audio
  293. snake_audio.play();
  294.  
  295. // Find and update food block's new position
  296. map_food_position();
  297. set_style(food, {
  298. 'left' : food_position[0] + 'px',
  299. 'top' : food_position[1] + 'px'
  300. });
  301. }
  302.  
  303. game_stat_left.innerHTML = 'Score: ' + game_score;
  304. game_stat_right.innerHTML = 'Level: ' + (game_level + 1);
  305.  
  306. // Add or modify snake blocks on each event
  307. for(var i = 0; i < snake.length; i++){
  308. var snake_elem = document.getElementById("snake_"+i);
  309. if(snake_elem == null){
  310. snake_elem = document.createElement("div");
  311. snake_elem.setAttribute("id", "snake_"+i);
  312. set_style(snake_elem, {
  313. 'position' : 'absolute',
  314. 'display' : 'block',
  315. 'width' : snake_width + 'px',
  316. 'height' : snake_width + 'px',
  317. 'border' : '0px solid #000000',
  318. 'background' : snake_color
  319. });
  320. snake_ground.appendChild(snake_elem);
  321. }
  322. set_style(snake_elem, {
  323. 'left' : snake[i][0] + 'px',
  324. 'top' : snake[i][1] + 'px'
  325. });
  326. }
  327.  
  328. };
  329.  
  330. }
  331. </script>
  332. </head>
  333. <body>
  334. <noscript>
  335. <h1 style="text-align: center;">Please use a Javascript enabled web browser. Thank you.</h1>
  336. </noscript>
  337. </body>
  338. </html>


Download: http://pastebin.com/raw.php?i=gEdVMMJG

Demo: http://pastehtml.com/view/cqkp8hmf1.html
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:

Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1.     /**
  2.     * @author Manish Raj
  3.     * @website http://www.technoslab.in
  4.     */
  5.    
  6.     // Configure
  7.     var blog_url = 'www.technoslab.in'; // Just the host. Example. yourblog.blogspot.com
  8.     var max_labels = 50; // Maximum number of random labels to show.
  9.     var label_element = 'labels'; // id of the element where labels would be displayed. Example: <div id="labels"></div>
  10.    
  11.     function showLabels(){
  12.         var queryUrl = 'http://query.yahooapis.com/v1/public/yql?q=select%20feed.category%20from%20json%20where%20url%3D%22http%3A%2F%2F' + blog_url + '%2Ffeeds%2Fposts%2Fsummary%3Falt%3Djson%26max-results%3D0%22&format=json&callback=labelCb'
  13.         var script = document.createElement('script');
  14.         script.setAttribute('type', 'text/javascript');
  15.         script.setAttribute('src', queryUrl);
  16.         document.getElementsByTagName('body')[0].appendChild(script);
  17.     }
  18.    
  19.     // Label Callback
  20.     function labelCb(response){
  21.         var html = '';
  22.         if(response.query.count > 0){
  23.             response.query.results.json = response.query.results.json.shuffle();
  24.             for(var i = 0; i < response.query.count && i < max_labels; i++){
  25.                 html += '<a href="http://'+blog_url+'/search/label/'+response.query.results.json[i].feed.category.term+'">'+response.query.results.json[i].feed.category.term+'</a>, ';
  26.             }
  27.         }
  28.         document.getElementById(label_element).innerHTML = html;
  29.     }
  30.    
  31.     // From SO: http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array-in-javascript
  32.     Array.prototype.shuffle = function () {
  33.     for (var i = this.length - 1; i > 0; i--) {
  34.         var j = Math.floor(Math.random() * (i + 1));
  35.         var tmp = this[i];
  36.         this[i] = this[j];
  37.         this[j] = tmp;
  38.     }
  39.         return this;
  40.     }
  41.    
  42.     // Load and show labels
  43.     window.onload = function(){
  44.         showLabels();
  45.     }


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.

Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. #include <stdio.h>
  2. #include <conio.h>
  3. #include <stdlib.h>
  4.  
  5. struct matrix{
  6.   int **elements;
  7.   int rows;
  8.   int cols;
  9. };
  10.  
  11. matrix read(){
  12.   int rows = 0, cols = 0, i, j;
  13.   matrix m = {NULL, 0, 0};
  14.   printf("\nEnter the number of rows: ");
  15.   scanf("%d", &rows);
  16.   printf("\nEnter the number of columns: ");
  17.   scanf("%d", &cols);
  18.   if( rows <= 0 || cols <= 0){
  19.     printf("%dx%d matrix does not exist!", rows, cols);  
  20.   }else {
  21.     m.rows = rows;
  22.     m.cols = cols;
  23.     m.elements = (int **)malloc(m.rows * sizeof(int *));
  24.     for( i = 0; i < rows; i++){
  25.       m.elements[i] = (int *)malloc(m.cols * sizeof(int));
  26.       for( j = 0; j < cols; j++){
  27.         printf("\nEnter element at %d x %d: ", i + 1, j + 1);
  28.         scanf("%d", &m.elements[i][j]);
  29.       }
  30.     }
  31.   }
  32.   return m;
  33. }
  34.  
  35. void display(char msg[], matrix m){
  36.   int i, j;
  37.   printf("\n========== %s ==========\n", msg);
  38.   for(i = 0; i < m.rows; i++){
  39.     for(j = 0; j < m.cols; j++){
  40.       printf("%d\t", m.elements[i][j]);
  41.     }
  42.     printf("\n");
  43.   }
  44. }
  45.  
  46. matrix process(matrix m1, matrix m2, char opr){
  47.   int i, j, k;
  48.   matrix m = {NULL, 0, 0};
  49.   if((opr == '1' || opr == '2') && (m1.rows != m2.rows || m1.cols != m2.cols)){
  50.     printf("\nMatrix addition or subtraction is not possible since number of rows and columns of the two matrices are not equal.");
  51.   }else if(opr == '3' && m1.cols != m2.rows){
  52.     printf("\nMatrix multiplication is not possible since number of columns of first matrix is not equal to number of rows of second matrix.");
  53.   }else{
  54.     if(opr == '1' || opr == '2'){
  55.       m.rows = m1.rows;
  56.       m.cols = m1.cols;
  57.       m.elements = (int **)malloc(m.rows * sizeof(int *));
  58.       for(i = 0; i < m1.rows; i++){
  59.         m.elements[i] = (int *)malloc(m.cols * sizeof(int));
  60.         for( j = 0; j < m1.cols; j++){
  61.           if(opr == '1'){
  62.             m.elements[i][j] = m1.elements[i][j] + m2.elements[i][j];
  63.           }else if(opr == '2'){
  64.             m.elements[i][j] = m1.elements[i][j] - m2.elements[i][j];
  65.           }
  66.         }
  67.       }
  68.     }else if(opr == '3'){
  69.       m.rows = m1.rows;
  70.       m.cols = m2.cols;
  71.       m.elements = (int **)malloc(m.rows * sizeof(int *));
  72.       for(i = 0; i < m1.rows; i++){
  73.         m.elements[i] = (int *)malloc(m.cols * sizeof(int));
  74.         for( j = 0; j < m2.cols; j++){
  75.           m.elements[i][j] = 0;
  76.           for(k = 0; k < m2.rows; k++){
  77.             m.elements[i][j] += m1.elements[i][k] * m2.elements[k][j];
  78.           }
  79.         }
  80.       }
  81.     }
  82.   }
  83.   return m;
  84. }
  85.  
  86. int main(){
  87.   while(1){
  88.     printf("\nPress 1 to add two matrices\nPress 2 to subtract\nPress 3 to multiply two matrices\nPress q to quit");
  89.     char opt = getch();
  90.     if(opt == 'q' || opt == 'Q'){
  91.       break;
  92.     }
  93.     matrix m1 = read();
  94.     matrix m2 = read();
  95.     if(m1.elements != NULL && m2.elements != NULL && (opt == '1' || opt == '2' || opt == '3')){
  96.       matrix m3 = process(m1, m2, opt);
  97.       if(m3.elements != NULL){
  98.         display("Matrix 1", m1);
  99.         display("Matrix 2", m2);
  100.         display("Result", m3);
  101.       }
  102.     }
  103.   }
  104.   return 0;
  105. }
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

17 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:
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. #include <stdio.h>
  2. #include <conio.h>
  3.  
  4. int main(){
  5.     int s1;
  6.     int s2;
  7.     int s3;
  8.     printf("Enter side 1: ");
  9.     scanf("%d", &s1);
  10.     printf("Enter side 2: ");
  11.     scanf("%d", &s2);
  12.     printf("Enter side 3: ");
  13.     scanf("%d", &s3);
  14.     printf("Triangle is ");
  15.     if(s1 == s2 && s1 == s3){
  16.         printf("Equilateral");
  17.     }else if(s1 == s2 || s2 == s3 || s1 == s3){
  18.         printf("Isoscles");
  19.         if(s1*s1 == s2*s2 + s3*s3 || s1*s1 == s2*s2 - s3*s3 || s1*s1 == - s2*s2 + s3*s3){
  20.             printf(" and is Right Angled");
  21.         }
  22.     }else{
  23.         printf("Scalene");
  24.         if(s1*s1 == s2*s2 + s3*s3 || s1*s1 == s2*s2 - s3*s3 || s1*s1 == - s2*s2 + s3*s3){
  25.             printf(" and is Right Angled");
  26.         }
  27.     }
  28.     printf(".");
  29.     getch();
  30.     return 0;
  31. }
Read More

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

1 comment:
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. #include <stdio.h>
  2. #include <conio.h>
  3.  
  4. int main(){
  5.     int i;
  6.     int sum = 0;
  7.     for(i = 0; i <= 100; i++){
  8.         if(i % 4 == 0){
  9.             sum = sum + i;
  10.         }
  11.     }
  12.     printf("Sum: %d", sum);
  13.     getch();
  14.     return 0;
  15. }
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. 


Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. #include <stdio.h>
  2. #include <conio.h>
  3.  
  4. int main(){
  5.  
  6.     const int length = 5;
  7.     int numbers[length];
  8.     int swapped;
  9.     int temp;
  10.     int i;
  11.    
  12.     for(i = 0; i < length; i++){
  13.         printf("Enter number %d: ", i + 1);
  14.         scanf("%d", &numbers[i]);
  15.     }
  16.  
  17.     /* Implement Bubble sort Algorithm */
  18.     while(1){
  19.         swapped = 0;
  20.         for(i = 0; i < length - 1; i++){
  21.             if(numbers[i] > numbers[i+1]){
  22.                 temp = numbers[i];
  23.                 numbers[i] = numbers[i+1];
  24.                 numbers[i+1] = temp;
  25.                 swapped = 1;
  26.             }
  27.         }
  28.         if(swapped == 0){
  29.             break;
  30.         }
  31.     }
  32.    
  33.     for(i = 0; i < length; i++){
  34.         printf("Number %d = %d\n", i+1, numbers[i]);
  35.     }
  36.    
  37.     getch();
  38.     return 0;
  39. }
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!
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. /*
  2. ===================================
  3. Program: Calculate version 1.0
  4. Author: Manish Raj
  5. Website: http://www.technoslab.in/
  6. Description: Simple CLI calculator for beginners
  7. ===================================
  8. */
  9.  
  10. /* Include header files */
  11. #include <stdio.h>
  12. #include <conio.h>
  13.  
  14. /* Begin main method */
  15. int main(){
  16.  
  17.     /* Display program information */
  18.     printf("\nCalculate v1 by Manish");
  19.    
  20.     /* Declare variables */
  21.     char cmd, oprt;
  22.     int num1, num2;
  23.    
  24.     /* Loop infinitely till 'x' is pressed */
  25.     while(1){
  26.    
  27.         /* Initialize variables to default value on each iteration */
  28.         cmd = '?';
  29.         oprt = '?';
  30.         num1 = 0;
  31.         num2 = 0;
  32.        
  33.         /* Ask user for action to be performed */
  34.         printf("\nPress x to exit, Press c to calculate: ");
  35.         cmd = getch();
  36.         if(cmd == 'X' || cmd == 'x'){
  37.        
  38.             /* If 'x' was pressed -> exit */
  39.             printf("%c", cmd);
  40.             break;
  41.         }
  42.         else if(cmd == 'c' || cmd == 'C'){
  43.            
  44.             /* If 'c' was pressed -> calculate */
  45.             printf("%c", cmd);
  46.            
  47.             /* Display instructions */
  48.             printf("\nEnter expression in this form - number1 operator number2.\nAllowed operators: + , -, *, /, %.\nExample: 2 + 2\nEnter now:");
  49.             scanf("%d %c %d", &num1, &oprt, &num2);
  50.            
  51.             /* Begin calculation */
  52.             switch(oprt){
  53.                 case '+' :
  54.                     printf("%d %c %d = %d", num1, oprt, num2, num1 + num2);
  55.                     break;
  56.                 case '-' :
  57.                     printf("%d %c %d = %d", num1, oprt, num2, num1 - num2);
  58.                     break;
  59.                 case '*' :
  60.                     printf("%d %c %d = %d", num1, oprt, num2, num1 * num2);
  61.                     break;
  62.                 case '/' :
  63.                     if( num2 == 0){
  64.                         printf("%d %c %d = Math Error. You can not divide any number by 0", num1, oprt, num2);
  65.                     }else{
  66.                         printf("%d %c %d = %d", num1, oprt, num2, num1 / num2);
  67.                     }
  68.                     break;
  69.                 case '%' :
  70.                     printf("%d %c %d = %d", num1, oprt, num2, num1 % num2);
  71.                     break;
  72.                 default:
  73.                     printf("Invalid expression. Operator %c is not allowed. Try again!", oprt);
  74.                     break;
  75.             }
  76.         }else{
  77.            
  78.             /* Display error */
  79.             printf("\nInvalid selection. Try again!");
  80.         }
  81.     }
  82.  
  83.     /* Display exit message */
  84.     printf("\nThank you for using the program.");
  85.  
  86.     /* Return 0 to OS */
  87.     return 0;
  88. }
Read More

May 22, 2012

MyBB plugin - IP history

10 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


Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1.     public void sendMailViaGmail(final String email, final String password, String sendTo, String subject, String body) {
  2.         java.util.Properties properties = new java.util.Properties();
  3.         properties.put("mail.smtp.auth", "true");
  4.         properties.put("mail.smtp.starttls.enable", "true");
  5.         properties.put("mail.smtp.host", "smtp.gmail.com");
  6.         properties.put("mail.smtp.port", "587");
  7.         javax.mail.Session session = javax.mail.Session.getInstance(properties, new javax.mail.Authenticator() {
  8.  
  9.             protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
  10.                 return new javax.mail.PasswordAuthentication(email, password);
  11.             }
  12.         });
  13.         try {
  14.             javax.mail.Message message = new javax.mail.internet.MimeMessage(session);
  15.             message.setFrom(new javax.mail.internet.InternetAddress(email));
  16.             message.setRecipients(javax.mail.Message.RecipientType.TO, javax.mail.internet.InternetAddress.parse(sendTo));
  17.             message.setSubject(subject);
  18.             message.setText(body);
  19.             javax.mail.Transport.send(message);
  20.         } catch (Exception e) {
  21.             System.out.println(e);
  22.         }
  23.     }

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.
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. <?php
  2.  
  3. session_start() ;
  4.  
  5. //error_reporting(-1);
  6.  
  7. error_reporting( 0 ) ;
  8.  
  9. // DEFINE VARIABLES.
  10.  
  11. $pass = "ZZZZZ" ; // password to access this page.
  12.  
  13. $gmail_username = "myusername@gmail.com" ; // your google account username.
  14.  
  15. $gmail_password = "mypassword" ; //  your google account password.
  16.  
  17. $perpage = 20 ; // number of mails to be display per page.
  18.  
  19. if ( isset( $_POST['pass'] ) )
  20. {
  21.  
  22.     if ( $pass == $_POST['pass'] )
  23.     {
  24.  
  25.         $_SESSION['logged'] = 1 ;
  26.  
  27.     }
  28.  
  29.     else
  30.     {
  31.  
  32.         echo "Invalid Login Details !" ;
  33.  
  34.     }
  35.  
  36. }
  37.  
  38. ?>
  39.  
  40. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  41.  
  42. <html xmlns="http://www.w3.org/1999/xhtml">
  43.  
  44. <head>
  45.  
  46. <title>FETCH MAIL</title>
  47.  
  48. <style type="text/css">
  49.  
  50. body{font:12px sans-serif;background:rgb(210,210,250);}
  51.  
  52.     .topbar{background:rgb(150,0,250);font:15px cursive;font-weight:bold;color:white;border:1px solid silver;padding:5px;}
  53.  
  54.         .message{background:rgb(255,255,255);border:1px solid rgb(0,0,155);padding:5px;}
  55.  
  56.         .mailbox{border:1px dashed silver;padding:5px;}
  57.  
  58.     input,submit,select{padding:3px;font:12px cursive;font-weight:bold;background:transparent;border:1px solid rgb(50,50,50);}
  59.  
  60. .header{font:40px 'script mt bold';font-weight:bold;color:purple;}
  61.  
  62. </style>
  63.  
  64. </head>
  65.  
  66. <body>
  67.  
  68. <?php
  69.  
  70. if ( ! isset( $_SESSION['logged'] ) && ! isset( $_POST['pass'] ) )
  71. {
  72.  
  73.     exit( "Please Log In<form method='post'><input type='password' name='pass'><input type='submit' value='Go'></form>" ) ;
  74.  
  75. }
  76.  
  77. $link = imap_open( "{imap.gmail.com:993/imap/ssl}INBOX", $gmail_username, $gmail_password ) or exit( "Connection  aborted: " . imap_last_error() ) ;
  78.  
  79. $mails = imap_search( $link, 'ALL' ) ;
  80.  
  81. rsort( $mails ) ;
  82.  
  83. $total = count( $mails ) ;
  84.  
  85. if ( isset( $_GET['page'] ) )
  86. {
  87.  
  88.     if ( is_numeric( $_GET['page'] ) )
  89.     {
  90.  
  91.         $begin = round( $_GET['page'], 0 ) * $perpage ;
  92.  
  93.     }
  94.  
  95.     else
  96.     {
  97.  
  98.         $begin = $total ;
  99.  
  100.     }
  101.  
  102. }
  103. else
  104. {
  105.  
  106.     $begin = $total ;
  107.  
  108. }
  109.  
  110. echo "<table class='main'><tr><td><h2 class='header'>FETCH EMAIL</h2></td></tr><tr><td>" ;
  111.  
  112. for ( $i = $begin; $i >= $begin - $perpage; $i-- )
  113. {
  114.  
  115.     if ( $i <= $total )
  116.     {
  117.  
  118.         $overview = imap_fetch_overview( $link, $i, 0 ) ;
  119.  
  120.         $message = imap_fetchbody( $link, $i, 2 ) ;
  121.  
  122.         $message = preg_replace( "@<style.+?</style>@is", "", $message ) ;
  123.  
  124.         $message = strip_tags( $message ) ;
  125.  
  126.         $read = ( $overview[0]->seen == 0 ) ? 'NOT READ YET' : 'ALREADY READ' ;
  127.  
  128.         echo "
  129. <div class='mailbox'>
  130.  
  131. <br/>
  132.  
  133. <div class='topbar'>
  134.  
  135. [ $i ]. SUBJECT : {$overview[0]->subject} || SENT FROM: {$overview[0]->from} || SENT AT: {$overview[0]->date} || $read
  136.  
  137. </div>
  138.  
  139. <br/>
  140.  
  141. <div class='message'>
  142.  
  143. <pre>{$message}</pre>
  144.  
  145. </div>
  146.  
  147. </div>
  148. " ;
  149.     }
  150.  
  151. }
  152.  
  153. echo "</td></tr></table>" ;
  154.  
  155. // pagination
  156.  
  157. echo "<table class='nav'><tr><td>" ;
  158.  
  159. if ( $begin > 0 )
  160. {
  161.     $pre = $begin - 1 ;
  162.  
  163.     echo "<form method='get' action=''>
  164.  
  165.        <input type='hidden' name='page' value='{$pre}' />
  166.  
  167.        <input type='submit' value='Previous' />
  168.  
  169.        </form>" ;
  170.  
  171. }
  172.  
  173. echo "</td><td>" ;
  174.  
  175. if ( $begin < $total )
  176. {
  177.  
  178.     $nxt = $begin + 1 ;
  179.  
  180.     echo "<form method='get' action=''>
  181.  
  182.    <input type='hidden' name='page' value='{$nxt}' />
  183.  
  184.    <input type='submit' value='Previous' />
  185.  
  186.    </form>" ;
  187.  
  188. }
  189.  
  190. echo "</td><td>" ;
  191.  
  192. $factor = round( $total / $perpage, 0 ) ;
  193.  
  194. echo "<form method='get' action=''>
  195.  
  196. <select name='page'>
  197. " ;
  198.  
  199. while ( $factor >= 0 )
  200. {
  201.     echo "<option value='{$factor}'>{$factor}</option>" ;
  202.     $factor-- ;
  203. }
  204.  
  205. echo "</select> <input type='submit' value='Goto Page'></form>" ;
  206.  
  207. echo "</td></tr></table>" ;
  208.  
  209. ?>
  210.  
  211.  
  212. </body>
  213.  
  214. </html>

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.



Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. javascript:window.location='https://plusone.google.com/_/+1/confirm?hl=en&url='+window.location;




[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