Enumerations on PHP

Depending upon use case, I would normally use something simple like the following: abstract class DaysOfWeek { const Sunday = 0; const Monday = 1; // etc. } $today = DaysOfWeek::Sunday; However, other use cases may require more validation of constants and values. Based on the comments below about reflection, and a few other notes, …

Read more

Correct way to write line to file?

This should be as simple as: with open(‘somefile.txt’, ‘a’) as the_file: the_file.write(‘Hello\n’) From The Documentation: Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single ‘\n’ instead, on all platforms. Some useful reading: The with statement open() ‘a’ is for append, or use ‘w’ to …

Read more

How do I create a constant in Python?

You cannot declare a variable or value as constant in Python. To indicate to programmers that a variable is a constant, one usually writes it in upper case: CONST_NAME = “Name” To raise exceptions when constants are changed, see Constants in Python by Alex Martelli. Note that this is not commonly used in practice. As …

Read more

Get the name of an object’s type

Is there a JavaScript equivalent of Java’s class.getName()? No. ES2015 Update: the name of class Foo {} is Foo.name. The name of thing‘s class, regardless of thing‘s type, is thing.constructor.name. Builtin constructors in an ES2015 environment have the correct name property; for instance (2).constructor.name is “Number”. But here are various hacks that all fall down …

Read more

How to escape single quotes within single quoted strings

If you really want to use single quotes in the outermost layer, remember that you can glue both kinds of quotation. Example: alias rxvt=”urxvt -fg “”‘”‘#111111′”‘”‘ -bg ‘”‘”‘#111111′”‘” # ^^^^^ ^^^^^ ^^^^^ ^^^^ # 12345 12345 12345 1234 Explanation of how ‘”‘”‘ is interpreted as just ‘: ‘ End first quotation which uses single quotes. …

Read more

performSelector may cause a leak because its selector is unknown

Solution The compiler is warning about this for a reason. It’s very rare that this warning should simply be ignored, and it’s easy to work around. Here’s how: if (!_controller) { return; } SEL selector = NSSelectorFromString(@”someMethod”); IMP imp = [_controller methodForSelector:selector]; void (*func)(id, SEL) = (void *)imp; func(_controller, selector); Or more tersely (though hard …

Read more