Posts

Showing posts from 2015

Creating custom category attribute in Magento

In this short article contains code for  creating custom category attribute in Magento  . Run this script from your magento root folder and it will create custom attribute of type int in General group. To test whether attribute is created or not Go to your magento admin panel > catelog > manage categories and user General tab you will see  Most Popular Products attribute . <?phprequire_once('app/Mage.php');Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));$installer = new Mage_Sales_Model_Mysql4_Setup;$attribute = array( 'group' => 'General', 'type' => 'int', 'label' => 'Most Popular Products', 'input' => 'select', 'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL, 'visible' => true, 'required' => false, 'user_define

Matlab code for uploading images to FTP server

Following is the MATLAB Code for establishing connection with remote FTP Server and uploading image files to this Server. main_path='C:\Users\Dell\Downloads\TakeVideoTakeVideoframes';mov_path='C:\Users\Dell\Downloads\TakeVideoTakeVideoframes2';if ~exist(mov_path, 'dir')        mkdir(mov_path);end;a=dir(main_path);f = ftp('ftp.servername.com','uname','pass');cd(f,'matlab');k = 1;while ~isempty(a)fullfilename = [main_path int2str(k) '.png'];%movfullfname = [mov_path int2str(k) '.png'];disp(fullfilename);x=exist(fullfilename,'file');if x > 0x=1;end;if x        temp=0;        mput(f,fullfilename );        movefile(fullfilename,mov_path);     end;  k = k+1;      end;  

Matlab code for capturing video from webcam

Following is the Matlab Code for Capturing video from local webcam on computer and storing captured video, video frames to local storage on System. my_log = 'c:/tempfiles/videotest/test2.avi';        aviobj = avifile(my_log, 'compression','Cinepak','fps',10,'quality',100);        vid = videoinput('winvideo',1,'YUY2_640x480');         set(vid, 'ReturnedColorSpace', 'rgb');        %vid.LoggingMode = 'disk&memory';        vid.TriggerRepeat = Inf;            set(vid,'FramesPerTrigger', 50);        start(vid);                     i=0;         outputFolder = fullfile(cd, 'frames');        if ~exist(outputFolder, 'dir')        mkdir(outputFolder);        end;         while 1        i=i+1;                img=getsnapshot(vid);        %either use preview or image        image(img);        pause(0.01);        aviobj=addframe(aviobj,img);        img = imresize(img, (1/2));        outputBase

PHP script for WHOIS Lookup on domain name or IP

This is a PHP script for performing WHOIS lookups on domain name or IP address . This PHP script is intended to lookup for domain registrant data for all top-level domains (both generic and country-code types are supported, 158 TLDs in total), and also for IP whois lookups. <?phpheader('Content-Type: application/json');/*************************************************************************Browse: whoise.php?domain=yourdomain.com*************************************************************************/$domain = $_GET['domain'];// For the full list of TLDs/Whois servers see http://www.iana.org/domains/root/db/ and http://www.whois365.com/en/listtld/$whoisservers = array( "ac" => "whois.nic.ac", // Ascension Island // ad - Andorra - no whois server assigned "ae" => "whois.nic.ae", // United Arab Emirates "aero"=>"whois.aero", "af" => "whois.nic.af", // Afghanistan "ag&qu

How Can Many Users Share the Same Port ( TCP / HTTP Listening )

So, what happens when a server listen for incoming connections on a TCP port? For example, let’s say you have a web-server on port 80. Let’s assume that your computer has the public IP address of 24.14.181.229 and the person that tries to connect to you has IP address 10.1.2.3. This person can connect to you by opening a TCP socket to 24.14.181.229:80. Simple enough. Intuitively (and wrongly), most people assume that it looks something like this: Local Computer  |  Remote Computer ——————————– <local_ip>:80     |  <foreign_ip>:80 🙁  not actually what happens, but this is the conceptual model a lot of people have in mind. This is intuitive, because from the standpoint of the client, he has an IP address, and connects to a server at IP:PORT. Since the client connects to port 80, then his port must be 80 too? This is a sensible thing to think, but actually not what happens. If that were to be correct, we could only serve one user per foreign IP address. Once a remote computer

8086 - Program to draw on screen using mouse (Free Hand Drawing)

Image
 ;Free hand drawing using mousecode segmentstart: mov ax, data mov ds, ax   mov al, 13hmov ah, 0   ; set graphics video mode.int 10h   mov ax, 0    ;initialize mouseint 33h                   mov ax, 1  ;shows mouse cursor         int 33h     start1:               mov ax, 3  ;get cursor positon in cx,dx        int 33h           call putpix ;call procedure         jmp start1       ;defining procedure to print    putpix proc    mov al, 1100b        mov ah, 0ch        shr cx,1           ; cx will get double so we divide it by twoint 10h     ; set pixel.ret     putpix endp     end:     mov ah,4ch     int 21hcode ends end start  

Generate Excel Sheet in PHP

Hello readers, in this post we are going to see the code to  generate excel sheet in PHP by exporting contents from database i.e., directly outputting your query result to excel sheet (.xls file) and adjusting HTTP header fields <?php// DATABASE DETAILS$DB_USERNAME="root";$DB_PASSWORD="root";$DB_HOST="localhost";$DB_NAME="local_test";//ESTABLISHING CONNECTION$conn=mysql_connect($DB_HOST,$DB_USERNAME,$DB_PASSWORD);$db=mysql_select_db($DB_NAME,$conn);if(!$conn)die("Sorry colud not connected to database");$query="SELECT * FROM MY_TABLE";//FIRING QUERY AND COLLECTING RESULT$result = mysql_query($query);// Header info settingsheader("Content-Type: application/xls");header("Content-Disposition: attachment; filename=output.xls");header("Pragma: no-cache");header("Expires: 0");// Define separator (defines columns in excel &amp; tabs in word)$sep = "\t"; // tabbed character// Sta

Determining if Two Trees are Identical - C Programming Tutorial

Image
In this c programming tutorial we are going to see how we can compare two trees to check whether they are identical or not. Two trees are identical when they have same data and arrangement of data is also same. To identify if two trees are identical, we need to traverse both trees simultaneously, and while traversing we need to compare data and children of the trees. Below is the simple Algorithm to compare two trees : sameTree(tree1, tree2)1. If both trees are empty then return 12. Else If both trees are non -empty Check data of the root nodes (tree1->data == tree2->data) Check left subtrees recursively i.e., call sameTree( tree1->left_subtree, tree2->left_subtree) Check right subtrees recursively i.e., call sameTree( tree1->right_subtree, tree2->right_subtree) If a,b and c are true then return 1.3. Else return 0 (one is empty and other is not) Time Complexity : Complexity of the identicalTree() will be according to the tree with lesser number of nodes

Implementing Vector - C Programming Tutorial

In this c programming tutorial we are going to see code for implementing vector in c language or creating array of size N (Any size array) in language. So let’s proceed, in this c programming tutorial we’re just going to create a dynamically sized array of integers. Here’s what the definition of a vector interface might look like: // vector.h#define VECTOR_INITIAL_CAPACITY 100// Define a vector typetypedef struct { int size; // slots used so far int capacity; // total available slots int *data; // array of integers we're storing} Vector;void vector_init(Vector *vector);void vector_append(Vector *vector, int value);int vector_get(Vector *vector, int index);void vector_set(Vector *vector, int index, int value);void vector_double_capacity_if_full(Vector *vector);void vector_free(Vector *vector); Note that we are writing this code in header file and we will be calling it vector.h Implementing Vector Below is the code for implementation of the interface we defined (vector.h

Why we need IPv6 ?

IPv6, the successor standard to IPv4, for existing networks that currently use IPv4 communications could solve the basic problem of the availability of only approximately 4.3 billion IPv4 addresses. Ceasing use of IPv4 addresses and only using IPv6 addresses, however, is impractical and thus maintaining an environment that enables mutual communication between IPv4 and IPv6 (dual stack environment) will be required for a certain period. Completing IPv6 support is therefore considered to require a large amount of both time and money. IPv6 addresses the main problem of IPv4, that is, the exhaustion of addresses to connect computers or host in a packet-switched network. IPv6 has a very large address space and consists of 128 bits as compared to 32 bits in IPv4. Therefore, it is now possible to support 2^128 unique IP addresses, a substantial increase in number of computers that can be addressed with the help of IPv6 addressing scheme. It is widely expected that the Internet will use IPv4 a

8086 program code for snake game

org 100hjmp starts_size equ 7snake dw s_size dup(0)tail dw ?left equ 4bhright equ 4dhup equ 48hdown equ 50hcur_dir db rightwait_time dw 0start:mov ah, 1mov ch, 2bhmov cl, 0bhint 10hgame_loop:mov al, 0mov ah, 05hint 10hmov dx, snake[0]mov ah, 02hint 10hmov al, '*'mov ah, 09hmov bl, 0ehmov cx, 1int 10hmov ax, snake[s_size * 2 - 2]mov tail, axcall move_snakemov dx, tailmov ah, 02hint 10hmov al, ' 'mov ah, 09hmov bl, 0ehmov cx, 1int 10hcheck_for_key:mov ah, 01hint 16hjz no_keymov ah, 00hint 16hcmp al, 1bhje stop_gamemov cur_dir, ahno_key:mov ah, 00hint 1ahcmp dx, wait_timejb check_for_keyadd dx, 4mov wait_time, dxjmp game_loopstop_game:mov ah, 1mov ch, 0bhmov cl, 0bhint 10hretmove_snake proc nearmov ax, 40hmov es, ax mov di, s_

Use of Software Reverse Engineering

Finding malicious code: Many virus and malware detection techniques use reverse engineering to understand how abhorrent code is structured and functions. Through Reversing, recognizable patterns emerge that can be used as signatures to drive economical detectors and code scanners. Discovering unexpected flaws and faults: Even the well-designed system can have holes that result from the nature of our “forward engineering” development techniques. Reverse engineering can help identify flaws and faults before they become mission-critical software failures. Finding the use of others’ code :   In supporting the cognizant use of intellectual property, it is important to understand where protected code or techniques are used in applications. Reverse engineering techniques can be used to detect the presence or absence of software elements of concern. Finding the use of shareware and open source code where it was not intended to be used. In the opposite of the infringing code concern, if a pro

Difference between Dynamic programming and Greedy approach

    In Greedy approach consider greedy choice property, we can make whatever choice seems best at the moment and then solve the sub-problems that arise later. The choice made by a greedy algorithm may depend on choices made so far but not on future choices or all the solutions to the sub-problem. It iteratively makes one greedy choice after another, reducing each given problem into a smaller one. In other words, a greedy algorithm never reconsiders its choices. This is the main difference from dynamic programming, which is exhaustive and is guaranteed to find the solution . After every stage, dynamic programming makes decisions based on all the decisions made in the previous stage, and may reconsider the previous stage’s algorithmic path to solution. For example, let’s say that you have to get from point A to point B as fast as possible, in a given city, during rush hour. A dynamic programming algorithm will look into the entire traffic report, looking into all possible combinations o

Run C program on Android Device - C Programming Tutorial

In this c programming tutorial we are going to see How To run C programs on your android phone you need “ Terminal IDE ” android app installed on your phone. Click here to install this app from play store . Once you have installed Terminal IDE , open it and now will see six buttons there on screen, from those buttons choose Install System , and then scroll down check the checkbox Overwrite ALL and then click Install System . By doing this some basic C / binary system files get installed in your phone (in applications private memory) Next Step is to install gcc on your phone; it will take up to 70MB memory on your phone, to install gcc , go to the main options in app then terminal screen will be opened, type install_gcc on terminal and hit enter from your android keyboard now gcc is installed on your mobile. To test it type cd   ~/system/src/c_examples/chello/ on terminal and hit enter , this will switch the current working directory of terminal to ~/system/src/c_examples/chello/.

C program for finding Optimal Binary Search Tree

Image
//Program for OBST#include<stdio.h>float e[6][6],w[6][6],t;int root[6][6];float p[6],q[6];void obst(int i, int j){ int value = root[i][j]; if(i==value) { printf("left child of k%d is d%d\n",value,value-1); } else { printf("left child of k%d is k%d\n",value,root[i][value-1]); obst(i,value-1); } if(j==value) { printf(" right child of k%d is d%d\n",value,value); } else { printf(" right child of k%d is k%d\n",value,root[value+1][j]); obst(value+1,j); }}int main(){p[1]=0.15;p[2]=0.10;p[3]=0.05;p[4]=0.10;p[5]=0.2;q[0]=0.05;q[1]=0.10;q[2]=0.05;q[3]=0.05;q[4]=0.05;q[5]=0.1;int l,i,n=5,r,j;for(i=1;i<=(n+1);i++){ e[i][i-1]=q[i-1]; w[i][i-1]=q[i-1];}for(l=1;l<=n;l++){ for(i=1;i<=(n-l+1);i++) { j=i+l-1; e[i][j]=10000; w[i][j]=w[i][j-1]+p[j]+q[j]; for(r=i;r<=j;r++) { t=e[i][r-1]+e[r+1][j]+w[i][j]; if(t<e[i][j]) { e[i][j]=t; root[i][j]=r; } } }}printf("w :\n");for(i=1;i<=(n+1);i++){ for(j=i-1;j&

Calculating running program time - C Programming Tutorial

Image
In this c programming tutorial we are going to see how we can calculate actual running time for any c program or algorithm implementation. Below is the code calculates running time

Least Common Sequence program in C

Image
#include<stdio.h>#include<string.h>void main(){ int i,j,m,n; char x[10],y[10],x1[10],y1[10],b[10][10]={ },ans[10]; int c[10][10]; int flag=0,wflag=1,k; int temp_i,temp_j; printf("\nEnter X sequence"); scanf("%s",x1); printf("\nEnter Y sequence"); scanf("%s",y1); m=strlen(x1); n=strlen(y1); x[0]='\0'; y[0]='\0'; for(i=1;i<=m;i++) { c[i][0]=0; x[i]=x1[i-1]; } x[i]=x1[i-1]; for(i=0;i<=n;i++) { c[0][i]=0; y[i+1]=y1[i]; } for(i=1;i<=m;i++) { for(j=1;j<=n;j++) { if(x[i]==y[j]) { c[i][j]=c[i-1][j-1]+1; b[i][j]='\\'; } else if((c[i-1][j])>=(c[i][j-1])) { c[i][j]=c[i-1][j]; b[i][j]='^'; } else { c[i][j]=c[i][j-1]; b[i][j]='<'; } } } printf("\n\ty"); for(j=1;j<=n;j++) { printf("\t%c",y[j]); } printf("\nx"); for(j=0;j<=n;j++) { printf("\t%d",c[j][0]); } printf("\n"); for(i=1;i<=m;i++) { pri

C program for Matrix chain multiplication

Image
#include<stdio.h>#define MAX 10void tree(int,int);int s[MAX][MAX];void main(){int m[MAX][MAX],p[MAX];int i,j,s1,k,l,q;printf("enter the size of P:");scanf("%d",&s1);printf("enter the p values:\n");for(i=0;i<=s1;i++)scanf("%d",&p[i]);for(i=0;i<=s1;i++)printf("%d",p[i]);for(i=1;i<=s1;i++){for(j=1;j<=s1;j++){m[i][j]=0;}}for(l=2;l<=s1;l++){for(i=1;i<=s1-l+1;i++){j=i+l-1;m[i][j]=100000000;for(k=i;k<=j-1;k++){q=m[i][k]+m[k+1][j]+(p[i-1]*p[k]*p[j]);if(q<m[i][j]){m[i][j]=q;s[i][j]=k;}}}}printf("\nMatrix M :\n");for(l=2;l<=s1;l++) { for(i=1;i<=s1-l+1;i++) { j=i+l-1; printf(" %d ",m[i][j]); }printf("\n\n");}printf("\nMatrix S :\n ");for(l=2;l<=s1;l++) { for(i=1;i<=s1-l+1;i++) { j=i+l-1; printf(" %d ",s[i][j]); }printf("\n");}tree(i-1,j);}void tree(int x,int y){if(x==y)printf("A%d",x);else{printf("(");tr

Comparing two locations for accuracy in Android

If you are developing a android application which uses android Location Service and you need to find best estimated location by comparing two locations, where one location is the currently obtained location and other is from the location fix then this post contains answer to your question. The below mentioned code contains a method isBetterLocation which will compare two locations and will return true if current location is more accurate than location fix . You might expect that the most recent location fix is the most accurate. However, because the accuracy of a location fix varies, the most recent fix is not always the best. isBetterLocation method follows following criteria for choosing location fixes, you vary this criteria depending on the use-cases of the application and field testing. Check if the location retrieved is significantly newer than the previous estimate. Check if the accuracy claimed by the location is better or worse than the previous estimate. Check which provider

How Web Browser Works ?

Image
      Now days one of the most important software use for surfing web called a Web browser. Web Browsers enables a user to navigate through Web pages by  fetching those pages from some servers and subsequently displaying them on the user’s screen.  A web browser typically provides an interface by which hyperlinks are displayed in such a way that the user can easily select them through a single mouse click. In old days web browser used to be simple program but now days thing are changed, browsers are considered to be one of the most complex piece of software. Logically,we browsers consist of several components, shown in Figure. An important aspect of Web browsers is that it should (ideally) be platform independent. This goal is often achieved by making use of standard graphical libraries, shown as the display back-end, along with standard networking libraries. The core of a browser is formed by the browser engine and the rendering engine. The latter contains all the code for properly di

Java Programming Question

Q.  Using loops and control statements to draw lines can lead to many interesting designs. Create the design in the left screen capture of Figure. This design draws lines from the top-left corner, fanning out the lines until they cover the upper-left half of the panel. One approach is to divide the width and height into an equal number of steps (we found 15 steps worked well). The first endpoint of a line will always be in the top-left corner (0, 0). The second endpoint can be found by starting at the bottom-left corner and moving up one vertical step and right one horizontal step. Draw a line between the two endpoints. Continue moving up and to the right one step to find each successive end-point. The figure should scale accordingly as you resize the window. Java Code: import javax.swing.JPanel; import javax.swing.JFrame; import java.awt.Graphics; public class q2ans extends JPanel { public static void main(String args[]) { q2ans panel = new q2ans(); //creates a panel JFrame frameapp =

Doubly linked list operations in C language.

/* Doubly linked list operationsInsertion , Deletion, Searching*/#include<stdio.h>#include<conio.h>#include<malloc.h>void insert();void deleted();void search();void display();int i=0;struct node *head,*temp,*m,*loc;int count;struct node{int data;struct node *prev;struct node *next;};int main(){    int op;    do{printf("n <<Doubly Linked List Operations>>");printf("n1.Insert Element");printf("n2.Delete Element");printf("n3.Search Element");printf("n4.Display");printf("n5.Exit");    scanf("%d",&op);    switch(op)    {    case 1:         insert();         break;    case 2:         deleted();         break;    case 3:         search();         break;    case 4:         display();         break;    case 5:         break;    default: printf("nPlease Enter Valid Choice..");    }     }while(op!=5);getch();}void insert(){printf("nEnter Elements To Be Inserted");temp =(stru

Google Login Tutorial - Part 5

In previous part of Google Login Tutorial we have discussed step 4 Authenticating User . Now in this part we are going to discuss step 5 and step 6. Note that this is the last part of tutorial. Step 5 : Obtaining user information from ID Token: An ID Token is a JWT (JSON Web Token), that is, a cryptographically signed Base64-encoded JSON object. Normally, it is critical that you validate an ID token before you use it, but since we are communicating directly with Google over an intermediary-free HTTPS channel and using your client secret to authenticate yourself to Google, we can be confident that the token you receive really comes from Google and is valid. If our server passes the ID token to other components of your app, it is extremely important that the other components validate the token before using it. An ID token’s payload : An ID token is a JSON object containing a set of name/value pairs. Here’s an example, formatted for readability: {"iss":"accounts.google.co

Google Login Tutorial - Part 4

In part 3 of Google Login Tutorials we have discussed step three in implementing Google login process. Now in this part we will be discussing step four of implementing Google login process with OAuth 2.0 Step 4: Authenticating User This is the main and most important step in our overall discussion. Authenticating the user involves obtaining a onetime authorization code from Google Servers and then an ID token and validating it.

Google Login Tutorial - Part 3

In part 2 of Google Login Tutorial we had discussed first two steps, now we will be moving forward and discussing Third Step. Step 3: Setting up Consent Screen: Consent screen is nothing but a view which user will see once he entered correct username and password. If user is already logged on Google then he will be directly redirected to this screen. Consent Screen contains information that the user is releasing and the terms that apply.

Google Login Tutorial - Part 2

In previous part of Google Login Tutorials we had just discussed to general idea about how Google Login with OpenID Connect (OAuth 2.0) works. As we mentioned earlier we gone see the whole process step by step,  so from here we begin. There are six main steps involved in implementing this whole Google Login process. 

How to add Google Login to your Website or WebApp ?

Hello readers 🙂 If you want to know how to add Google Login to your website or WebApp without using existing Google’s API, then this series of tutorial is for you. Hoping that you will find it useful. So let’s begin. There are two ways of adding Google Login (Authentication) to your website or web app. Using OpenID Connect (OAuth 2.0 for Login) Using Google+ Sign-In client library that is built on the OAuth 2.0 and OpenID Connect protocols.

Python code to find maximum recursion limit on a machine

Image
Python script given here is to finds the maximum safe recursion limit on a particular platform.  If you need to change the recursion limit on your system, this script will tell you a safe upper bound.  To use the new limit, call sys.setrecursionlimit(). This python script implements several ways to create infinite recursion in Python.  Different implementations end up pushing different numbers of C stack frames, depending on how many calls through Python ‘s abstract C API occur. After each round of tests, it prints a message  “Limit of NNNN is fine”. The highest printed value of “NNNN” is therefore the highest potentially safe limit for your system (which depends on the OS, architecture and the compilation flags). As it is practically impossible to test all possible recursion paths in the interpreter , so the results of this test should not be trusted blindly, although they give a good hint of which values are reasonable. import sysimport itertoolsclass RecursiveBlowup1: def __in

Difference between IPv4 and IPv6

     On the Internet, data is transmitted in the form of network packets. IPv6 specifies a new packet format, designed to minimize packet header processing by routers. Because the headers of IPv4  and IPv6 header packets are significantly different, the two protocols are not interoperable. However, in most respects, IPv6 is a conservative extension of IPv4. Most transport and application-layer protocols need little or no change to operate over IPv6 ; Address space: The main advantage of IPv6 over IPv4 is its larger address space. The length of an IPv6 address is 128 bits, compared with 32 bits in IPv4. The address space therefore has 2128 or approximately 3.4×1038 addresses. By comparison, this amounts to approximately 4.8×1028 addresses for each of the seven billion people alive in 2011. In addition, the IPv4 address space is poorly allocated, with approximately 14% of all available addresses utilized. While these numbers are large, it wasn’t the intent of the designers of the IPv6 ad

Security issues with IPv6

Deployment of a new generation of Internet protocols is on its way. It is a process that may take several years to complete. In the meantime, the deployment raises considerable new issues, being security one of the most compelling. From a security point of view, the new IPv6 protocol stack represents a considerable advance in relation to the old IPv4 stack . However, despite its innumerable virtues, IPv6 still continues to be by far vulnerable. Dual-stack related security issues with IPv6 : Presently, the Internet continues to be mostly IPv4 based. However, it is reasonable to expect that this scenario will change soon as more and more networks are migrated to the new protocol stack. Unfortunately, migrating millions of networks is going to take quite some time. In the meantime, some form of 6 to 4 dual-stack will supply the desired functionality. Without a doubt, IPv6-IPv4 dual stacks increase the potential for security vulnerabilities—as a consequence of having two infrastructure

Python script to print files statistics

Image
import osimport sysclass Stats: def __init__(self): self.stats = {} def statargs(self, args): for arg in args: if os.path.isdir(arg): self.statdir(arg) elif os.path.isfile(arg): self.statfile(arg) else: sys.stderr.write("Can't find %s\n" % arg) self.addstats("<???>", "unknown", 1) def statdir(self, dir): self.addstats("<dir>", "dirs", 1) try: names = os.listdir(dir) except os.error, err: sys.stderr.write("Can't list %s: %s\n" % (dir, err)) self.addstats("<dir>", "unlistable", 1) return names.sort() for name in names: if name.startswith(".#"): continue # Skip CVS temp files if name.endswith("~"): continue# Skip Emacs bac