To split an image into tiles using ImageMagick
If you've got ImageMagick installed, you can split an image into squares with a command like:
convert -crop 256x256 terrain.png tiles/tile%03d.png
I'm using this to break up a MineCraft texture I downloaded.
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:
/usr/local/bin/python
Another nice command is whereis which will "locate the binary, source, and manual page files for a command":
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 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();
}
}
Subtracting Sets
A couple times now I've wanted to subtract one set (`HashSet
Or you could use Linq's Except method, except that it returns `IEnumerable
So... which method is faster? Let's find out!
{
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.
String Slice
Here's an extension method to slice strings in C#, similar to Python's slice notation.
{
if (step == 0) throw new ArgumentException("Step size cannot be zero.", "step");
if (start == null) start = step > 0 ? 0 : str.Length - 1;
else if (start < 0) start = start < -str.Length ? 0 : str.Length + start;
else if (start > str.Length) start = str.Length;
if (end == null) end = step > 0 ? str.Length : -1;
else if (end < 0) end = end < -str.Length ? 0 : str.Length + end;
else if (end > str.Length) end = str.Length;
if (start == end || start < end && step < 0 || start > end && step > 0) return "";
if (start < end && step == 1) return str.Substring(start.Value, (end - start).Value);
var sb = new StringBuilder((int)Math.Ceiling((end - start).Value / (float)step));
for (int i = start.Value; step > 0 && i < end || step < 0 && i > end; i += step)
sb.Append(str[i]);
return sb.ToString();
}
"Hello World".Slice(1, -1); // ello Worl
"Hello World".Slice(null, null, -1); // dlroW olleH
How to deep-copy/clone an object
The easiest way to deep copy an object is to serialize and deserialize it. Here's an example from a project I'm working on:
public class Board :ICloneable, ISerializable {
// ...
object ICloneable.Clone()
{
return this.Clone();
}
public Board Clone()
{
using (var ms = new MemoryStream())
{
var bf = new BinaryFormatter();
bf.Serialize(ms, this);
ms.Position = 0;
return (Board)bf.Deserialize(ms);
}
}
You might need to implement the serialization functions too for this to work, however.
Recursive get/set/has-attr
try: left, right = attr.split('.', 1)
except: return getattr(obj, attr, default)
return _getattr(getattr(obj, left), right, default)
def _setattr(obj, attr, val):
try: left, right = attr.split('.', 1)
except: return setattr(obj, attr, val)
return _setattr(getattr(obj, left), right, val)
def _hasattr(obj, attr):
try: left, right = attr.split('.', 1)
except: return hasattr(obj, attr)
return _hasattr(getattr(obj, left), right)
class C(object): pass
a = C()
a.b = C()
a.b.c = 4
assert _getattr(a, 'b.c') == 4
_setattr(a, 'b.c', 2)
assert a.b.c == 2
assert _hasattr(a, 'b.c')
Thread-Safe Observable List for WPF
I'm probably posting this too early; I haven't had a chance to extensively test it yet but I basically just locked every function down, and made any method that actually modifies the list run on the main thread so that notifications can be sent. It ought to work
{
private Dispatcher dispatcher;
private List<T> list;
private object sync;
public ObservableList(Dispatcher dispatcher = null)
{
this.dispatcher = dispatcher ?? Dispatcher.CurrentDispatcher;
this.list = new List<T>();
this.sync = new object();
}
public event NotifyCollectionChangedEventHandler CollectionChanged;
public virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
lock (sync)
{
if (CollectionChanged != null)
{
CollectionChanged(this, e);
}
}
}
public int IndexOf(T item)
{
lock (sync)
{
return list.IndexOf(item);
}
}
public void Insert(int index, T item)
{
if (dispatcher.CheckAccess())
{
lock (sync)
{
list.Insert(index, item);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index));
}
}
else
{
dispatcher.Invoke(new Action<int, T>(Insert), DispatcherPriority.Send, index, item);
}
}
public void RemoveAt(int index)
{
if (dispatcher.CheckAccess())
{
lock (sync)
{
var item = list[index];
list.RemoveAt(index);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, index));
}
}
else
{
dispatcher.Invoke(new Action<int>(RemoveAt), DispatcherPriority.Send, index);
}
}
public T this[int index]
{
get
{
lock (sync) { return list[index]; }
}
set
{
lock (sync) { list[index] = value; }
}
}
public void Add(T item)
{
if (dispatcher.CheckAccess())
{
lock (sync)
{
list.Add(item);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item));
}
}
else
{
dispatcher.Invoke(new Action<T>(Add), DispatcherPriority.Send, item);
}
}
public void Clear()
{
if (dispatcher.CheckAccess())
{
lock (sync)
{
list.Clear();
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}
else
{
dispatcher.Invoke(new Action(Clear), DispatcherPriority.Send);
}
}
public bool Contains(T item)
{
lock (sync) { return list.Contains(item); }
}
public void CopyTo(T[] array, int arrayIndex)
{
lock (sync) { list.CopyTo(array, arrayIndex); }
}
public int Count
{
get { lock (sync) { return list.Count; } }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(T item)
{
if (dispatcher.CheckAccess())
{
lock (sync)
{
var index = list.IndexOf(item);
var result = list.Remove(item);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, index));
return result;
}
}
else
{
return (bool)dispatcher.Invoke(new Func<T, bool>(Remove), DispatcherPriority.Send, item);
}
}
public IEnumerator<T> GetEnumerator()
{
lock (sync)
{
return list.GetEnumerator();
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
You can simply delete the "where T : INotifyPropertyChanged" if you don't like that restriction, but I put it there so that you don't forget that your objects should notify your controls that their properties have changed, so that the GUI gets refreshed properly.
Thread-Safe Observable Priority Queue for WPF
Building on my last post, I realized that you couldn't push elements onto the queue from a worker thread, making it pretty much useless. However, if we dispatch the pushes back to the UI thread, it should work, right?
Here's (what I believe to be) a thread-safe observable priority queue with notifications for use in WPF.
where TValue : INotifyPropertyChanged
where TPriority : IComparable
{
private SortedDictionary<TPriority, Queue<TValue>> dict;
private int count;
private Dispatcher dispatcher;
public int Count { get { return count; } }
public bool Empty { get { return Count == 0; } }
public PriorityQueue(Dispatcher dispatcher = null)
{
this.dispatcher = dispatcher ?? Dispatcher.CurrentDispatcher;
this.count = 0;
this.dict = new SortedDictionary<TPriority, Queue<TValue>>(new ReverseComparer());
}
private class ReverseComparer : IComparer<TPriority>
{
public int Compare(TPriority x, TPriority y) { return y.CompareTo(x); }
}
public virtual void Push(TValue val, TPriority pri = default(TPriority))
{
if (dispatcher.CheckAccess())
{
++count;
if (!dict.ContainsKey(pri)) dict[pri] = new Queue<TValue>();
dict[pri].Enqueue(val);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, val));
}
else
{
dispatcher.Invoke(new Action<TValue, TPriority>(Push), DispatcherPriority.Send, val, pri);
}
}
public virtual TValue Peek()
{
return dict.First().Value.Peek();
}
public virtual TValue Pop()
{
if (dispatcher.CheckAccess())
{
--count;
var pair = dict.First();
var queue = pair.Value;
var val = queue.Dequeue();
if (queue.Count == 0) dict.Remove(pair.Key);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, val));
return val;
}
else
{
return (TValue)dispatcher.Invoke(new Func<TValue>(Pop), DispatcherPriority.Send);
}
}
public event NotifyCollectionChangedEventHandler CollectionChanged;
public virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (CollectionChanged != null)
{
CollectionChanged(this, e);
}
}
public IEnumerator<TValue> GetEnumerator()
{
foreach (var queue in dict.Values)
{
foreach (var value in queue)
{
yield return value;
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
Read this blog post to find out how this works.
Observable Priority Queue
Just started playing around with WPF in VS 2010. They have this ObservableCollection class which you can bind to your DataGrid or ListControl and then when you add or remove items from it, the control is refreshed automatically. However, I wanted to use my PriorityQueue class that I posted about earlier, so I modified it a bit:
class PriorityQueue<TValue, TPriority> : IEnumerable<TValue>, INotifyCollectionChanged
where TValue : INotifyPropertyChanged
where TPriority : IComparable
{
private SortedDictionary<TPriority, Queue<TValue>> dict = new SortedDictionary<TPriority, Queue<TValue>>(new ReverseComparer());
private int count = 0;
public int Count { get { return count; } }
public bool Empty { get { return Count == 0; } }
private class ReverseComparer : IComparer<TPriority>
{
public int Compare(TPriority x, TPriority y) { return y.CompareTo(x); }
}
public void Enqueue(TValue val, TPriority pri = default(TPriority))
{
++count;
if (!dict.ContainsKey(pri)) dict[pri] = new Queue<TValue>();
dict[pri].Enqueue(val);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, val));
}
public TValue Dequeue()
{
--count;
var pair = dict.First();
var queue = pair.Value;
var val = queue.Dequeue();
if (queue.Count == 0) dict.Remove(pair.Key);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, val));
return val;
}
public event NotifyCollectionChangedEventHandler CollectionChanged;
public virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (CollectionChanged != null)
{
CollectionChanged(this, e);
}
}
public IEnumerator<TValue> GetEnumerator()
{
foreach (var queue in dict.Values)
{
foreach (var value in queue)
{
yield return value;
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
Priorities are sorted in descending order (higher value = higher priority).
Also discovered that I could just use "yield return" instead of having to write a custom Enumerator class too! Very nice. Especially since I wouldn't have known how to write it