Wednesday, November 28, 2007

Combine multiple pdf into a file

install Ghostscript ...
#> gswin32 -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=output.pdf sample.pdf sample.pdf

Java CROP image Sample Code

Resource: http://www.java2s.com/Code/Java/2D-Graphics-GUI/Imagecrop.htm

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Insets;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;

import javax.swing.ImageIcon;
import javax.swing.JFrame;

public class Crop extends JFrame {

  Image image;

  Insets insets;

  public Crop() {
    super();
    ImageIcon icon = new ImageIcon("wall2.jpg");
    image = icon.getImage();
    image = createImage(new FilteredImageSource( image.getSource(),
        //new CropImageFilter(73, 63, 141, 131)));
        new CropImageFilter(50, 30, 141, 131)));
  }

  public void paint(Graphics g) {
    super.paint(g);
    if (insets == null) {
      insets = getInsets();
    }
    g.drawImage(image, insets.left, insets.top, this);
  }

  public static void main(String args[]) {
    JFrame f = new Crop();
    f.setSize(600, 400);
    f.show();
  }
}

Tuesday, November 27, 2007

Map windows directory to a drive path

C:\Documents and Settings\admin>help subst
Associates a path with a drive letter.

SUBST [drive1: [drive2:]path]
SUBST drive1: /D

  drive1:        Specifies a virtual drive to which you want to assign a path.
  [drive2:]path  Specifies a physical drive and path you want to assign to
                 a virtual drive.
  /D             Deletes a substituted (virtual) drive.

Type SUBST with no parameters to display a list of current virtual drives.

Friday, November 23, 2007

Completely disable sendmail

Quoted From::
http://lists.freebsd.org/pipermail/freebsd-questions/2005-December/107620.html

On Thu, Dec 15, 2005 at 09:30:07AM +0100, Pietro Cerutti wrote:
> Same thing with "NONE" instead of "NO", moreover `man sendmail.rc` says
>
> sendmail_enable
> (str) If set to ``YES'', run the sendmail(8) daemon at system
> boot time. If set to ``NO'', do not run a sendmail(8) daemon to
> listen for incoming network mail. This does not preclude a
> sendmail(8) daemon listening on the SMTP port of the loopback
> interface. The ``NONE'' option is deprecated and should not be
> used. It will be removed in a future release.

Hi Pietro,

Setting the 4 sendmail*_enable variables to NO as you've done will prevent
any sendmail daemons from running. However, it doesn't stop anything from
directly invoking /usr/sbin/sendmail - which is what cron does when it
wants to send some mail. When sendmail is invoked this way it will try to
deliver the mail according to its submit.cf configuration file.

You should be able to disable any email sending from cron by adding a
MAILTO=""
line to your crontab file. It might still be a good idea to fix your
sendmail configuration so you can actually send mail from this system.

Cheers,

Scott

--

Thursday, November 22, 2007

PHP, AJAX auto complete text field

Original Source:
http://wiseguysonly.com/2006/04/14/ajax-autocompletion-for-the-impatient/

Ingredients:

  1. The Scriptaculous Javascript libraries.
  2. An (X)HTML web document
  3. A textfield with and id (for this example id='search')
  4. A hidden div with an id (for this example id='auto_complete')
  5. A script to query a database written in the server-side language of your choice (for this example server.php).
  6. A database of your choice.

Step One - creating the user interface:

  • Include the lib/prototype.js and src/scriptaculous.js and src/controls.js (1) files in the head of your (X)HTML web document (2)
  • Insert your textfield (3) into the body of your (X)HTML document (2).
  • Below your textfield (3) embed some JavaScript in script tags to call a function from our included scriptaculous scripts (1):

    new Ajax.Autocompleter(”search”,”hint”,”server.php”);

  • The three arguments for our new Autocompleter wrapper are: the id of the textfield to observe; the id of the hidden div which will contain autocompletion hints; the script that will be called upon to provide the list of hints in the background.

Step two: Creating the server script.

  • Include or write whatever you need to in order to connect to your database.
  • Write your SQL to search the database for terms that are LIKE whatever is contained in the POST variable related to your textfield. In my case I gave my textfield the name 'search_item' (the same value as the id for ease).
  • Here is an example of ...SQL in php:
    • $sql = SELECT title FROM tablename WHERE title ILIKE ‘%”.$_POST[’search_item’].”%’”;
  • Output an unordered list in the server file with one list item for each result. The server file should only output this list and no other markup.

That is all you need to do. Providing you implemented that framework correctly and filled in the gaps correctly using your own server side scripting language you should be in business with an autocompletion field.


Example content of :: autocomplete.html



<div>
<label>
Type here</label>
<input type="text" id="search" name="search">
</div>
<div id="hint">
</div>
<script type="text/javascript">
new Ajax.Autocompleter("search","hint","server.php");
</script>

Example content of :: server.php

 
$sql = "SELECT title FROM autocomplete_demo
WHERE title LIKE '%" . $_POST['search'] . "%'";
$rs = mysql_query($sql);
?>
<ul>
<? while($data = mysql_fetch_assoc($rs)) { ?>
<li><? echo stripslashes($data['title']);?></li>
<? } ?>
</ul>

Thursday, November 15, 2007

solaris add user [ useradd ]

You must be root (superuser) to add a user. An easy way to remember the syntax of the useradd command in Solaris is to run it with no options. Follow the resulting usage information including the parts that you require. Important options are:

-d home-directory-path
This is the new user's home directory, typically /export/home/username

-m
make home directory and copy the default skeleton files (these files are located in /etc/skel directory).

-u uid
The uid (userid) is a number from 0 to 65535 which identifies the user on the system. uid 0 is reserved for root. If you don't specify one, the next available uid will be used automatically.

-c "User Name"
Comment field which usually contains the name of the user. Make sure you enclose the name in quotes if it contains a space.

-s /path/to/shell
The shell to use. If you don't specify this, it will default to /bin/sh. Make sure you specify the fully qualified path.

So, putting it together, a typical addition of a user named fred would be:

useradd -d /export/home/fred -m -s /bin/ksh -c "Fred Smith" fred


It's a smart idea to run pwck (passwd check) whenever you make a change to the /etc/passwd file (as when adding or chaning a user). This program will identify any problems with the passwd file. If it doesn't tell you anything, then you are in good shape.

Fingerprint biometrics

Principles of fingerprint biometrics

A fingerprint is made of a a number of ridges and valleys on the surface of the finger. Ridges are the upper skin layer segments of the finger and valleys are the lower segments. The ridges form so-called minutia points: ridge endings (where a ridge end) and ridge bifurcations (where a ridge splits in two). Many types of minutiae exist, including dots (very small ridges), islands (ridges slightly longer than dots, occupying a middle space between two temporarily divergent ridges), ponds or lakes (empty spaces between two temporarily divergent ridges), spurs (a notch protruding from a ridge), bridges (small ridges joining two longer adjacent ridges), and crossovers (two ridges which cross each other).

The uniqueness of a fingerprint can be determined by the pattern of ridges and furrows as well as the minutiae points. There are five basic fingerprint patterns: arch, tented arch, left loop, right loop and whorl. Loops make up 60% of all fingerprints, whorls account for 30%, and arches for 10%.

Fingerprints are usually considered to be unique, with no two fingers having the exact same dermal ridge characteristics.

How does fingerprint biometrics work

The main technologies used to capture the fingerprint image with sufficient detail are optical, silicon, and ultrasound.

There are two main algorithm families to recognize fingerprints:

  • Minutia matching compares specific details within the fingerprint ridges. At registration (also called enrollment), the minutia points are located, together with their relative positions to each other and their directions. At the matching stage, the fingerprint image is processed to extract its minutia points, which are then compared with the registered template.
  • Pattern matching compares the overall characteristics of the fingerprints, not only individual points. Fingerprint characteristics can include sub-areas of certain interest including ridge thickness, curvature, or density. During enrollment, small sections of the fingerprint and their relative distances are extracted from the fingerprint. Areas of interest are the area around a minutia point, areas with low curvature radius, and areas with unusual combinations of ridges.

Issues with fingerprint systems

The tip of the finger is a small area from which to take measurements, and ridge patterns can be affected by cuts, dirt, or even wear and tear. Acquiring high-quality images of distinctive fingerprint ridges and minutiae is complicated task.

People with no or few minutia points (surgeons as they often wash their hands with strong detergents, builders, people with special skin conditions) cannot enroll or use the system. The number of minutia points can be a limiting factor for security of the algorithm. Results can also be confused by false minutia points (areas of obfuscation that appear due to low-quality enrollment, imaging, or fingerprint ridge detail).

Note: There is some controversy over the uniqueness of fingerprints. The quality of partial prints is however the limiting factor. As the number of defining points of the fingerprint become smaller, the degree of certainty of identity declines. There have been a few well-documented cases of people being wrongly accused on the basis of partial fingerprints.

Benefits of fingerprint biometric systems

  • Easy to use
  • Cheap
  • Small size
  • Low power
  • Non-intrusive
  • Large database already available

Applications of fingerprint biometrics

Fingerprint sensors are best for devices such as cell phones, USB flash drives, notebook computers and other applications where price, size, cost and low power are key requirements. Fingerprint biometric systems are also used for law enforcement, background searches to screen job applicants, healthcare and welfare.

SSH port forwarding

To forward port from a host inside firewall so that i can access the host from home.

ssh -N -f -R 1234:localhost:22 USER@externalhost

this will forward MYHOST port 22 to port 1234 at the external server side.

From my home :: i access to the externalhost and dothis to access myhost:

ssh -p 1234 USER@localhost

Freebsd + PHP + MSSQL How To Connect Witt FreeTDS

// /usr/local/etc/freetds.conf

[global]
# TDS protocol version
tds version = 4.2
text size = 64512

[MSSQL2000]
host = XX.XX.XX.XX
port = 1433
tds version = 8.0

test connection with php

$dbhandle=mssql_connect("MSSQL2000", "username", "password")
or die("Couldn't connect to SQL Server on $myServer");

Convert a Computer ATX Power Supply to a Lab Power Supply

See Here ...

http://www.wikihow.com/Convert-a-Computer-AT X-Power-Supply-to-a-Lab-P ower-Supply" title="http://www.wikihow.com/Convert-a-Computer-AT X-Power-Supply-to-a-Lab-P ower-Supply" target="_blank"http://www.wikihow.com/Conver...

How do I create the libwinscard.a import library suitable for linking with native Windows WINSCARD.DLL

How do I create the libwinscard.a import library suitable for linking with native Windows WINSCARD.DLL ?

First, create the .def file from the DLL itself:

#> /usr/bin/impgen WINSCARD.DLL > winscard.def


Then, create the .a import library:

#> /usr/bin/dlltool --as=as \
#> --dllname WINSCARD.DLL --def winscard.def \
#> --kill-at --output-lib libwinscard.a


Now you can place libwinscard.a into a standard library path and use -lwinscard to link using it. Note that this file is only required to be found by gcc when linking. It will not be required when executing the program.

Adding New Users to MySQL

by Jeff Hunter, Sr. Database Administrator

You can add new users to MySQL in two different ways: by using the GRANT statement or my manipulating the MySQL grant tables directly. The preferred method is to use the GRANT statement because they are more concise and less error-prone.

The following examples show how to use the mysql client to set up new users. These examples assume that privileges are set up according to the defaults provided in the previous MySQL DBA Tip, "Setting Up the Initial MySQL Privileges". This means that to make changes, you must be on the same machine where mysqld is running, you must connect as teh MySQL root user, and the root user must have the insert privilege for the mysql database and the reload administrative privilege. Also, if you have changed the root user password, you must specify it for the following mysql commands:

You can add new users by issuing GRANT statements:

  % mysql -u root mysql
mysql> GRANT ALL PRIVILEGES ON *.* TO oracle@localhost
-> IDENTIFIED BY 'manager' WITH GRANT OPTION;

mysql> GRANT ALL PRIVILEGES ON *.* TO oracle@"%"
-> IDENTIFIED BY 'manager' WITH GRANT OPTION;

mysql> GRANT RELOAD, PROCESS ON *.* TO admin@localhost;

mysql> GRANT USAGE ON *.* TO dummy@localhost;

The GRANT statements (above) create and set up three new users:

  • oracle
    A full superuser who can connect to the server from anywhere, but who must use a password 'manager' to do so. Note that we must issue GRANT statements for both oracle@localhost and oracle@"%". If we don't add the entry with localhost, the anonymous user entry for localhost that is create by mysql_install_db will take precedence when we connect from the local host because it has a more specific Host field value and thus comes earlier in the user table sort order.
  • admin
    A user who can connect from localhost without a password and who is granted the reload and process administrative privileges. This allows the user to execute the mysqladmin reload, mysqladmin refresh, and mysqladmin flush_* commands, as well as mysqladmin processlist. No database-related privileges are granted. (They can be granted later by issuing additional GRANT statements.)
  • dummy
    A user who can connect without a password, but only from the local host. The global privileges are all set to 'N' - the usage privilege type allows you to create a user with no privileges. It is assumed that you will grant database-specific privileges later

Syslogd

Freebsd syslog
- by default syslog service is enable on freebsd with -ss option.
- to enable remote logging.
= edit /etc/syslog.conf
- add @hostname, where @hostname is the place where the logging server is located.
= make sure in /etc/service
- syslog 514/udp exist

AS400 logs in syslog

quota from http://www.securityfocus.com/...

> I would like to analyze in real time, the AS400 events. I'm seeking a
> method to forward AS400 logs in syslog, SNMP or SMTP.

I'm not familiar with the AS400 (been over 12 years), so please bare with me.
I assume the problem is there is no stock syslog and/or no way to get syslog
to compile? Is there a copy of logger? If so, you can use that. If not, its messy but:

tail -f /var/log/messages | nc -u 192.168.1.1 514 &

will work in a pinch.
I've used this to Syslog off log entries that I've been either too lazy to
setup correctly, or only needed a short term solution. This of course
means you need a working copy of Netcat, but the code is pretty small
and portable.

syslog windows client

Refer to link below for those who want to do a central remote logging.


Winlogd
Ntsyslogd
Evtsys


Syslog Logging with PostgreSQL HOWTO

PostgreSQL Database Setup

Create the a database named syslog. To do this, run this command: createdb syslog

Environment:

  • FreeBSD 5.1
  • Syslog-NG
  • PostgreSQL (v 7.3.2 used here; Compiled from source)

Next, create the table in the newly-created datbase. Download the SQL directly: syslog.sql

CREATE TABLE logs (
host varchar(32) default NULL,
facility varchar(10) default NULL,
priority varchar(10) default NULL,
level varchar(10) default NULL,
tag varchar(10) default NULL,
date date default NULL,
time time default NULL,
program varchar(15) default NULL,
msg text,
seq serial,
PRIMARY KEY (seq)
);

3. Syslog-NG Setup

Install Syslog-NG.

Edit your syslog-ng configuration file.

/etc/syslog-ng/syslog-ng.conf.

Here are the relevant parts of syslog-ng.conf:

#
# SQL logging support
#

destination d_pgsql {
pipe("/tmp/pgsql.pipe"
template("INSERT INTO logs (host, facility, priority, level, tag, date, time, program,
msg) VALUES ( '$HOST', '$FACILITY', '$PRIORITY', '$LEVEL', '$TAG,
'$YEAR-$MONTH-$DAY', '$HOUR:$MIN:$SEC', '$PROGRAM', '$MSG' );n
)

template-escape(yes)

);

};

log { source(src); destination(d_pgsql); };

Getting PostgreSQL and Syslog to Work Together

Use this script I've adapted for PostgreSQL, syslog-ng-pgsql-pipe.sh:

#!/bin/sh
#
# File: syslog-ng-pgsql-pipe.sh
#
# Take input from a FIFO and run execute it as a query for
# a PostgreSQL database.
#
# IMPORTANT NOTE: This could potentially be a huge security hole.
# You should change permissions on the FIFO accordingly.
#

if [ -e /tmp/pgsql.pipe ]; then
while [ -e /tmp/pgsql.pipe ]
do
psql -q -U mydbusername syslog < /tmp/pgsql.pipe> done
else
mkfifo /tmp/pgsql.pipe
fi


How to open/read/write a local file from an applet - jar signing

OK, here we go:

'keytool' is delivered with Sun's development kit.

>> keytool -genkey -keyalg rsa -alias yourkey
Follow the instructions and type in all needed information.

Now we make the certificate:
>> keytool -export -alias yourkey -file yourcert.crt

Now we have to sign the applet:

Just make a *.bat file including this:

javac yourapplet.java
jar cvf yourapplet.jar yourapplet.class
jarsigner yourapplet.jar yourkey

The batch-file compiles the applet, makes a jar-archive and signs the jar-file.

The HTML-code to display the applet:
  ;


Now we are done! The applet is signed and if the user accepts the certificate, the applet is allowed to access local files. If the user doesn't agree, this appears in the console:

[JAVA] Remove leading or trailing spaces in a String using regular expressions

import java.util.regex.*;

public class BlankRemover
{

/* remove leading whitespace */
public static String ltrim(String source) {
return source.replaceAll("^\\s+&qu ot;, "");

}

/* remove trailing whitespace */
public static String rtrim(String source) {
return source.replaceAll("\\s+$&qu ot;, "");
}

/* replace multiple whitespaces between words with single blank */

public static String itrim(String source) {
return source.replaceAll("\\b\\s{2 ,}\\b", " ");
}

/* remove all superfluous whitespaces in source string */
public static String trim(String source) {

return itrim(ltrim(rtrim(source) ));
}

public static String lrtrim(String source){
return ltrim(rtrim(source));
}

public static void main(String[] args){
String oldStr =

"> <1-2-1-2-1-2-1-2-1-2-1> <";
String newStr = oldStr.replaceAll("-", " ");
System.out.println(newStr);

System.out.println(ltrim(newStr));
System.out.println(rtrim(newStr));
System.out.println(itrim(newStr));
System.out.println(lrtrim(newStr));
}
}

Parsing and Formatting a Byte Array into Binary, Octal, and Hexadecimal

This example uses a BigInteger to convert a byte array to a string of binary, octal, or hexadecimal values.
    // Get a byte array
byte[] bytes = new byte[]{(byte)0x12, (byte)0x0F, (byte)0xF0};

// Create a BigInteger using the byte array
BigInteger bi = new BigInteger(bytes);

// Format to binary
String s = bi.toString(2); // 100100000111111110000

// Format to octal
s = bi.toString(8); // 4407760

// Format to decimal
s = bi.toString(); // 1183728

// Format to hexadecimal
s = bi.toString(16); // 120ff0
if (s.length() % 2 != 0) {
// Pad with 0
s = "0"+s;
}


// Parse binary string
bi = new BigInteger("1001000001111111100 00", 2);

// Parse octal string
bi = new BigInteger("4407760", 8);

// Parse decimal string
bi = new BigInteger("1183728");

// Parse hexadecimal string
bi = new BigInteger("120ff0", 16);

// Get byte array
bytes = bi.toByteArray();

VB6 connect to mysql

Private Sub cmdConnectMySQL_Click()

Dim cnMySql As New rdoConnection
Dim rdoQry As New rdoQuery
Dim rdoRS As rdoResultset

' set up a remote data connection
' using the MySQL ODBC driver.
' change the connect string with your username,
' password, server name and the database you
' wish to connect to.

cnMySql.CursorDriver = rdUseOdbc
cnMySql.Connect = "uid=YourUserName;pw d=YourPassword;
server=YourServerName;&qu ot; & _
"driver={MySQL ODBC 3.51 Driver};
database=YourDataBase;dsn =;"
cnMySql.EstablishConnection

' set up a remote data object query
' specifying the SQL statement to run.

With rdoQry
.Name = "selectUsers"
.SQL = "select * from user"
.RowsetSize = 1
Set .ActiveConnection = cnMySql
Set rdoRS = .OpenResultset(
& nbsp; &n bsp; rdOpenKeyset, rdConcurRowVer)
End With

' loop through the record set
' processing the records and fields.

Do Until rdoRS.EOF
With rdoRS

' your code to process the fields
' to access a field called username you would
' reference it like !username

& nbsp; rdoRS.MoveNext
End With
Loop

' close record set
' close connection to the database

rdoRS.Close
cnMySql.Close

End Sub

Install Apache on Windows Vista

Installing Apache under Windows XP was trivial. Not so, under Vista. Creation of the Apache service fails. The conf directory can’t be set up by the installer, probably due to permission problems.

I finally got it working with the following procedure. I used the latest version of Apache (2.2.4) and Windows Vista Home Premium.

  1. Uninstall any previous installations of Apache Web server (Start > Control Panel > Programs and Features).
  2. Turn off your firewall (Control Panel).
  3. Stop User Account Control (UAC).
  4. Get the most recent version of apache from http://httpd.apache.org/downl... and put it on your desktop. Rename it to apache.msi
  5. Start > All Programs > Accessories
  6. Right-Click “Command Prompt” and choose “Run as Administrator”
  7. Manually remove directories containing previous apache installations (like C:Program FilesApache Software Foundation…)
  8. Change to your desktop folder (At prompt type cd desktop)
  9. Type “msiexec /i apache.msi” on the command prompt.
  10. Run through the Apache installer. I’m running a development server, so I left the domain and computer name blank. Choose the default server on port 80 for all users option. Change the installation directory to c:apache.
  11. Reboot.
  12. The little Apache feather won’t appear on the task bar under Vista with the present version of Apache (2.2.4). To remove the “error” box that says ‘the operation completed successfully” on startup, go to All Programs > Startup, and remove the Apache item there.
  13. Browse to http://localhost. It should say “It works!” If it doesn’t, check your httpd.conf file by going to All Programs > Apache HTTP Server 2.2.x > Configure Apache Server > Test Configuration. Follow the directions for fixing the configuration file.
  14. Turn your firewall back on. You can turn UAC back on too, if you like (mine is off, and it’s staying off!)
Original Source http://senese.wordpress.com/2...

Changing Solaris 10 Hostname

This applied if the host is using DHCP

Make sure that the hostname you want to use is in /etc/nodename;
the contents of that file will then be used to set the hostname.
(Note that it is essential that the hostname you put into /etc/nodename
is terminated with a carriage return.

IF it set manually... look for these files:

Change the hostname in the following files:

/etc/nodename
/etc/hostname.*interface
/etc/inet/hosts
/etc/inet/ipnodes

and rename directory under /var/crash

# cd /var/crash
# mv oldname newname

then reboot the server.

Create thumbnail for pdf document using php

To convert source test.pdf to image test.jpg

Pass this command to php function ' system()';

#> gs -q -dNOPAUSE -dBATCH -sDEVICE=jpeg -sOutputFile=test.jpg test.pdf
#> convert -resize 120x120 test.jpg test.jpg

** this was successfully done on FreeBSD ....

Centos 7 reset root/ any user lost password / lockout due to cant remember password

1. Need to be in front of the terminal. (Physically if not vm). 2. Reboot the server 3. Press 'e' in the GRUB2 boot screen. 3. bunch...