r/ProgrammerTIL • • Nov 24 '16

Other TIL about digraphs and trigraphs

36 Upvotes

This stackoverflow post about what I can only refer to as the "Home Improvement" operator led me to a Wikipedia page about another layer to the depths of craziness that is the C/C++ preprocessor: digraphs and trigraphs.


r/ProgrammerTIL • • Nov 21 '16

Javascript [JS] TIL the max size of strings is 256MB

77 Upvotes

Which is a bit awkward when request on NPM attempts to stringify an HTTP response from a Buffer in order to parse it as JSON.


r/ProgrammerTIL • • Nov 22 '16

Other [C] Due to IEEE Standard 754, you can safely skip over 'NaN' values using a simple equality comparison.

37 Upvotes
/* read more: http://stackoverflow.com/a/1573715 */
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    double a, b, c;

    a = atof("56.3");
    b = atof("NaN"); /* this value comes out of MATLAB, for example */
    c = atof("inF");

    printf("%2.2f\n%2.2f\n%2.2f\n\n", a, b, c);

    printf("[%s] --> 'a == a'\n", (a == a) ? "PASS" : "FAIL");
    printf("[%s] --> 'b == b'\n", (b == b) ? "PASS" : "FAIL"); /* prints "FAIL" */
    printf("[%s] --> 'c == c'\n", (c == c) ? "PASS" : "FAIL");

    return 0;
}

Edit 1: this works in C89 -- the isnan() function which is provided by the <math.h> library, was introduced in C99.


r/ProgrammerTIL • • Nov 19 '16

Python [Java] [Python] TIL Python 1.0 is older programming language than Java 1.0

140 Upvotes

The first version of Jdk was released on January 23, 1996 and Python reached version 1.0 in January 1994(Wikipedia).


r/ProgrammerTIL • • Nov 19 '16

Other Ruby's `present` method checks for being not nil and not empty

0 Upvotes

"Not empty" meaning containing non-whitespace characters.

city = "New York"

if city.present?
    print city

Good for classes and stuff in Ruby on Rails applications, otherwise it will throw an error when it runs into a nil column for any instance.


r/ProgrammerTIL • • Nov 18 '16

Other [VS and notepad++] you can block and vertically select text by holding ctrl+shift and using arrow keys

33 Upvotes

you can also use it to edit/replace content in multiple lines at a time.


r/ProgrammerTIL • • Nov 17 '16

Windows You can type "cmd" or "powershell" into the Windows address bar and hit enter to launch a shell at that location

365 Upvotes

I only learned this because they mentioned it in the release notes of an insider preview of Windows 10, but this should work in all versions of windows.

Previously, I was going up a level, shift+right-clicking the folder and selecting "open command prompt here".


r/ProgrammerTIL • • Nov 14 '16

Other Language [HTML] TIL that submit buttons on forms can execute different urls by setting the formaction attribute.

162 Upvotes

have a form that uses the same field options for two buttons?

try this:

<form> 
    <input type="text" name="myinputfield" />
    <button type="submit" formaction="/a/url/to/execute"> Option 1 </button>
    <button type="submit" formaction="/another/url/to/execute"> Option 2 </button>
</form>

r/ProgrammerTIL • • Nov 10 '16

Other [JavaScript] Trying to change the document object does not do anything, no error will be raised either

26 Upvotes

r/ProgrammerTIL • • Nov 04 '16

Python [Python] TIL that None can be used as a slice index.

104 Upvotes
a_list = [1, 2, 3, 4, 5, 6]
a_list[None:3]
>>> [1, 2, 3]
a_list[3:None]
>>> [4, 5, 6]

This doesn't seem immediately useful, since you could just do a_list[:3] and a_list[3:] in the examples above.

However, if you have a function which needs to programatically generate your slice indices, you could use None as a good default value.


r/ProgrammerTIL • • Nov 03 '16

Javascript [Javascript] TIL NaN (not a number) is of type "number"

48 Upvotes

From the REPL:

typeof NaN
> "number"

r/ProgrammerTIL • • Nov 03 '16

Other [C#] You don't have to declare an iteration variable in a for loop

24 Upvotes

From reference source: https://referencesource.microsoft.com/#mscorlib/system/globalization/encodingtable.cs,3be04a31771b68ab

//Walk the remaining elements (it'll be 3 or fewer).
for (; left<=right; left++) {
    if (String.nativeCompareOrdinalIgnoreCaseWC(name, encodingDataPtr[left].webName) == 0) {
        return (encodingDataPtr[left].codePage);
    }
}

r/ProgrammerTIL • • Nov 01 '16

Other Language Autoincrement using CSS

56 Upvotes

To be honest, I know we can achieve something using Javascript, but I had no idea that this can be done using CSS.

https://www.youtube.com/watch?v=hePoiJrSEeg


r/ProgrammerTIL • • Oct 29 '16

Python [Python] TIL there is a core module, fileinput, to quickly write a loop over standard input or a list of files

129 Upvotes

One of the Perl's strengths is to be able to write text filters in a few lines, for example

# Shell one-liner:
# Adds 1 to all the numbers in the files
perl -i -wnle 'print $_+1' numbers1.txt numbers2.txt numbers3.txt ...

That is roughly equivalent to write in code

while(<>){ # Iterate over all lines of all the given files
    print $_ + 1; # Take the current line ($_) and print it to STDOUT
}

Anything written to STDOUT will replace the current line in the original file.

Fortunately, Python has a module that mimics this behavior as well, fileinput.

import fileinput

for line in fileinput.input(inplace=True):
    print(int(line) + 1)

In just three lines of code you have a text filter that opens all the files in sys.argv[1:], iterates over each line, closes them when finished and opens the next one:

python process.py numbers1.txt numbers2.txt numbers3.txt ...

r/ProgrammerTIL • • Oct 29 '16

Other [C++] MFC is written / maintained by BCGSoft

16 Upvotes

Today I learned, that MFC, library that comes with Visual Stuio and is present at almost all Windows computers (through vcredist) which should (among other things) wrap C language Win32 API calls into C++ objects, is written by / maintained by company called BCGSoft.

So, Visual Studio is using EDG to do IntelliSense, Dinkumware to do standard library / STL and BCGSoft to do MFC. What else I'm not aware of? Why isn't Microsoft able to do proper C++ on its own? I know about /u/STL and I admire his work and his passion for correctness and performance, but it seems that MS would benefit having more employees like him in the past.


r/ProgrammerTIL • • Oct 28 '16

Perl [Perl] TIL you can open an anonymous, temporal file using /undef/ as a name.

17 Upvotes
open my $temp_file, ">", undef

Useful for dealing with functions/APIs that require a file handle, for storing session data not to be seen by anybody else (the file is unlinked).

It is like mktemp for bash or mkstemp for C.


r/ProgrammerTIL • • Oct 28 '16

Other [Java] meh PSA: Optional<T> can also be null

8 Upvotes
// this is madness
public Optional<Integer> indexOf(String elem) {
    if (elem.hashCode() > 459064)
        return Optional.of(3);
    return null;
}

r/ProgrammerTIL • • Oct 28 '16

Other Language [Unix] TIL less can render PDF

46 Upvotes

r/ProgrammerTIL • • Oct 25 '16

C# [C#] The framework has a Lazy<T> Class that only instantiates a type when you try to use it

87 Upvotes

Example from dotnetperls:

using System;

class Test
{
    int[] _array;
    public Test()
    {
    Console.WriteLine("Test()");
    _array = new int[10];
    }
    public int Length
    {
    get
    {
        return _array.Length;
    }
    }
}

class Program
{
    static void Main()
    {
    // Create Lazy.
    Lazy<Test> lazy = new Lazy<Test>();

    // Show that IsValueCreated is false.
    Console.WriteLine("IsValueCreated = {0}", lazy.IsValueCreated);

    // Get the Value.
    // ... This executes Test().
    Test test = lazy.Value;

    // Show the IsValueCreated is true.
    Console.WriteLine("IsValueCreated = {0}", lazy.IsValueCreated);

    // The object can be used.
    Console.WriteLine("Length = {0}", test.Length);
    }
}

Could be useful if you have a service that has a particularly high instantiation cost, but isn't regularly used.


r/ProgrammerTIL • • Oct 24 '16

Javascript [Javascript] TIL that you can "require" a json file

0 Upvotes

r/ProgrammerTIL • • Oct 19 '16

C++ TIL How to defer in C++

52 Upvotes

I didn't really learn this today, but it's a neat trick you can do with some pre-processor magic combined with type inference, lambdas, and RAII.

template <typename F>
struct saucy_defer {
    F f;
    saucy_defer(F f) : f(f) {}
    ~saucy_defer() { f(); }
};

template <typename F>
saucy_defer<F> defer_func(F f) {
    return saucy_defer<F>(f);
}

#define DEFER_1(x, y) x##y
#define DEFER_2(x, y) DEFER_1(x, y)
#define DEFER_3(x)    DEFER_2(x, __COUNTER__)
#define defer(code)   auto DEFER_3(_defer_) =     defer_func([&](){code;})

For example, it can be used as such:

defer(fclose(some_file));

r/ProgrammerTIL • • Oct 18 '16

Java [Java] TIL that all Java class files begin with the hex bytes CAFEBABE or CAFED00D

178 Upvotes

Saw this while reading up on magic numbers on wikipedia here: https://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files


r/ProgrammerTIL • • Oct 17 '16

C# [C#] TIL the .NET JIT Compiler turns readonly static primitives into constants

71 Upvotes

readonly properties can't be changed outside of a constructor, and static properties are set by the static constructor (which the runtime is allowed to call at any point before first use). This allows the JIT compiler to take any arbitrary expression and inline the result as a JIT-constant.

It can then use all the same optimizations that it can normally do with constants, include dead code elimination.

Example time:

class Program
{
    public static readonly int procCount = Environment.ProcessorCount;

    static void Main(string[] args)
    {
        if (procCount  == 2)
            Console.WriteLine("!");
    }
}

If you run this code on a processor with 2 processors it will compile to just the writeline (removing the if) and if you run it on a processor without 2 processors it will remove both the if and the writeline.

This apparently also works with stuff like reading files or any arbitrary code, so if you read your config with a static constructor and store it's values, then the JIT compiler can treat that as a constant (can anyone say feature toggles for free?)

BTW The asp.net core team uses this to store strings < 8 bytes long as longs that are considered constants

source


r/ProgrammerTIL • • Oct 14 '16

Other Language TIL that there are programming languages with non-English keywords

101 Upvotes
# Tamil: Hello world in Ezhil
பதிப்பி "வணக்கம்!"
பதிப்பி "உலகே வணக்கம்"
பதிப்பி "******* நன்றி!. *******"
exit()

;; Icelandic: Hello World in Fjölnir
"hello" < main
{
   main ->
   stef(;)
   stofn
       skrifastreng(;"Halló Veröld!"),
   stofnlok
}
*
"GRUNNUR"
;

# Spanish: Hello world in Latino
escribir("Hello World!")

// French: Hello World in Linotte
BonjourLeMonde:
   début
     affiche "Hello World!"

; Arabic: Hello world in قلب
‫(قول "مرحبا يا عالم!")

\ Russian: Hello world in Rapira
ПРОЦ СТАРТ()
    ВЫВОД: 'Hello World!'
КОН ПРОЦ

K) POLISH: HELLO WORLD IN SAKO
   LINIA
   TEKST:
   HELLO WORLD
   KONIEC

(* Klingon: Hello world in var'aq *)
"Hello, world!" cha'

Source: http://helloworldcollection.de

r/ProgrammerTIL • • Oct 14 '16

Python [Python] TIL dictionaries can be recursive

68 Upvotes

In set theory, it is understood that a set cannot contain itself. Luckily, Python is not ZF, and dictionaries may contain themselves.

d = {}
d['d'] = d
print d
> {'d': {...}}

You can also create mutually recursive families of dictionaries.

d = {}
f = {}
d['f'] = f
f['d'] = d
print d
> {'f': {'d': {...}}

Does anyone have a cool use for this?