PHP: Generate a unique filename for a given directory

This function will generate a filename unique to specified directory. If you’re using it to create filenames for uploaded images, for example, you can give it a path to your upload folder an extension such as ‘jpg’.

It will generate the filename using the characters specified in the function, you can modify it as desired. I chose to omit uppercase letters in case you are running this on a Windows system (case insensitive).

/**
 * Converts large hexidecimal numbers into decimal strings.
 *
 * @param string $hex Hexidecimal number
 * @return string Decimal number
 * @see http://stackoverflow.com/a/1273535/65387
 */

function bchexdec($hex)
{
    $dec = 0;
    $len = strlen($hex);
    for ($i = 1; $i <= $len; $i++) {
        $dec = bcadd($dec, bcmul(strval(hexdec($hex[$i - 1])), bcpow('16', strval($len - $i))));
    }
    return $dec;
}

function base_encode($val, $base=62, $chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
    if(!$base) $base = strlen($chars);
    $str = '';
    do {
        $m = bcmod($val, $base);
        $str = $chars[$m] . $str;
        $val = bcdiv(bcsub($val, $m), $base);
    } while(bccomp($val,0)>0);
    return $str;
}

function unique_filename($dir, $ext='') {
    do {
        $filename = $dir.'/'.base_encode(bchexdec(uniqid()), null, '0123456789abcdefghijklmnopqrstuvwxyz_-');
        if($ext) $filename .= '.'.$ext;
    }while(file_exists($filename));
    return $filename;
}
Posted in

High quality image resize (C#)

You can use this class to resize images proportionally (maintaining aspect ratio), or to resize an image to an exact size and crop off excess (useful for making nice thumbnails):

 


public static class ImageExt {
  public static Image Resize(this Image img, int srcX, int srcY, int srcWidth, int srcHeight, int dstWidth, int dstHeight) {
    var bmp = new Bitmap(dstWidth, dstHeight);
    using(var graphics = Graphics.FromImage(bmp)) {
      graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
      graphics.CompositingMode = CompositingMode.SourceCopy;
      graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
      using(var wrapMode = new ImageAttributes()) {
        wrapMode.SetWrapMode(WrapMode.TileFlipXY);
        var destRect = new Rectangle(0, 0, dstWidth, dstHeight);
        graphics.DrawImage(img, destRect, srcX, srcY, srcWidth, srcHeight, GraphicsUnit.Pixel, wrapMode);
      }
    }
    return bmp;
  }

  public static Image ResizeProportional(this Image img, int width, int height, bool enlarge = false) {
    double ratio = Math.Max(img.Width / (double) width, img.Height / (double) height);
    if (ratio &lt; 1 &amp;&amp; !enlarge) return img;
    return img.Resize(0, 0, img.Width, img.Height, M2.Round(img.Width / ratio), M2.Round(img.Height / ratio));
  }
  public static Image ResizeCropExcess(this Image img, int dstWidth, int dstHeight) {
    double srcRatio = img.Width / (double) img.Height;
    double dstRatio = dstWidth / (double) dstHeight;
    int srcX,
    srcY,
    cropWidth,
    cropHeight;
    if (srcRatio &lt; dstRatio) // trim top and bottom
    {
      cropHeight = dstHeight * img.Width / dstWidth;
      srcY = (img.Height - cropHeight) / 2;
      cropWidth = img.Width;
      srcX = 0;
    } else // trim left and right
    {
      cropWidth = dstWidth * img.Height / dstHeight;
      srcX = (img.Width - cropWidth) / 2;
      cropHeight = img.Height;
      srcY = 0;
    }
    return Resize(img, srcX, srcY, cropWidth, cropHeight, dstWidth, dstHeight);
  }
}
Posted in

Convert decimal numbers to any base (C#)

You can use this little function to convert a decimal to any base. I use it for compacting large numbers.

public static class BaseConverter
{
    public static string Encode(BigInteger value, int @base=0, string chars="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
    {
        if (@base <= 0) @base = chars.Length;
        var sb = new StringBuilder();
        do
        {
            int m = (int)(value % @base);
            sb.Insert(0, chars[m]);
            value = (value - m) / @base;
        } while (value > 0);
        return sb.ToString();
    }
}

Or you can use it to make a nice GUID:

private static BigInteger UnsignedBigInt(byte[] bytes)
{
    if ((bytes[bytes.Length - 1] & 0x80) != 0) Array.Resize(ref bytes, bytes.Length + 1);
    return new BigInteger(bytes);
}

private static string GetUniqueFileName(string extension)
{
    return BaseConverter.Encode(UnsignedBigInt(Guid.NewGuid().ToByteArray()), 0, "0123456789abcdefghijklmnopqrstuvwxyz_-") + extension;
}
Posted in

Microphone Boost

This post is a bit a different than my usual posts.

I was on Skype, about to start a gaming session with my friend, when he notified me that my mic was really quiet compared to when he talked to his other friends. I checked my settings, everything was maxed out in both Skype and Windows Sound settings.

He told me about this “microphone boost” option that he used before, but I didn’t seem to have it. I thought maybe my driver was out of date?

I tried updating my driver via Windows Devices to no avail, so I tried looking for one from my hardware vendor. Problem is, I couldn’t remember who made my hardware, and I didn’t feel like popping open my computer.

I’ve used a program to give me my device information in the past, but I also couldn’t remember what it was called. I found a new one called HWiNFO which seems to do a pretty good job though. It looks like this:

From here I could see my motherboard was an Asus Sabertooth 55i. Googling “asus sabertooth 55i drivers” lead me to the driver I needed. Get the audio driver.

Unless of course, you have a dedicated sound card. Then grab the driver for that instead! I had one before, but I didn’t feel the need to plug it in for my new rig.

After installing the driver (and a mandatory reboot), I found this ugly guy on my desktop:

Doesn’t have a lot of settings (that I can see), but the volume slider wasn’t maxed out yet.

So I upped that, and then went back into my sound settings and discovered I had a new option!

Upping the Microphone Boost to just 10 dB give me a huge boost in volume output. Huzzah!

Hopefully someone else with the same problem will find this post useful.

Using OpenGL with Qt: A Tutorial with Code Examples and Screenshots

My last tutorial on this subject was written almost thee years ago, and it’s still the most popular article on this blog, yet I’m not sure even I could follow it. Thus, I’m going through the steps again with the latest versions of NetBeans (7.1.2) and Qt (4.8.1), this time taking screenshots along the way.

Read more Using OpenGL with Qt: A Tutorial with Code Examples and Screenshots

Find where executable is installed to

Often when writing a script, I want to put a hashbang (#!) at the top so that I can execute the file, but I can never remember where the binary for python or php is installed to. An easy way to find out is to use the which command:

mark-ubuntu$ which python
/usr/local/bin/python

Another nice command is whereis which will “locate the binary, source, and manual page files for a command”:

mark-ubuntu$ whereis python
python: /usr/bin/python2.6-config /usr/bin/python2.6 /usr/bin/python /etc/python2.6 /etc/python /usr/lib/python3.1 /usr/lib/python2.6 /usr/local/bin/python2.7-config /usr/local/bin/python2.7 /usr/local/bin/python /usr/local/lib/python2.7 /usr/local/lib/python2.6 /usr/include/python2.6 /usr/share/python /usr/share/man/man1/python.1.gz

JSON Prettifier

This is a simple class I wrote to nicely format a JSON string. Just call it with JsonFormatter.PrettyPrint(yourJsonString)

public static class JsonFormatter
{
    public static string Indent = "    ";

    public static void AppendIndent(StringBuilder sb, int count)
    {
        for (; count > 0; --count) sb.Append(Indent);
    }

    public static bool IsEscaped(StringBuilder sb, int index)
    {
        bool escaped = false;
        while (index > 0 && sb[--index] == '\\') escaped = !escaped;
        return escaped;
    }

    public static string PrettyPrint(string input)
    {
        var output = new StringBuilder(input.Length * 2);
        char? quote = null;
        int depth = 0;

        for(int i=0; i<input.Length; ++i)
        {
            char ch = input[i];

            switch (ch)
            {
                case '{':
                case '[':
                    output.Append(ch);
                    if (!quote.HasValue)
                    {
                        output.AppendLine();
                        AppendIndent(output, ++depth);
                    }
                    break;
                case '}':
                case ']':
                    if (quote.HasValue)  
                        output.Append(ch);
                    else
                    {
                        output.AppendLine();
                        AppendIndent(output, --depth);
                        output.Append(ch);
                    }
                    break;
                case '"':
                case '\'':
                    output.Append(ch);
                    if (quote.HasValue)
                    {
                        if (!IsEscaped(output, i))
                            quote = null;
                    }
                    else quote = ch;
                    break;
                case ',':
                    output.Append(ch);
                    if (!quote.HasValue)
                    {
                        output.AppendLine();
                        AppendIndent(output, depth);
                    }
                    break;
                case ':':
                    if (quote.HasValue) output.Append(ch);
                    else output.Append(" : ");
                    break;
                default:
                    if (quote.HasValue || !char.IsWhiteSpace(ch))
                        output.Append(ch);
                    break;
            }
        }

        return output.ToString();
    }
}
Posted in

Subtracting Sets

A couple times now I’ve wanted to subtract one set (`HashSet`) from another. `HashSet` has a method ExceptWith that does just this, except that it modifies the current set in place. What if you don’t want that? You need to copy it first.

Or you could use Linq’s Except method, except that it returns `IEnumerable` instead of a `HashSet`. What if you don’t want that? You need to convert it.

So… which method is faster? Let’s find out!

static class Program
{
    public static HashSet<T> ToSet<T>(this IEnumerable<T> collection)
    {
        return new HashSet<T>(collection);
    }

    public static HashSet<T> Subtract<T>(this HashSet<T> set, IEnumerable<T> other)
    {
        var clone = set.ToSet();
        clone.ExceptWith(other);
        return clone;
    }

    static void Main(string[] args)
    {
        var A = new HashSet<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        var B = new HashSet<int> { 2, 4, 6, 8, 10 };
        var sw = new Stopwatch();

        sw.Restart();
        for (int i = 0; i < 1000000; ++i)
        {
            var C = A.Except(B).ToSet();
        }
        sw.Stop();
        Console.WriteLine("Linq: {0} ms", sw.ElapsedMilliseconds);

        sw.Restart();
        for (int i = 0; i < 1000000; ++i)
        {
            var C = A.Subtract(B);
        }
        sw.Stop();
        Console.WriteLine("Native: {0} ms", sw.ElapsedMilliseconds);

        Console.ReadLine();
    }
}

On my computer, this outputs:

Linq: 1291 ms
Native: 756 ms

So, clearly the second method is faster. About 40% for you math types.

I should note that “clone” isn’t really a clone, it’s a shallow copy. Only the container class itself is “cloned”; the elements still refer their originals.

Posted in