Monthly Archives: June 2013

Web

For loop through an associative array

assocarr
To go through an associative array or object, you could use:

<script type='text/javascript'>
/* <![CDATA[ */
var data = {};
data['var1'] = 'value1';
data['var2'] = 'value2';
data['var3'] = 'value3';
console.log(data);

for (var prop in data) {
  if (Object.prototype.hasOwnProperty.call(data, prop)) { 
    console.log("prop: " + prop + " value: " + data[prop])
  }
}
/* ]]> */
</script>

Using JDBC

jdbc
Next snippet shows using JDBC:

import java.sql.*;

public class DBConnect {

	public static void main(String[] args) {
		Connection conn = null;
		Statement stmtSelect = null;
		PreparedStatement stmtInsert = null;
		PreparedStatement stmtUpdate = null;
		PreparedStatement stmtDelete = null;
		Statement stmtBatchInsert = null;
		Statement stmtBatchUpdate = null;
		ResultSet rs = null;

		try {
			Class.forName("com.pointbase.jdbc.jdbcUniversalDriver");
			String connectionString = "jdbc:pointbase:server://localhost:9092/nameOfDB";
			conn = DriverManager.getConnection(connectionString, "PBPUBLIC",
					"PBPUBLIC");

			// add
			stmtInsert = conn
					.prepareStatement("insert into users "
							+ "(NAME, ADDRESS, USERNAME, PASSWORD, ACCESSLEVEL)"
							+ " values (?, ?, ?, ?, ?)");
			stmtInsert.setString(1, "Superman");
			stmtInsert.setString(2, "Earth");
			stmtInsert.setString(3, "spet");
			stmtInsert.setString(4, "123456");
			stmtInsert.setString(5, "0");
			int resInsert = stmtInsert.executeUpdate();
			System.out.println("resInsert: " + resInsert);
			
			// upd
			stmtUpdate =conn.prepareStatement("update users set ADDRESS = ? where name='Superman'", Statement.RETURN_GENERATED_KEYS);
			stmtUpdate.setString(1, "Mars");
			int resUpdate = stmtUpdate.executeUpdate();
			System.out.println("resUpdate: " + resUpdate);

			// del
			conn.setAutoCommit(false);
			stmtDelete = conn
					.prepareStatement("delete from users where name=?");
			stmtDelete.setString(1, "Superman");
			int resDelete = stmtDelete.executeUpdate();
			System.out.println("resDelete: " + resDelete);
			
			// batch insert
			stmtBatchInsert = conn.createStatement();
			stmtBatchInsert.addBatch("insert into users values ('User1', 'Earth', 'p1', '123456', 0)");
			stmtBatchInsert.addBatch("insert into users values ('User2', 'Earth', 'p2', '123456', 0)");
			stmtBatchInsert.addBatch("insert into users values ('User3', 'Earth', 'p3', '123456', 0)");
			conn.setAutoCommit(false);
			int[] resBatchInsert = stmtBatchInsert.executeBatch();
			System.out.println("resBatchInsert: " + resBatchInsert);
			conn.commit();
			
			// batch update
			stmtBatchUpdate = conn.createStatement();
			stmtBatchUpdate.addBatch("update users set ADDRESS = 'no 111' where userid = 129");
			stmtBatchUpdate.addBatch("update users set ADDRESS = 'no 222' where userid = 130");
			stmtBatchUpdate.addBatch("update users set ADDRESS = 'no 333' where userid = 131");
			conn.setAutoCommit(false);
			int[] resBatchUpdate = stmtBatchUpdate.executeBatch();
			System.out.println("resBatchUpdate: " + resBatchUpdate);
			conn.commit();

			// get
			stmtSelect = conn.createStatement();
			stmtSelect.setFetchSize(1);
			rs = stmtSelect.executeQuery("select * from users");
			while (rs.next()) {
				String s = rs.getString("NAME");
				System.out.println(s);
			}
			
			// stored proc
			CallableStatement callableStatement = conn.prepareCall("{call CountAllOrdersSum(?, ?)}");
			callableStatement.setString(1, "In Progress"); 
			callableStatement.registerOutParameter(2, java.sql.Types.DOUBLE);
			callableStatement.execute();
		    double resCall = callableStatement.getDouble(2);
		    System.out.println("resCall: " + resCall);
		    callableStatement.close();
			

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println(e.getSQLState());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				stmtSelect.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				stmtInsert.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				stmtUpdate.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				stmtDelete.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				conn.rollback();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}

Don’t forget to add to classpass JDBC-driver for your database.
Also, see JDBC Home

Using SETLOCAL and ERRORLEVEL together in Batch

bat-file-icon
Interesting thing about using SETLOCAL and ERRORLEVEL together.
Consider two files:

first.bat

@echo off

echo %ERRORLEVEL% in first bat before setlocal

setlocal

echo Some actions with error finished here...

set ERRORLEVEL=1
echo %ERRORLEVEL% in first bat.

exit /b %ERRORLEVEL%

second.bat

@echo off

echo %ERRORLEVEL% in second bat before setlocal

setlocal

echo %ERRORLEVEL% in second bat after setlocal

Exec in series:

C:\first.bat && second.bat

You’ll see the next output:

0 in first bat before setlocal
Some actions with error finished here...
1 in first bat.
1 in second bat before setlocal
0 in second bat after setlocal

More info http://ss64.com/nt/setlocal.html

Right way to define time spent in Batch

patrick
Here is an example of how to calculate the time spent during batch script execution:

REM Start timer
call z_timer_start.bat

REM Action
...

REM Stop timer
call z_timer_finish.bat

And here are the scripts.

z_timer_start.bat

@echo off

REM Settings
set start_time=%time%

REM Get start time
for /f %%i in ('z_strtoint %start_time:~0,2%') do set /a hours_before=%%i
for /f %%i in ('z_strtoint %start_time:~3,2%') do set /a minutes_before=%%i
for /f %%i in ('z_strtoint %start_time:~6,2%') do set /a seconds_before=%%i

z_timer_finish.bat

@echo off

REM Settings
set finish_time=%time%
set debug=0

REM Get finish time
for /f %%i in ('z_strtoint %finish_time:~0,2%') do set /a hours_after=%%i
for /f %%i in ('z_strtoint %finish_time:~3,2%') do set /a minutes_after=%%i
for /f %%i in ('z_strtoint %finish_time:~6,2%') do set /a seconds_after=%%i

REM Make calc
set /a before=%hours_before% * 3600 + %minutes_before% * 60 + %seconds_before%
set /a after=%hours_after% * 3600 + %minutes_after% * 60 + %seconds_after%
set /a timediff=%after%-%before%

REM Show result
echo.
echo Total time spent: %timediff% seconds

REM Show debug
if "%debug%" == "1" (
	echo.
	echo Timer debug-info:
	
	echo.
	echo start_time:  %start_time%
	echo finish_time: %finish_time%
	
	echo.
	echo hours_before:   %hours_before%
	echo minutes_before: %minutes_before%
	echo seconds_before: %seconds_before%
	
	echo.
	echo hours_after:  %hours_after%
	echo minutes_after: %minutes_after%
	echo seconds_after: %seconds_after%
	
	echo.
	echo before: %before%
	echo after:  %after%
	echo timediff: %timediff%
)

And use z_strtoint from here remove-leading-zeros-from-string-in-batch/

You can download all files here: batch_timer

Set file and folder permissions in Linux

read-write-permission-attributes-linux
Convenient way to apply permissions in Linux is to save alias in .bashrc file:

Set all permissions for FTP:

alias setftpperm="chown -R _pure-ftpd:_pure-ftpd /usr/serv/ftp/anonymous && \
    chmod -R u+rwX,go+rX,go-w /usr/serv/ftp/anonymous && \
    chmod -R u+rwX,go+rX,go+w /usr/serv/ftp/anonymous/PUBLIC && \
    chmod -R u+rwX,go+rX,go+w /usr/serv/ftp/anonymous/TORRENTS"

Next is permissions for Apache:

alias setapacheperm="chown -R _pure-ftpd:daemon . && \
  chmod 666 . && chmod -R u+rwX,go+rX,go-w ."

alias setapachewperm="chown -R _pure-ftpd:daemon . && \
  chmod 666 . && chmod -R u+rwX,go+rX,go+w ."

Remove leading zeros from string in Batch

sacsC
It is often need to convert string to int in batch. But:

set /a int=0100
echo Int: %int%

Will result

Int: 64

It ‘s because lead zero – seen as a HEX (0xNUMBER)

To solve use next:

@echo off
setlocal enableextensions enabledelayedexpansion

REM Removes leading "0" from string

REM Settings
set z_strtoint=%1

REM Init
set strterm=___ENDOFSTRING___
set tmp=%z_strtoint%%strterm%

REM Action
:loop
set char=%tmp:~0,1%
set tmp=%tmp:~1%
REM echo char: %char%
if [!char!] EQU [0] set z_strtoint=!z_strtoint:~1!
if [!char!] NEQ [0] goto endloop
if [!tmp!] NEQ [!strterm!] goto loop
:endloop

REM Show result
echo %z_strtoint%

So, exec:

z_strtoint 0100
100

Save result of program to variable in Batch

Construct_Sequential

set cmd=application
set arg1=0101
for /f %%i in ('%cmd% %arg1%') do set result=%%i
echo =%result%

Thanx to http://stackoverflow.com/a/2340018