Wednesday, May 6, 2015

Heap size java commands

To find java heap size

java -XX:+PrintFlagsFinal -version 2>&1 | grep MaxHeapSize
java -XX:+PrintFlagsFinal -version | grep -iE 'HeapSize|PermSize|ThreadStackSize'
    uintx AdaptivePermSizeWeight                    = 20              {product}           
     intx CompilerThreadStackSize                   = 0               {pd product}        
    uintx ErgoHeapSizeLimit                         = 0               {product}           
    uintx HeapSizePerGCThread                       = 87241520        {product}           
    uintx InitialHeapSize                          := 64749440        {product}           
    uintx LargePageHeapSizeThreshold                = 134217728       {product}           
    uintx MaxHeapSize                              := 1035993088      {product}           
    uintx MaxPermSize                               = 174063616       {pd product}        
    uintx PermSize                                  = 21757952        {pd product}        
     intx ThreadStackSize                           = 1024            {pd product}        
     intx VMThreadStackSize                         = 1024            {pd product}        
Bytes t0 MB
87241520/(1024*1024)

Thursday, April 30, 2015

Working with #Sqlite database in #Android

Log in into android Shell

adb root
adb remount
adb shell

Not in shell, cd to the folder where sql db is located at.

cd /data/user/0//databases/

Make sure you have the needed db

ls
example.db


Activate the sqlite commands

sqlite3 and ENTER


to see version of database
.headers on

PRAGMA user_version;

You will see sqlite tab now. Type following command to open the needed database.

sqlite> .open example.db

see the tables in the database

sqlite> .tables

table1  table2 table3

To see schema of table1

sqlite>.schema table1


CREATE TABLE table1 (_id INTEGER PRIMARY KEY, name TEXT NOT NULL, license TEXT NOT NULL);

to see contents of table
sqlite> select * from table1;


To see what all supported commands are there -
sqlite> .help
.backup ?DB? FILE      Backup DB (default "main") to FILE
.bail on|off                     Stop after hitting an error.  Default OFF
.clone NEWDB             Clone data into NEWDB from the existing database
.databases                      List names and files of attached databases
.dump ?TABLE? ...      Dump the database in an SQL text format
                         If TABLE specified, only dump tables matching
                         LIKE pattern TABLE.
.echo on|off                 Turn command echo on or off
.eqp on|off                   Enable or disable automatic EXPLAIN QUERY PLAN
.exit                             Exit this program
.explain ?on|off?         Turn output mode suitable for EXPLAIN on or off.
                         With no args, it turns EXPLAIN on.
.fullschema                 Show schema and the content of sqlite_stat tables
.headers on|off           Turn display of headers on or off
.help                            Show this message
.import FILE TABLE     Import data from FILE into TABLE
.indices ?TABLE?       Show names of all indices
                         If TABLE specified, only show indices for tables
                         matching LIKE pattern TABLE.
.log FILE|off          Turn logging on or off.  FILE can be stderr/stdout
.mode MODE ?TABLE?     Set output mode where MODE is one of:
                         csv      Comma-separated values
                         column   Left-aligned columns.  (See .width)
                         html     HTML code
                         insert   SQL insert statements for TABLE
                         line     One value per line
                         list     Values delimited by .separator string
                         tabs     Tab-separated values
                         tcl      TCL list elements
.nullvalue STRING      Use STRING in place of NULL values
.once FILENAME         Output for the next SQL command only to FILENAME
.open ?FILENAME?       Close existing database and reopen FILENAME
.output ?FILENAME?     Send output to FILENAME or stdout
.print STRING...       Print literal STRING
.prompt MAIN CONTINUE  Replace the standard prompts
.quit                  Exit this program
.read FILENAME         Execute SQL in FILENAME
.restore ?DB? FILE     Restore content of DB (default "main") from FILE
.save FILE             Write in-memory database into FILE
.schema ?TABLE?        Show the CREATE statements
                         If TABLE specified, only show tables matching
                         LIKE pattern TABLE.
.separator STRING ?NL? Change separator used by output mode and .import
                         NL is the end-of-line mark for CSV
.shell CMD ARGS...     Run CMD ARGS... in a system shell
.show                  Show the current values for various settings
.stats on|off          Turn stats on or off
.system CMD ARGS...    Run CMD ARGS... in a system shell
.tables ?TABLE?        List names of tables
                         If TABLE specified, only list tables matching
                         LIKE pattern TABLE.
.timeout MS            Try opening locked tables for MS milliseconds
.timer on|off          Turn SQL timer on or off
.trace FILE|off        Output each SQL statement as it is run
.vfsname ?AUX?         Print the name of the VFS stack
.width NUM1 NUM2 ...   Set column widths for "column" mode

                         Negative values right-justify




Monday, April 27, 2015

MY SQL commands

My SQL commands to keep safe update off
SET SQL_SAFE_UPDATES = 0;

Wednesday, April 22, 2015

Unix commands - maven and file listing

Maven command to run java program

mvn exec:java -Dexec.mainClass="com.lochbridge.hadoop.NewCollectDriver" -Dexec.args="Sample.txt trips"  -Dlog4j.configuration=log4j.properties


Unix command to find non-zero files created today

find -maxdepth 1 -size +0 -mtime -1


List files details 

ls -al 
ls -al file1 file2 file3


Merge multiple files
cat file1 file2 file3 >ResultFile

Setting Maven on Amazon Ubuntu Linux


Download the compressed maven binary. 

$ sudo wget ftp://apache.mirrors.pair.com/maven/maven-3/3.3.1/binaries/apache-maven-3.3.1-bin.tar.gz

If the link is old, get the latest link from maven site. Copy the link address, by selecting a proper mirror site.
Once you have proper link, the above command will download the compressed file.

$ ls
apache-maven-3.3.1-bin.tar.gz

$ sudo tar -xzvf apache-maven*

$sudo mv apache-maven-3.3.1 /usr/local/maven

$vi ~/.bashrc

type Esc , then i

Go to last line
add 
export M2_HOME=/usr/local/maven
export MAVEN_HOME=/usr/local/maven
export M2=/usr/local/maven/bin
export PATH=${PATH}:$M2

then type following commands :

Esc
:wq!

This will exit the vi editor

$source ~/.bashrc  
$mvn -version

You are all set. You will see following logs
Apache Maven 3.3.1
Maven home: /usr/local/maven

Friday, January 9, 2015

Fiiles/Folder related to Android Studio

These folders may be helpful in debugging related to issues related to Android Studio.

~/Library/Application Support/AndroidStudio
~/Library/Caches/AndroidStudio
~/Library/Logs/AndroidStudio
~/Library/Preferences/AndroidStudio

Sunday, November 23, 2014

Starting Android Game with libgdx

I started with libgdx as a game engine to see how easy it to write code with. My initial impression is very good. The libgdx website gives you a jar to download. When you run the following command on the downloaded jar:


java -jar gdx-setup.jar --dir testGame --package --mainClass MyGame --sdkLocation

a UI is presented. I was able to select Android Studio as a my IDE, and was able to generate the project. It generates two modules - android and core. The android module has your application launcher. The core is where your game logic resides. 


Once created, it comes with a default sample code. This displays a spooky bad logic icon on a red background. I was able to run the android module on emulator to see the result. 

The following code was auto-generated by the jar. Once, you have this code base, you can use it to further extend your game logic.



import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class MyGdxGame extends ApplicationAdapter {
 SpriteBatch batch;
 Texture img;
 
 @Override
 public void create () {
  batch = new SpriteBatch();
  img = new Texture("badlogic.jpg");
 }

 @Override
 public void render () {
  Gdx.gl.glClearColor(1, 0, 0, 1);
  Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
  batch.begin();
  batch.draw(img, 0, 0);
  batch.end();
 }
}

updating android studio to 0.8.4 on Mac

While updating Android Studio 0.8.4 on Mac, you might get an error message to remove the sdk out of application.

To resolve the issue, have android sdk copied to some place else and delete the sdk inside the android studio.

cd /Android\ Studio.app 
ls
rm -rf sdk

When launching android studio after update, just point the android studio to location where you have copied the sdk.

Friday, November 7, 2014

Generic return type

Java function that accept a type param  and return a value of this type so  don't have to cast the return type

For Known String type in  and out:

public String stringReturnFunc(String out)
{                                                                
         return out;                                        
}                                                               

The compiler doesn't know anything about the type

public <T> T genricMT(T type)
{
  return type;
}
 If return type is of certain class-CertainClass
public <T extends CertainClass> T genricMT(T type){
  // now you can use YourType methods
  return type;
}

Generic Types in Java

generic type is a generic class or interface that is parameterized over types.


generic class is defined with the following format:
class name { /* ... */ }


The most commonly used type parameter names are:
  • E - Element (used extensively by the Java Collections Framework)
  • K - Key
  • N - Number
  • T - Type
  • V - Value
  • S,U,V etc. - 2nd, 3rd, 4th types

The Diamond:
Replace the type arguments required to invoke the constructor of a generic class with an empty set of type arguments (<>) as long as the compiler can determine, or infer, the type arguments from the context. This pair of angle brackets, <>, is informally called the diamond. For example, you can create an instance of Box with the following statement:
Box integerBox = new Box<>();

Multiple Types Parameter:

public interface Pair {
    public K getKey();
    public V getValue();
}

public class OrderedPair implements Pair {

    private K key;
    private V value;

    public OrderedPair(K key, V value) {
 this.key = key;
 this.value = value;
    }

    public K getKey() { return key; }
    public V getValue() { return value; }
}
The following statements create two instantiations of the OrderedPair class:
Pair p1 = new OrderedPair("Even", 8);
Pair  p2 = new OrderedPair("hello", "world");
The code, new OrderedPair, instantiates K as a String and V as an Integer. Therefore, the parameter types of OrderedPair's constructor are String and Integer, respectively. Due to autoboxing, it is valid to pass a String and an int to the class.
As mentioned in The Diamond, because a Java compiler can infer the K and V types from the declaration OrderedPair, these statements can be shortened using diamond notation:
OrderedPair p1 = new OrderedPair<>("Even", 8);
OrderedPair  p2 = new OrderedPair<>("hello", "world");

Parameterized Types

You can also substitute a type parameter (i.e., K or V) with a parameterized type (i.e., List). For example, using the OrderedPair example:
OrderedPairBox






More details at:
http://docs.oracle.com/javase/tutorial/java/generics/types.html




Tuesday, November 4, 2014

Delete the git branch

Git: Delete a branch (local or remote)

To delete a local branch

git branch -d the_local_branch
To remove a remote branch (if you know what you are doing!)

git push origin :the_remote_branch

Monday, October 20, 2014

Solve Android Studio crash for Yosemite Mac update

The Android Studio will start crashing once you update Mac to Yosemite.

The fix is to point android studio to 1.7* from 1.6*.

Here is what you need to do -

cd to Content to AndroiD studio -

cd /Applications/Android\ Studio.app/Contents

open Info.plist using a text editor like Sublime. (If you have Sublime in Path, you can open Info.plist
by command - Sublime Info.plist )

Update  

JVMVersion
1.6*

to 

JVMVersion
1.7*

Close the editor. Now launch the Android Studio.

Tuesday, September 23, 2014

# KitKat NDK APP_PLATFORM Values : android/asset_manager.h: No such file or directory -

You might get an error android/asset_manager.h: No such file or directory
while making an NDK project.

The APP_PLATFORM has to be updated to android-14, which may fix the problem.


android-3      -> Official Android 1.5 system images
android-4      -> Official Android 1.6 system images
android-5      -> Official Android 2.0 system images
android-6      -> Official Android 2.0.1 system images
android-7      -> Official Android 2.1 system images
android-8      -> Official Android 2.2 system images
android-9      -> Official Android 2.3 system images
android-14     -> Official Android 4.0 system images
Also, make sure that both Application.mk and Android.mk is present in jni folder. 
Supported headers are at $NDK/platforms/android-/arch-arm/usr/include

OPENGL NDK build problem using Android Studio on Mac OS

While building NDK application that consumes OPENGL, may not compile properly.
First make sure you have
ndk.dir= in local.settings
Also, the ndk folder has to be in PATH.
echo $PATH will show whats there in path and what is not.


You may get error like -
error: undefined reference to 'glGetUniformLocation'
error: undefined reference to 'glGetAttribLocation'
error: undefined reference to 'glUseProgram'
error: undefined reference to 'glBindTexture'
error: undefined reference to 'glUniform2f'
error: undefined reference to 'glVertexAttribPointer'
.......

I also saw that the Headers files for OPENGL framework in Mac OS was missing. You can update that using:
xcode-select --install

However, the error will not go.

The solution is:
Deactivate the ndk compilation from gradle by setting in build.gradle of your module. ( the inner one).
Place it inside under android tag:, below the build tool version

sourceSets.main {   
jni.srcDirs = []
    jniLibs.srcDir 'src/main/libs'
}
to be able to call ndk-build yourself and integrate libs from libs/.
Do a ndk-build at app/src/main, where jni folder resides.
The compiled jni code will be in 'src/main/libs'

Then install the app by gradle iD 

Tuesday, August 26, 2014

Code snippet for Setting Alarm using fragements

           //Main Activity

            public static final String FRAGTAG = "RepeatingAlarmFragment";

            if (getSupportFragmentManager().findFragmentByTag(FRAGTAG) == null ) {
                        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                        RepeatingAlarmFragment fragment = new RepeatingAlarmFragment();
                        transaction.add(fragment, FRAGTAG);
                        transaction.commit();
            }



            //RepeatingAlarmFragment - setting intent and alarm

            Intent intent = new Intent(getActivity(), MainActivity.class);
            intent.setAction(Intent.ACTION_MAIN);
            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
  
            PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(), REQUEST_CODE,
                    intent, 0);

            int alarmType = AlarmManager.ELAPSED_REALTIME;
            final int FIFTEEN_SEC_MILLIS = 15000;

            AlarmManager alarmManager = (AlarmManager)
                    getActivity().getSystemService(getActivity().ALARM_SERVICE);

            alarmManager.setRepeating(alarmType, SystemClock.elapsedRealtime() + FIFTEEN_SEC_MILLIS,
                    FIFTEEN_SEC_MILLIS, pendingIntent);

Monday, August 4, 2014

Python code to search array of strings in particular folder

import os

#list of strings you want to find
apis = ["sandeepshabd@gmail.com",
"sandeep.shabd"
]

def find(word):
    def _find(path):
        with open(path, "rb") as fp:
            for n, line in enumerate(fp):
                if word in line:
                   yield word, n+1, line
    return _find

def search(word, start):
    finder = find(word)
    for root, dirs, files in os.walk(start):
        for f in files:
            path = os.path.join(root, f)
            for word, line_number, line  in finder(path):
                yield word, path, line_number, line.strip()

if __name__ == "__main__":
    import sys
 
    result =set()
    #Path of the document folder
    start= "/Users/sandeepshabd/Documents/"
    for api in apis:
        for word, path, line_number, line in search(api, start):
           result.add(word)
 
    print "**************************"
    for filterApi in list(result):
        print filterApi
    print "**************************"


Monday, April 28, 2014

#Android #chromium code base language distribution

Tried to find what all consist of android chrome code base. The one I downloaded has these details




Friday, May 3, 2013

First step with Mongo DB - A quick start


Download Mongo DB-

MongoDB on Windows

Local Database folder (default)-
C:\data\db

Start Mongo DB server
C:\mongodb\bin\mongod.exe –dbpath “C:\data\db








Mongo client on separate cmd window -
C:\mongodb\bin\mongo.exe


The value, if string, has to be in double quotes.

db.test.save()  - saves the value
db.test.find() – gives the value.

Mongo as Service on Windows Environment-
From  CMD prompt

md C:\mongodb\log
echo logpath=C:\mongodb\log\mongo.log > C:\mongodb\mongod.cfg
 
Install
C:\mongodb\bin\mongod.exe --config C:\mongodb\mongod.cfg –install
 
 
Run MongoDB as service –
net start MongoDB
 
To Stop-
net stop MongoDB
 
Remove-
C:\mongodb\bin\mongod.exe --remove


Saturday, November 10, 2012

Java code to list files and download files using jsp and servlet


Here is code that will read a file from a directory. Once clicked, the files will be downloaded.

The files are stored in a directory - D:/filesFolder/
Modify the path, as per your file path in  DownloadFile and in .jsp
--------------------------------------------------------------------------------------

The servlet java file is DownloadFile.java
--------------------------------------------------------------------------------------


package com.sandeepshabd.example;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class DownloadFile
 */
public class DownloadFile extends HttpServlet implements
javax.servlet.Servlet{
private static final long serialVersionUID = 1L;
private static final int BUFSIZE = 4096;
    /**
     * Default constructor.
     */
    public DownloadFile() {
        // TODO Auto-generated constructor stub
    }

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String name = request.getParameter("fileName");
if(name==null || name.length()==0)
{
//DO NOTHING
}else
{
startDownload(response,name);
}
}



void startDownload(HttpServletResponse response,String name)
{

String filePath = "D://filesFolder//"+name;
File file = new File(filePath);
        int length   = 0;
        ServletOutputStream outStream;
try {
outStream = response.getOutputStream();

       ServletContext context  = getServletConfig().getServletContext();
       String mimetype = context.getMimeType(filePath);
     
       // sets response content type
       if (mimetype == null) {
           mimetype = "application/octet-stream";
       }
       response.setContentType(mimetype);
       response.setContentLength((int)file.length());
       String fileName = (new File(filePath)).getName();
     
       // sets HTTP header
       response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
     
       byte[] byteBuffer = new byte[BUFSIZE];
       DataInputStream in;
try {
in = new DataInputStream(new FileInputStream(file));        // reads the file's bytes and writes them to the response stream
       try {
while ((in != null) && ((length = in.read(byteBuffer)) != -1))
{
   outStream.write(byteBuffer,0,length);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
     
       in.close();
       outStream.close();
     
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

}


---------------------------------- files.jsp under webcontent---------------------------------------------

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
Skunkwork Download File

Directories

    <%
    String root="D://filesFolder//";
    java.io.File file;
    java.io.File dir = new java.io.File(root);

    String[] list = dir.list();

    if (list.length > 0) {

    for (int i = 0; i < list.length; i++) {
      file = new java.io.File(root + list[i]);
      if (file!= null && !file.isDirectory() ) {
      %>
      <%
         }
      }
    }
    %>
    ----------------------------------------------------------------------------------






    Wednesday, March 23, 2011

    Firefox being downloaded faster Than the new IE






    More people are downloading Firefox 4.0 on its first day then IE 9 on its first day. Mozilla had pushed for a Guinness World Record with a "Download Day" campaign that urged users to flood its servers with requests.
    Europeans are 2 times more downloading than Americans. Asians are in thrid place.

    TCl code to find and reorder chunk of data in string or paragraph



    set dataStr "Result*****ADDENDED*****~~My name is sandeep and I am trying to test the system ~~why do not u do it in a fast manner.~~~IMPRESSION:*****ADDENDED*****~~~well i am trying it with different ways.~~~Examination:OCB - complete it as fast as possible asdasd.Result*****ADDENDED*****~~My qqqqname is sandeep and I am trying to test the system ~~why do not u do it in a fast manner.~~~IMPRESSION:*****ADDENDED*****~~~well fff i am trying it with different ways.~~~Examination:OCB - comddddplete it as fast as possible"
    set resultStr "Result*****ADDENDED*****"
    set examData "~~~Examination"
    set imprdata "~~~IMPRESSION:*****ADDENDED*****~~~"
    set strLnth [string length $dataStr]

    set resLen  23
    set startRange 0
    set EndRange  [expr $startRange + 23 ]
    set str0 ""
    set resultStartIn $startRange
    set finalList ""

    while { $EndRange < $strLnth+1 } {
        set str1 [string range $dataStr $startRange $EndRange]
        if {[string equal $str1 $resultStr]} {
            if { $startRange > 0} {
                set str0 [string range $dataStr $resultStartIn $startRange-1]
            }
            set resultStartIn $startRange
            set impFlag "Y"
            while {[string equal $impFlag "Y"] && $EndRange < $strLnth} {
                set startRange  [expr $startRange + 1 ]
                set EndRange  [expr $startRange + 34 ]
                set str2 [string range $dataStr $startRange $EndRange]
           
                if { [string equal $str2 $imprdata]} {
                    set impFlag "N"
                    set finalResultStr [string range $dataStr $resultStartIn $startRange-1]
                    set resultStartIn $startRange
                   
                    set examFlag "Y"
                    while {[string equal $examFlag "Y"] && $EndRange < $strLnth} {
                        set startRange  [expr $startRange + 1 ]
                        set EndRange  [expr $startRange + 13 ]
                        set str3 [string range $dataStr $startRange $EndRange]
                        if { [string equal $str3 $examData]} {
                            set examFlag "N"
                            set finalImpressionStr [string range $dataStr $resultStartIn $startRange-1]
                            set resultStartIn $startRange
                            set finalList [concat $finalList $str0]
                            set finalList [concat $finalList $finalImpressionStr]
                            set finalList [concat $finalList $finalResultStr]

                       
                        }
                    }
                }
               
            }

        }
       
       
        set startRange  [expr $startRange +1 ]
        set EndRange  [expr $startRange + 23 ]
    }

    set str0 [string range $dataStr $resultStartIn $strLnth-1]
    set finalList [concat $finalList $str0]
    puts $finalList