Skip to main content

Posts

Showing posts with the label source code

Determining image file size in Javascript

After a lot of googling and searching, I realized the best way to do this is to create a service call to the backend witht he url of the image whose size needs to be figured out. This service should make a HEAD call to the server to get the content - length. And pass it along as a response. Not all servers support HEAD calls so as a fallback make a GET call to the get the request and determine the file size from the headers. We need to set few headers for this to work universally. One of them is user-agent. Code for the same is : private void makeRequest( @FormParam ( "url" ) String url, Map response, String requestMethod) { try { HttpURLConnection urlCon = (HttpURLConnection) new URL(url).openConnection(); urlCon.setRequestMethod(requestMethod); urlCon.setRequestProperty( "User-Agent" , "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" ); //urlCon.setDoOutput...

Linkedin Status Update Image not displayed

I was facing this problem when I was updating images from my site on linkedin. I even asked a question on stackoverflow ( When using linkedin share api submitted-picture-url or sharing url via linkedin, particular url format doesnot work? ) but never got a good response. After that I did lots of experimentation to figure out few things about linkedin in status update image url. I would list them out below: Max size for image should be 100 MB (read somewhere, have not tried it myself.) Linkedin caches the images on its server for 7 days. So if the image on the url shared have changed, linkedin won't update it. A good workaround is to add a query parameter to the image url with some random string of the timestamp while sharing. So, this would make each image url unique. Set the correct mime-type on the servlet serving the image. I was using cdn and with my servlet acting at a proxy to cdn to serve the image. In the process I was missing out the mime-type in the response head...

Making Twitter Media Upload Api work with Java

I was trying to upload an image and do status update on twitter using there api version 1.1. For this I was using media/upload.json  . I was trying to send content of files as base64 encoded string and setting the appropriate content-type and content-transfer-encoding. But this didn't work. I was getting errors like: 1) Missing paramter media 2) Could not authenticate. My main reason to use this approach was I was getting image url and didn't wanted to save it into a file. But this never worked, then I took a different approach of saving the imageurl into a file and doing a multi part upload. Code for it is below. Hope this helps someone. private String uploadImage(String imageUrl) { File f = new File("/tmp/twitterUploadImage_"+StringUtil.encodeURL(imageUrl)); try { FileUtils.copyURLToFile(new URL(imageUrl), f); } catch (IOException e) { logger.severe("Failed to save image in a file"); return null; } U...

Git CheatSheet/Quickguide

Git Rebase Command git checkout branch name # checkout branch on which you want to merge git rebase branch_name # Original branch would be rebased to current branch. Rebase would remove changes in your branch and merge all the changes from the new branch then applyour changes on top of it. Git merge from a branch. git checkout branch name # checkout branch on which you want to merge git merge branch_name # branch_name is the branch from which you want to merge Reverting merge conflict files git reset --hard HEAD file_name # hard revert to HEAD Reverting to the last commited changes on a branch: git reset --hard HEAD # hard revert to HEAD Switching branches without committing changes: git add uncommited_files # Add uncommitted files to index git stash # Stash your changes git checkout new_branch # Switch to new branch, # Work on the new branch git stash pop # Switc...

Zopper Programming Assessment Problem 2 with solution

This is the second problem from HackerEarth that I tried for the friend for interview: Problem: HackerMan says that 5 and 8 are smart digits. A positive integer is called a smart number if it has only smart digits in its decimal representation. HackerMan has three sets of numbers. And he needs your help to find out the number of distinct smart numbers that he can make using one number from each of the three sets. You have to help in it Note:  You must not count the same smart number more than once. Constraints The three sets will contain between 1 and 50 elements, inclusive. Each number in the three sets will contain numbers between 1 and 30,000, inclusive. Input Format The first, third and fifth lines will contain a number N that will specify the count of numbers in the sets on the second, fourth and sixth lines of input. The second, fourth and sixth line will contain the three sets of numbers respectively. Output Format Print a single line containing the ...

Zopper online assesment question on HackerEarth with solution.

Recently a friend asked me to solve a problem which he got on one of the interview, online assessment test. I decided to document my solution here. The companies name was Zopper and the question was asked on the initial online screening test on HackerEarth. Problem: HackerMan says that 5 and 8 are smart digits. A positive integer is called a smart number if it has only smart digits in its decimal representation. HackerMan has three sets of numbers. And he needs your help to find out the number of distinct smart numbers that he can make using one number from each of the three sets. You have to help in it Note:  You must not count the same smart number more than once. Constraints The three sets will contain between 1 and 50 elements, inclusive. Each number in the three sets will contain numbers between 1 and 30,000, inclusive. Input Format The first, third and fifth lines will contain a number N that will specify the count of numbers in the sets on the second, fou...

Understanding Code Execution in Javascript

If you are doing any form of programming in Javascript then understanding its eventloop is very important. Any javascript engine has three kinds of memory models: Stack, which has the current function pointer an gets executed sequentially. Heap, this stores all the objects, functions basically anything that is initiated is stored here. Queue, all things to be executed is stored here and stack picks up tasks to do from the queue. So, to understand this further, when a function is getting executed its loaded in the stack and if it encounters any setTimeouts then it would be added in the queue and when the current stack gets empty then the new function to be executed from the queue. This code run will explain the process: console.log("Add this code to queue"); setTimeout(function() {                                                //This goes and si...

Flatten a Binary Search Tree into a LinkedList in Java

package com.biplav.algorithms; public class FlattenBST { public static class TreeNode { public TreeNode left; public TreeNode right; public int value; public TreeNode(TreeNode left, TreeNode right, int value) { super(); this.left = left; this.right = right; this.value = value; } } public static class ListNode { public ListNode next; public int value; public ListNode(ListNode next, int value) { super(); this.next = next; this.value = value; } } public static ListNode flatten(TreeNode root) { ListNode left = root.left != null ? flatten(root.left) : null; ListNode base = new ListNode(null,root.value); ListNode right = root.right != null ? flatten(root.right) : null; base.next = right != null ? right : null; if(left == null) return base; else { ListNode home = left; while(left.next != null) left = left.next; left.next= base; return home; } } /* * 6 * 3 8 * 2 4 7 10 */ ...

Alogrithm to sort a huge list of numbers in O(n) complexity in Java

A large file of numbers can be sorted in O(n) complexity by using a large bit array of the size same as the largest number in the list of numbers to be sorted. It can be done in Java using BitSet. package com.biplav.algorithms; import java.util.Arrays; import com.biplav.ds.BitArray; public class SortMillionNumbersWithGivenMax { //n+m public static int[] sort(int[] list, int max) { int[] sortedList = new int[list.length]; //BitSet bitSet = new BitSet(max); BitArray bitSet = new BitArray(max); for(int n:list) bitSet.set(n); //n int index=0; for(int i =0 ; i<=  max; i++) { //m if(bitSet.get(i)) { sortedList[index++] = i; } } return sortedList; } public static void main(String[] args) { int[] list = new int[]{1,2,3,4,5,9,15,18,25,7,11}; System.out.println(Arrays.toString(sort(list, 27))); } } I have used BitArray defined by me. Its implementation is: package com.biplav.ds; public class BitArray { privat...

Fibonacci Series With Matrix Multiplication in Java with recursion.

Attempting to solve the fibonacci series using matrix multiplication applying divide and conquer to reduce the complexity to O(logN) package com.biplav.algorithms; public class FibonacciSeries { //2*2 matrix static int [][] multiply( int [][] X , int [][] Y ) { int [][] response = new int [2][2]; response [0][0] = X [0][0]* Y [0][0] + X [0][1]* Y [1][0]; response [0][1] = X [0][0]* Y [0][1] + X [0][1]* Y [1][1]; response [1][0] = X [1][0]* Y [0][0] + X [1][1]* Y [1][0]; response [1][1] = X [1][0]* Y [0][1] + X [1][1]* Y [1][1]; return response ; } static int [][] power( int [][] X , int N ) { if ( N == 1) { return X ; } else { int [][] X2 = power( X , N /2); return multiply( X2 , X2 ); } } public static int get( int n ) { int [][] X = new int [][] {{1,1},{1,0}}; return power( X , n )[0][0]; } public static void main(String[] args ) { System. out .println(get(4)); } }

Java Merge Sort Source Code

I was not able to find a good implementation of merge sort in java as most of the implementations online didn't use comparable and have flags for sorting direction, so I decided to write one of my own. import java.util.Arrays; public class MergeSort { public static void main(String[] args) { Integer[] a = new Integer[] {3,2,1,4,2,7,1,3,4,5,6,8,9,6,7,8}; sort(a, false ); System. out .println(Arrays.toString(a)); sort(a, true ); System. out .println(Arrays.toString(a)); } public static void sort( Comparable [] list, boolean asc) { Comparable[] aux = new Comparable[list. length ]; mergeSort(list, aux, 0, list. length -1,asc); } private static void mergeSort( Comparable [] list, Comparable [] aux, int start, int end, boolean asc) { if (end <= start) { return ; } int mid = (start+end)/2; mergeSort(list,aux,start,mid,asc); mergeSort(list,aux,mid+1,end,asc); merge(list,aux,star...

How to convert a Java Object List into csv.

Wrote a general method to convert a List into a CSV file. package com.biplav.utils import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; public class ObjectListToCSV { private static final Logger logger = Logger.getLogger(ObjectListToCSV.class); private static final String CSV_SEPARATOR = ","; public static String convertListToCSV(List objectList) { if(objectList.size() < 1) { logger.info("No data in the list to convert to CDR!"); return ""; } String csv = ""; T t = objectList.get(0); Field[] declaredFields = t.getClass().getDeclaredFields(); ArrayList useableFields = getUseableFields(declaredFields); csv = getCSVHeader(csv, useableFields,null); csv=csv.concat("\n"); for(T object : objectList) { csv = addObjectValue(csv, useableFields, object); csv=csv.concat("\n"); } ...

SmartGWT Calendar widget scroll to Current Time in month view

The calendar widget of smartgwt is quite powerful. But it lacks one important functionality, that is, scroll to the current time in case of month view. But this feature can easily be enabled by working on the Workday feature which smartGWT calendar widget supports. I wrote a simple function to achieve the same: private void scrollToCurrentTime() { int[] workDays = new int[1]; Date now = new Date(); workDays[0] = now.getDay(); int currentHour = now.getHours(); now.setHours(currentHour-1); String start = DateTimeFormat.getFormat( PredefinedFormat.TIME_SHORT).format(now); now.setHours(currentHour+7); String end = DateTimeFormat.getFormat( PredefinedFormat.TIME_SHORT).format(now); calendar.setWorkdays(workDays); calendar.setWorkdayStart(start); calendar.setWorkdayEnd(end); calendar.setScrollToWorkday(true); calendar.setShowWorkday(true); }

Annotation in C# for mapping JsonProperty to a variable

If for some reason you are .NET Framework 2.0 and using Newtonsoft.Json libray than this is gonna be very useful. You have a case where your Json property contains a '-' sign, than obviously you can't have a C# variable to map the same as variable naming scheme does not allow - signs. I recently faced a similar problem and spent hours googling to figure out how to do it in .net 2.0 but all the efforts were in vain. Than after a lot of hit and trial and reading source files I hit this annotation JsonProperty("my-name") and hurray it worked. Just to provide a small example usage: JSON: {"my-name" : "Biplav"} C# snippet: public class Name {    private String m_my_name;    [JsonProperty("my-name")]    public String my_name    {       get { return m_my_name;}       set  { m_my_name = value;}   }

How function overriding is different in C# from Java?

If you are moving from Java to C#, than this is one thing which you would find very funny. Suppose you wrote the following code: class a {    public void display()     {      Console.WriteLine("A");    } } class b:a {    new public void display()    {     Console.WriteLine("B");    }  } And did something like: A a = new B(); a.display(); B b = new B(); b.display(); The output would be: A B Although we expect here that as we have overriden display in B, so the display of B must be called. But this assumption is incorrect as we have reserved reference for A, so the C# compiler won't know that B can override display function. Hence we need to tell the compiler that there is a possibility that display can be overriden in derived classes and please check for it. To do so we would have to define the baseclass function which can be overriden ...

Node.js vs PHP response time metrics

I recently did a small Hello World Time Metric Test to see response time on Node.js and PHP and plotted the graph to see the performance difference between the two. PHP was hosted on a LAMP stack while node.js was downloaded via apt-get install. Instructions can be found on http://nodejs.org . The node.js script was simple hello world script: var http = require('http'); http.createServer(function (req, res) {   res.writeHead(200, {'Content-Type': 'text/plain'});   res.end('Hello World\n'); }).listen(1337, "127.0.0.1"); console.log('Server running at http://127.0.0.1:1337/'); While the PHP script used was: echo "Hello World"; ?> The tester script was: $j=0; while($j<100) { $time1=microtime(true); $i=0; while($i<10000) {     file_get_contents("http://localhost/hello.php"); $i++; } $time2=microtime(true); print($time2-$time1); print(' '); $j++; } Any gu...

Facebook connect invitaion request:how to

The code to display extended permission is as given below. Call popupFacebookInvite() function to display the extended permission dialog box. Its pretty simple, So try out today... function popupRequestForm(){ FB.IFrameUtil.CanvasUtilServer.run(true); var _e1=document.createElement("div"); _e1.setAttribute("iframeHeight","560px"); _e1.setAttribute("iframeWidth","630px"); var _e2=new FB.UI.PopupDialog("Your message here",_e1,false,false); _e2.setContentWidth(630); _e2.setContentHeight(560); _e2.set_placement(FB.UI.PopupPlacement.center); _e1.setAttribute("fbml"," "+" \">"+" "+" "+" "); _e2.show(); FB_RequireFeatures(["XFBML"],function(){ var _e3=new FB.XFBML.ServerFbml(_e1); FB.XFBML.Host.addElement(_e3); }); } function popupFacebookInvite(){ FB.Facebook.get_sessionState().waitUntilReady(Delegate.create(null,function(_e4){ FB.Facebook.apiClient.connec...

C++ code for snake game..

here i post the code for generating the snake game.. i have created a header file which can also be downloaded.. the snake game code is available here..download by clicking below.. Snake.h and the header file symbol.h is.. it can be downloaded from... Symbol.h try executing the above program n tell me how u liked it..