Wednesday, September 15, 2010

Rename all files from one extension to another using DOS command line

I was looking for a fast way of massively renaming files from one extension to another. Apparently, DOS command line was pretty handy solving this issue.

For example, in order to rename all the files with extension “jpg” to “test” on the directory named “C:\My Pics” you should do:

ren "C:\My Pics\*.jpg" *.test

This is how it looks on the DOS command line:

1

Disable password complexity on Windows 2008 Server

Windows 2008 server enforces by default a pretty hard restrictive policy for defining user passwords. Actually, it is so hard, that after 15 minutes of trying to define a new password I simply gave up. Instead, I simply disabled the password complexity requirements.

Here is how you can easily disable password complexity on Windows 2008 Server:

First, you have to load a program named “gpedit”. Press on Windows “Start” button, and on the text box write: “gpedit.msc”. This is how it should look:

1

When “gpedit” is loaded, on the tree, go to: Computer Configuration –> Windows Settings –> Security Settings –> Account Policies –> Password Policy. This is how it looks:

2

On the right pane, you will see list of policies. Search for a policy named: “Password must meet complexity requirments”. It should be “Enabled”. In order to disable it, double click on the policy. A dialog will open:

3

Choose: “Disabled” value and press “OK”. That’s it. Now you will be able easily define/change passwords on Windows 2008 server.

Sunday, September 12, 2010

EXIF Eraser – Free EXIF/IPTC/XMP erasing software

A long time ago, I was using Delphi to write all of my software. I think Delphi was and still is the best choice for rapidly developing Windows UI applications (though I have to admit, I have superficial familiarity with Visual Basic and C#, that I believe are also good candidates for Windows UI development). The biggest problem with Delphi, is that you have to write in Pascal, which is kind of an anachronistic language.

Anyway, a month ago, I decided It will be a nice thing, to have a look at Delphi again, and check what way it did along the years I left it. I downloaded the latest Delphi version from http://www.embarcadero.com/, which I believe is currently the company that maintains and develops the future of Delphi. Back then, Delphi was strongly identified with Borland. I was surprised to find, that things didn’t changed much along the years. Many features of modern IDEs were added, but the main idea was pretty much identical.

In order to refresh my Delphi development skills, I decided to write a small utility program, that wipes EXIF, IPTC and XMP meta data from image files. EXIF (Exchangeable Image File) data is a record of what camera settings were used to take a photograph. This data is recorded into the actual image file. Therefore each photograph has its own unique data. EXIF data stores information like camera model, exposure, aperture, ISO, what camera mode was used and whether or not a flash fired. IPTC and XMP are also additional meta data that are attached to image files.

I named the utility: Free EXIF Eraser. The nice thing is, that it deletes EXIF, IPTC and XMP meta data without doing any modifications to the original image. That means, the quality of the original image is kept untouched.

It was so fun and easy to get back to Delphi development, that I decided to put a bit more effort on my small utility: I dedicated for it a special domain and created a home page. If you need a small and lightweight utility, that will easily erase EXIF, IPTC and XMP meta data, you can check: http://www.exiferaser.com

Monday, August 30, 2010

Change Windows clock time synchronization interval

Windows has an option synchronizing it’s time against a time server. The time server returns a very accurate time. In order to synchronize your machine with a time server you need double click on the clock that appears on the task bar. On Windows 2003 server you should see something like this:
image
Then move to the tab named: “Internet Time”:
image
Make sure that the check box: “Automatically synchronize with an Internet time server” is checked.
Usually, we would like to synchronize several servers on our farm to have almost exactly the same time. For this, the default synchronization interval of Windows is not enough, since it takes only a few days to start seeing differences.
Changing the default synchronization interval can be done by changing the value of the key: “SpecialPollInterval” in the registry of the machine.
This is the complete path of the key:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpClient\SpecialPollInterval
In order to change the synchronization interval to 1 hour, set the DWORD value to: e10 which is 3600 in hexadecimal. The value is in seconds, therefore 3600 gives 1 hour.
This is how it looks on regedit:
image
After updating the value in the registry, press the “Update Now” on the “Date and Time Properties” window, and make sure, that the “Next synchronization” shows you a next update time of an hour.

Friday, July 16, 2010

Firefox – Disable login confirmation dialog

There are times FireFox presents a confirmation dialog, telling you that you are about to log in to a site that does not requires authentication. The exact text of this dialog is:

You are about to log in to the site “somesite.com” the the username “someuser”, but the web site does not require authentication. This may be an attempt to trick you. Is “somesite.com” the site you want to visit.

And here is how the dialog looks like:

image

By showing this dialog FireFox is trying to protect you from cases in which someone would like to trick you to go to a different domain. For example, take a look at the following url:

http://www.mybank.com:password@example.com/badsite

The first part of the url is: “www.mybank.com:password”, is not a domain, but actually the username/password used to log to the domain: example.com. FireFox showing this dialog in order to get your attention and decide if you are sure you would like to proceed to the domain.

However, if this dialog is annoying you, you can easily remove it. First, write on FireFox url: “about:config”. This will take you to FireFox advanced configuration. This configuration contains a long list of keys and values. In order to cancel the configuration dialog you have to add a new value by right clicking on the list and selecting: new—> Integer from the popup menu:

image

On the popup that will show enter the following value: “network.http.phishy-userpass-length”

image

The press “OK” and enter the value: 255

image

That’s it. The confirmation dialog should never bother you again.

Friday, July 9, 2010

Set/Reset identity value on SQL Server 2005

There are times we would like to set identity column to a specific value on SQL Server. In the most common case, we would like to reset it to start from the value 1.

This is how it is done:

DBCC CHECKIDENT('some_table', RESEED, 0)


Note that the last parameter is the value for which the identity column is set. If we set it to: 0, the next value of the inserted row will be: 1.

Thursday, June 3, 2010

Java interview question: Fibonacci Series

Fibonacci series is a sequence of numbers, in which, each number is the sum of it’s previous 2 numbers. The first 2 numbers in the sequence are by definition: 0 and 1.
For some reason, it seem like writing a Java function that returns Fibonacci number is favorited by interviewers. I really find it difficult to understand why an interviewer would ask this kind of question, since it is not a question that implies on any practical knowledge or experience and can be easily memorized.
But, anyway, let’s see how it is done:
There are 2 ways of writing this function: recursive and none recursive. Interviewers may ask to write both versions.
Let’s start with the recursive version, which is surprisingly simple. well… simple if do not try to debug it in your head, but think of the process in a more mathematical way. In general, I believe that solving recursion problems is much simpler if you think of the solution in an abstract way, rather than trying to figure what exactly going on on each iteration.
Well, this is how the recursive function looks like:
package com.bashan.blog.interview;
/**
* @author Bashan
*/
public class Fibonacci {
  public static int fibonacci1(int n)
  {
    if (n == 0)
    {
      return 0;
    }
    else if (n == 1)
    {
      return 1;
    }
    else
    {
      return fibonacci1(n - 1) + fibonacci1(n - 2);
    }
}
 
public static void main(String[] args)
  {
    System.out.println(fibonacci1(12));
  }
}
Note, that both 2 first numbers in the series are handled separately. The output of the test program is of course: 144.
This function can be shorten to a single line of code:
package com.bashan.blog.interview;
/**
* @author Bashan
*/
public class Fibonacci {
  public static int fibonacci2(int n)
  {
    return n == 0 ? 0 : (n == 1 ? 1 : (fibonacci1(n - 1) + fibonacci1(n - 2)));
  }
}
The none recursive version should always save the current and the previous number in order to calculate the next number in the series. Let’s see how it looks in Java code:
package com.bashan.blog.interview;
/**
* @author Bashan
*/
public class Fibonacci {
  public static int fibonacci3(int n)
  {
    int prevN = 0, currentN = 1;
    for (int i = 0; i < n; i++)
    {
      int saveCurrentN = currentN;
      currentN = prevN + currentN;
      prevN = saveCurrentN;
    }
   
    return prevN;
  }
}
Note, that we return prevN rather than currentN. This saves us for writing a logic to handle the case of n = 0.
Here is a Java class that contains all 3 functions.

Check out this cool infographic to learn more about Fibonacci series.

Saturday, May 22, 2010

Get first and last thumb of a video using Java and FFMpeg

In the post Java Video to FLV (Flash Video) converter using FFmpeg we saw how almost any video format can be easily converted to FLV video file using FFMpeg.

FFMpeg can do much more. It can also grab a thumb at any size from any point of time in the video. We will see how it can be used to get the first and the last thumbs of a video. Getting the first thumb of a video is not so hard. You simply have to take the thumb at zero or first second of the video.

In order to achieve that, we will first construct a Java class that can take a thumb from a given video file for a given second minute and hour:"

package com.bashan.blog.video;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
/**
 * @author Bashan
 */
public class VideoThumbTaker
{
  protected String ffmpegApp;
  public VideoThumbTaker(String ffmpegApp)
  {
    this.ffmpegApp = ffmpegApp;
  }
  public void getThumb(String videoFilename, String thumbFilename, int width, int height,int hour, int min, float sec)
      throws IOException, InterruptedException
  {
    ProcessBuilder processBuilder = new ProcessBuilder(ffmpegApp, "-y", "-i", videoFilename, "-vframes", "1",
        "-ss", hour + ":" + min + ":" + sec, "-f", "mjpeg", "-s", width + "*" + height, "-an", thumbFilename);
    Process process = processBuilder.start();
    InputStream stderr = process.getErrorStream();
    InputStreamReader isr = new InputStreamReader(stderr);
    BufferedReader br = new BufferedReader(isr);
    String line;
    while ((line = br.readLine()) != null);
    process.waitFor();
  }
  public static void main(String[] args)
  {
    VideoThumbTaker videoThumbTaker = new VideoThumbTaker("C:\\ffmpeg.exe");
    try
    {
      videoThumbTaker.getThumb("C:\\someVideo.flv", "C:\\thumbTest.png", 120, 100, 0, 0, 10);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }
}


Take a look at the test program, showing how a thumb is being taken from the 10th second of a video named: “someVideo.flv”. Note that we pass to the constructor the class the location of your FFMpeg tool. Also note, that we pass the width and height of the thumb.



After we have a class that knows to grab the thumb of any size from any video on a specific point in time, we can easily construct a class that grabs the first thumb of a video:



package com.bashan.blog.video;
import java.io.IOException;
/**
 * @author Bashan
 */
public class VideoFirstThumbTaker extends VideoThumbTaker
{
  public VideoFirstThumbTaker(String ffmpegApp)
  {
    super(ffmpegApp);
  }
  public void getThumb(String videoFilename, String thumbFilename, int width, int height)
      throws IOException, InterruptedException
  {
    super.getThumb(videoFilename, thumbFilename, width, height, 0, 0, 1);
  }
}


In that class we simply extend our “VideoThumbTaker” to grab the first second of the video. Grabbing the zero second of the video is not a good idea, since the first frame in many videos usually black.



In order to get the last frame of a video, we first have to know what is it’s length in hours, minutes and seconds. FFMpeg can also help us with that. We will take a dummy thumb from the video, by doing it, FFMpeg will write to the standard output the video information. We will use simple regular expression to extract the length of the video in term of hours, minutes and second. and finally, we will delete the dummy thumb that was created:



package com.bashan.blog.video;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * @author Bashan
 */
public class VideoInfo {
  private String ffmpegApp;
  private int hours;
  private int minutes;
  private float seconds;
  public VideoInfo(String ffmpegApp) {
    this.ffmpegApp = ffmpegApp;
  }
  public void getInfo(String videoFilename)
      throws IOException, InterruptedException {
    String tmpFile = videoFilename + ".tmp.png";
    ProcessBuilder processBuilder = new ProcessBuilder(ffmpegApp, "-y", "-i", videoFilename, "-vframes", "1",
        "-ss", "0:0:0", "-an", "-vcodec", "png", "-f", "rawvideo", "-s", "100*100", tmpFile);
    Process process = processBuilder.start();
    InputStream stderr = process.getErrorStream();
    InputStreamReader isr = new InputStreamReader(stderr);
    BufferedReader br = new BufferedReader(isr);
    String line;
    StringBuffer sb = new StringBuffer();
    while ((line = br.readLine()) != null) {
      sb.append(line);
    }
    new File(tmpFile).delete();
    Pattern pattern = Pattern.compile("Duration: (.*?),");
    Matcher matcher = pattern.matcher(sb);
    if (matcher.find()) {
      String time = matcher.group(1);
      calcTime(time);
    }
    process.waitFor();
  }
  private void calcTime(String timeStr) {
    String[] parts = timeStr.split(":");
    hours = Integer.parseInt(parts[0]);
    minutes = Integer.parseInt(parts[1]);
    seconds = Float.parseFloat(parts[2]);
  }
  public int getHours() {
    return hours;
  }
  public int getMinutes() {
    return minutes;
  }
  public float getSeconds() {
    return seconds;
  }
  public static void main(String[] args) {
    VideoInfo videoInfo = new VideoInfo("C:\\ffmpeg.exe");
    try {
      videoInfo.getInfo("C:\\testVideo.wmv");
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}


We will now use our “VideoInfo” class to construct: “VideoLastThumbTaker”. We will take the duration of the video, and subtract from it’s seconds part a small value of: 0.2 second , in order to take almost the last thumb of the video. Note: This class doesn’t handle properly a case in which the video seconds part length is a bit less than 0.2 seconds. I assume you won’t have much terrible handling this case yourself. Let’s have a look at the class:



package com.bashan.blog.video;
import java.io.IOException;
/**
 * @author Bashan
 */
public class VideoLastThumbTaker extends VideoThumbTaker
{
  public VideoLastThumbTaker(String ffmpegApp)
  {
    super(ffmpegApp);
  }
  public void getThumb(String videoFilename, String thumbFilename, int width, int height)
      throws IOException, InterruptedException
  {
    VideoInfo videoInfo = new VideoInfo(ffmpegApp);
    videoInfo.getInfo(videoFilename);
    super.getThumb(videoFilename, thumbFilename, width, height, videoInfo.getHours(),
                                                                videoInfo.getMinutes(), videoInfo.getSeconds() - 0.2f);
  }
}

You can download the source of that classes here.

Tuesday, May 4, 2010

Tomcat Performance: gzip Compression

One of the ways of increasing server performance, is by reducing the amount of data passed on the network. This can be done by using compression.
Most modern web browsers support compression. If a browser supports compression it will send in the request header the following string:
Accept-Encoding: gzip,deflate
The server can identify this header and return a compressed response. If the browser doesn’t send this header, the server will always return an uncompressed response. If the response is compressed, it will return in the response header the following string:
Content-Encoding: gzip
Now the client knows that the response is gzip compressed.
Tomcat supports gzip compression out of the box. You can easily add compression support to your server, without writing a single line of code.
To turn on Tomcat compression, you should edit server.xml, which is located under Tomcat conf directory. The compression is added to the connector element:
<Connector port="8080" protocol="HTTP/1.1" 
connectionTimeout="20000" redirectPort="8443" 
compression="on" compressableMimeType="text/html,
text/xml,text/plain,text/javascript,text/css" 
/>
Note that you can determine the mime types for which tomcat should do the compression.
Sometimes there are user agents (web browsers) that has problems with gzip compression, even If they send Content-Encoding: gzip direction in the request header. In order to exclude specific user agents from being served with gzip compression you can use the property: noCompressionUserAgents. You can use regular expression to define user agents list separated with commas:
<Connector port="8080" protocol="HTTP/1.1" 
connectionTimeout="20000" redirectPort="8443" 
compression="on" compressableMimeType="text/html,text/xml,text/plain,text/javascript,text/css" 
noCompressionUserAgents=".*MSIE 6.*"
/>


If a file is too small, the overhead of compressing it may take longer than sending it uncompressed. You can define a minimum size for which a compression should not be done:
<Connector port="8080" protocol="HTTP/1.1" 
connectionTimeout="20000" redirectPort="8443"
compression="on" compressableMimeType="text/html,text/xml,text/plain,text/javascript,text/css" 
noCompressionUserAgents=".*MSIE 6.*"
compressionMinSize="1024"
/>

Saturday, May 1, 2010

Installing Apache FLV module on Windows

Most modern FLV players can show a video from a specific point. But this can only be done with server side help. In order to support this feature you will first have to inject meta data to the FLV file. This can be done, for example, with a command line named: Yamdi

The meta data, is actually a vector mapping specific points in time to their corresponding byte in the FLV file. When you move the video progress bar, the player is sending a request for the FLV file with a parameter named “start”. The parameter contains the specific byte in the FLV file from which we would like to see the vide.

Apache has a very nice module, named mod_flvx, that supports FLV streaming out of the box. When it receives a request for FLV with with the “start” parameter, it automatically knows to return the file starting at the given byte.

Finding a Windows compiled version of the module took me quite some time. So I put it here as a direct download.

Put the module under Apache modules directory and add these lines in your httpd.conf configuration file:

LoadModule flvx_module modules/mod_flvx.so
AddHandler flv-stream .flv

Restart your server, and you are ready to go. You can test the module, but making a request with the start parameter to some FLV file. For example:

http://localhost/myflv.flv?start=10000

If the module is installed properly, Apache will return the FLV file starting from byte 10,000.