Compute sum of even powers of x I am to compute recurrently (not necessarily recursively) the y, where
$$y = {x}^{2n} + {x}^{2(n-1)} + ... + {x}^{4} + {x}^{2} + x$$

Here is what I am doing:

#include <iostream>
using namespace std;

double polynom(unsigned, double);

int main(void)
{
    cout << polynom(2, 3) << endl;
    return 0;
}

double polynom(unsigned n, double x)
{
    double currentAdd(x);
    double res(0);
    while (n)
    {
        res += currentAdd;
        currentAdd *= currentAdd;
        --n;
    }
    return res;
}

Is it possible to do it better?

Don't do this:

using namespace std;

See: Why is “using namespace std” considered bad practice?

Its a bad habits you should not get into doing (even for small programs). Bad habits bite you in the butt when you get to larger projects and forget to stop doing them.

Comments

There are a couple of things I would do differently. But I can't say you are doing them wrong.

I prefer not to use unsigned for numeric values.

double polynom(unsigned, double);

There is no way to check that what was passed was not negative. I can easily call this with:

polynom(-1, 2); // Compiler is happy to convert that -1 to a very large
                // positive number without an y errors. On the reciving
                // side you can not tell if it was an error.

There are very few times when you need the extra bit for larger positive numbers. Any time I have come across this type of case I have just used a larger integer type (not swapped to the unsigned version).

Unsigned values should be reserved for bit masks in user code.

Don't use return in main.

int main(void)
{
    return 0;
}

If you don't put a return at the end of main() then the compiler will automatically plant code to return 0. So it is not technically needed.

Additionally not using the return 0 is a way to indicate that your application can never fail. Note: return 0 indicates a success to the OS and the compiler is planting it by default to indicate successful termination.

So when I see a return 0 at the end of main() I also start to scan the rest of main() to see if there are any other returns (with non zero value) that will indicate the error conditions of the application.

Initialization

This is fine.

    double currentAdd(x);
    double res(0);

But personally I think the = sign provides more context.

    double currentAdd = x;
    double res        = 0;

Prefer for() over while()

This is so 50/50. Its just that for() loops can be slightly more compact.

    while (n)
    {
        --n;
    }
    // over
    for(;n; --n)
    {
    }

Would not worry too much about it though.


Encapsulating common Try-Catch code. Is this a known pattern? Is it good or bad? In an effort to reduce code duplication, I often use and have used this style to capture handling of exceptions on a boundary of an application:
Given the following extension methods:

public static class FuncExtenstion
{
    [DebuggerStepThrough]
    public static Action<A> AsAction<A, T>(this Func<A, T> f)
    {
        return (a) => f(a);
    }

    [DebuggerStepThrough]
    public static Func<bool> AsFunc(this Action a)
    {
        return () => { a(); return true; };
    }
}

public static class IlogExtensions
{
    public static TResult TryCatchLogThrow<TResult>(this ILog logger, Func<TResult> f)
    {
        try
        {
            return f();
        }
        catch (Exception ex)
        {
            logger.Error(ex.Message, ex);
            throw;
        }
    }

    public static void TryCatchLogThrow(this ILog logger, Action f)
    {
        logger.TryCatchLogThrow(f.AsFunc());
    }

    public static TResult TryCatchLog<TResult>(this ILog logger, Func<TResult> f)
    {
        try
        {
            return f();
        }
        catch (Exception ex)
        {
            logger.Error(ex.Message, ex);
            return default(TResult);
        }
    }

    public static void TryCatchLog(this ILog logger, Action f)
    {
        logger.TryCatchLog(f.AsFunc());
    }
}

In the code I will use these (e.g. in a Windows/WCF/Web Service) to either silently catch the error and let the code continue to run (used in a polling service) or to at least log the error locally on the server and then rethrow the full exception again.
I have used several other variations where the exception gets wrapped in more 'user friendly' exceptions or in WCF FaultExceptions

So typically this code is used as follows:

    Response ISomeService.SomeOperation(Request request)
    {
        return _logger.TryCatchLogThrow(() => _domainImplementation.SomeOperation(request));
    }

    OtherResponse ISomeService.OtherOperation(OtherRequest request)
    {
        return _logger.TryCatchLogThrow(() => _domainImplementation.OtherOperation(request));
    }

I have not seen this style of code anywhere else. So I was wondering if there is an other pattern I should be using, or if this is ok to use.

This looks like the Execute Around pattern in its static syntax. A thunk is passed around, and then invoked at the appropriate moment.

The intent is however a bit different. In true execute around, the is something done before and something done after a certain action/function/block. Catching exceptions "feels" a bit different.


Python Rabin-Karp Code Optimization Here's the Rabin-Karp implementation that I've written in Python:
from functools import lru_cache
from itertools import islice
from typing import List, Optional

BASE = 139
MOD = 2 ** 31 - 1

@lru_cache(maxsize=None)
def char_to_int(c: str) -> int:
    return ord(c) + 1

def calculate_hash(s: str, length: Optional[int] = None) -> int:
    ret_hash = 0
    if length is not None:
        s = islice(s, 0, length)
    power = len(s) - 1 if length is None else length - 1
    for i, c in enumerate(s):
        ret_hash += char_to_int(c) * BASE ** power
        power -= 1
    return ret_hash % MOD

def roll_hash(prev_hash: int, prev_char: int, next_char: str, length: int) -> int:
    new_hash = ((prev_hash - char_to_int(prev_char) * BASE ** (length - 1)) * BASE) % MOD
    new_hash += char_to_int(next_char)
    return new_hash % MOD

def rabin_karp(text: str, pattern: str) -> List[int]:
    """
    Returns a list of indices where each entry corresponds to the starting index of a
    substring of `text` that exactly matches `pattern`
    """
    p_hash = calculate_hash(pattern)
    n = len(pattern)
    curr_hash = calculate_hash(text, n)
    indices = []
    if p_hash == curr_hash:
        indices.append(0)
    for i in range(1, len(text) - n + 1):
        curr_hash = roll_hash(
            curr_hash, text[i - 1], text[i + n - 1], n
        )
        if p_hash == curr_hash:
            indices.append(i)
    return indices

if __name__ == "__main__":
    with open("lorem_ipsum.txt", "r") as f:
        text = f.read()
    pattern = "lorem"
    indices = rabin_karp(text, pattern)
    print(f"indices: {indices}")

I'm trying to optimize the code as much as possible, so I've tried to do some dynamic code analysis to better understand bottlenecks. I used cProfile to understand the function calls and made changes to the code accordingly to arrive at the above code. Here is the final output from cProfile:
Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    60301    0.091    0.000    0.091    0.000 rabin_karp.py:25(roll_hash)
        1    0.035    0.035    0.126    0.126 rabin_karp.py:30(rabin_karp)
       42    0.000    0.000    0.000    0.000 rabin_karp.py:11(char_to_int)
        2    0.000    0.000    0.000    0.000 rabin_karp.py:15(calculate_hash)
       57    0.000    0.000    0.000    0.000 {method 'append' of 'list' objects}
       42    0.000    0.000    0.000    0.000 {built-in method builtins.ord}
        3    0.000    0.000    0.000    0.000 {built-in method builtins.len}

Are there any other ways I could further optimize the code? Another interesting thing of note is that adding @lru_cache actually increases execution time as measured by timeit despite the caching mechanism reducing the number of functions calls to char_to_int() (from 120612 to 42).

Disclaimer: I did not get any noticeable performance improvements but here are a few ideas nonetheless. Also, your code looks really good to me and there is not much to improve.
In calculate_hash, you compute a power in the body of the loop. Based on the way the exponents is computed, we can tell that the different values will be: BASE ** (length - 1), BASE ** (length - 2), etc. A different option could be to compute the initial value with the '**' and then update the power using division by BASE.
We could get something like:
def calculate_hash(s: str, length: Optional[int] = None) -> int:
    if length is not None:
        s = islice(s, 0, length)
    else:
        length = len(s)
    power = BASE ** (length - 1)
    ret_hash = 0
    for c in s:
        ret_hash += char_to_int(c) * power
        power /= BASE
    return ret_hash % MOD

In roll_hash, the computation is split across different lines as the first line is getting too big. In order to keep the expressions easier to read, it may be useful to define additional local variables such as: prev_int, next_int = char_to_int(prev_char), char_to_int(next_char).
Then, a few things can be spotted:

we compute m = (val1 % MOD) and then (m + val2) % MOD: we could perform the modulo operation just once
the ((prev_hash - char_to_int(prev_char) * BASE ** (length - 1)) * BASE) expression can be slightly simplified by expanding it, we get: prev_hash * BASE - char_to_int(prev_char) * BASE ** length. It is much easier to read and should be just as efficient (if not more).

At the end, the whole function becomes:
def roll_hash(prev_hash: int, prev_char: int, next_char: str, length: int) -> int:
    prev_int, next_int = char_to_int(prev_char), char_to_int(next_char)
    return (next_int + prev_hash * BASE - prev_int * BASE ** length) % MOD

As mentionned in the comment, the power operation is quite expensive. Maybe we could try to compute it just once and provide it to the roll_hash function.
Also, we could try to take this chance to use an unknown part of the pow builtin: the mod parameter. Here, we may as well compute BASE ** length % MOD so that we get to handle smaller values later on (this is an improvements when the length of the pattern is bigger than 4).
At this stage, we get:
def roll_hash(prev_hash: int, prev_char: int, next_char: str, base_pow_length: int) -> int:
    prev_int, next_int = char_to_int(prev_char), char_to_int(next_char)
    return (next_int + prev_hash * BASE - prev_int * base_pow_length) % MOD

def rabin_karp(text: str, pattern: str) -> List[int]:
    """
    Returns a list of indices where each entry corresponds to the starting index of a
    substring of `text` that exactly matches `pattern`
    """
    p_hash = calculate_hash(pattern)
    n = len(pattern)
    curr_hash = calculate_hash(text, n)
    indices = []
    if p_hash == curr_hash:
        indices.append(0)
    base_pow_length = pow(BASE, n, MOD)
    for i in range(1, len(text) - n + 1):
        curr_hash = roll_hash(
            curr_hash, text[i - 1], text[i + n - 1], base_pow_length
        )
        if p_hash == curr_hash:
            indices.append(i)
    return indices


a Python2 to Python3 print fixer in perl Sometimes, I'm reviewing old questions written in Python2, with no parenthesis around print statements. Or I'm changing one of my older codes, also without parenthesis around print statements.

It annoys me to do this manually, so I decided to write a little perl script to change it for me, however it looks rather ugly. And I think I'm missing some obvious regex to do this?

I don't yet write to another file, but just print to the commandline.

Note that I'm making the assumption that lines that print and are net yet ended, end with \

use strict;
use warnings;

my @filenames = @ARGV;

foreach my $filename (@filenames){
    my $print_ended = 0;
    my $concat_print = qw{};
    open my $fh, '<', $filename or die "Can't open $filename: $!";

    while (my $line = <$fh>) {

        chomp $line;
        if ($print_ended) {
            $concat_print .= $line;
            $print_ended = $line =~ /\\$/;

            if (! $print_ended) {
                (my $newline = $concat_print) =~ s/print /print(/;
                 print $newline . ")\n";
                 $concat_print = qw{};
            }
        }
        elsif ($line =~ /print /) {
            if ($line =~ /\\$/) {
                $print_ended = 1;
                $concat_print .= $line . "\n";
            }
            else {
                (my $newline = $line) =~ s/print /print(/;
                print $newline . ")\n";
            }
        }
        else {
            print $line . "\n";
        }
    }
}

\h matches horizontal white spaces

/x modifier instructs regex to ignore white spaces (readability)

/m modifier instructs ^ $ anchors to match begin/end of line, instead of string!

local $/; # read all text at once

while (my $line = <>) {
    $line =~ s/print \s+ (.+? (?: [^\\]\h*$ ) )/print($1)/xgsm;
    print $line;
}


Creating circles at the mouse cursor This code takes the position of your mouse cursor, and it creates circles where the cursor is.

 strokeWeight(3);
 stroke(24, 0, 0);
 fill(245, 0, 0);
 background(255, 255, 255);
    draw = function() {
        ellipse(mouseX, mouseY, 30, 30)
    };

I would like to know:

If there is a way to shorten this code, but still keep it readable.
Or any suggestions to make it better.

You can see a live demo here.

There's basically nothing to shorten here. Processing.js is already doing the heavy-lifting of setting up a canvas so you can draw, hooking up to the DOM, etc. etc., leaving you do focus on the task. And that task is:

draw a circle where the cursor is
make it red
with a dark border
that's 3px thick
on a white background

which is what your code does. Almost line for line (just backwards, kinda). So there's nothing to shorten.

Well, I guess you can reduce background(255, 255, 255); to background(255); since Processing will automatically assume you mean that 255 should be used for all three. But that's just a minor shortcut built into Processing.

But really, why shorten it? Short code is not a goal in itself*. Efficient code is a goal, but code length and efficiency are not the same thing. Sure, code can be inefficient and long - typically, that's how it works out (e.g. the code takes an overly complicated route to accomplish its task). But it can also be inefficient and short. Or long but very efficient.

Point is, you have to know what metric you're interested in. Maybe it's memory usage, maybe it's speed, maybe it's safety, or extensibility. Hopefully, it's also readability. Short code, in and of itself, doesn't automatically impact these.

Sidenote: Since JavaScript is almost always part of a web page, and thus sent over the internet, it is actually worth making it short, since it'll take less space, and thus download faster. But even that's only really interesting if you have thousands of lines of code. Those few lines above probably take less time to transmit than it takes to even establish the connection they're sent through.

But even if you have a ton of code, you'd use a minifier to make your JavaScript more compact after you've written it. You'd still work on the regular, readable code, and then let the minifier compress it into highly compact but humanly-unreadable gibberish.

For an example, go to google.com and view source - a lot of that nonsense is heavily optimized and minified javascript. But nobody wrote it like that. For another example, look at Processing.js itself: Here is the code pretty much as it was written (though there was probably a lot of tooling involved in piecing it together), and here's the minified version that a computer spat out.

Anyway, there's nothing in you code to shorten, but there is something that can be made more efficient. And in this case, that means more code:

strokeWeight(3);
stroke(24, 0, 0);
fill(245, 0, 0);
background(255, 255, 255);
noLoop();

mouseMoved = function() {
    ellipse(mouseX, mouseY, 30, 30);
};

You were drawing the circle in the draw function. That function runs many times a second. But if the mouse hasn't moved, why bother drawing another circle in the same place? Using draw is great for animation and stuff like that, where things are always changing. But here, nothing changes if the mouse doesn't move.

Also, if you run your code, but the mouse isn't anywhere near the canvas, it'll just endless draw circles at 0,0 - i.e. top left. It doesn't know where the mouse is, so it just defaults to zero, zero.

Hence, the code above calls noLoop() - which means that draw isn't being called constantly and pointlessly - and instead does its drawing in mouseMoved. So if you don't move the mouse, nothing happens. It only springs into action if the mouse coordinates change - that's when it has to draw a new circle.

Here it is in action.

*) Unless you're playing code golf for fun


Converting an Excel range into an array I'm iterating through a list of possible values that reside in a named range on a worksheet. Since accessing ranges is slow, I wanted an easy way to convert them to an array and came up with the function below that does so. Is there a better way of setting my code up?

Public Function ConvertRangeIntoArray(ByVal convertRange As Range) As String()
    Dim temporaryVariant As Variant
    Dim is2DArray As Boolean
    Select Case True
        Case convertRange.Rows.Count = 1
            temporaryVariant = Application.WorksheetFunction.Transpose(Application.WorksheetFunction.Transpose(convertRange))
        Case convertRange.columns.Count = 1
            temporaryVariant = Application.WorksheetFunction.Transpose(convertRange)
        Case Else
            temporaryVariant = convertRange
            is2DArray = True
    End Select

    Dim returnValue() As String
    Dim rw As Long
    Dim cl As Long
    If is2DArray Then
        ReDim returnValue(LBound(temporaryVariant) To UBound(temporaryVariant), LBound(temporaryVariant, 2) To UBound(temporaryVariant, 2))
        For rw = LBound(temporaryVariant) To UBound(temporaryVariant)
            For cl = LBound(temporaryVariant, 2) To UBound(temporaryVariant, 2)
                returnValue(rw, cl) = CStr(temporaryVariant(rw, cl))
            Next
        Next
    Else
        ReDim returnValue(LBound(temporaryVariant) To UBound(temporaryVariant))
        For cl = LBound(temporaryVariant) To UBound(temporaryVariant)
            returnValue(cl) = CStr(temporaryVariant(cl))
        Next
    End If

    ConvertRangeIntoArray = returnValue
End Function

Kudos for explicit Public and the ByVal parameter. I wouldn't make it return a String() array though.

You can't know that every value in the source Range can be converted to a String.

returnValue(cl) = CStr(temporaryVariant(cl))

This instruction will make your function fail if the convertRange contains any Error value. You need to first verify whether IsError(temporaryVariant(cl)) before you can attempt any safe type conversion.

But then, what would you do with a value that can't be converted? Remove it from the results? Return an empty string?

What if the range is all numeric values, that the calling code needs to add up; there's some serious overhead going on with iterating both dimensions of a 2D array to convert everything to a String, and then doing the same thing again to convert strings back to Double for proper calculations.

IMO that's one of the cases where you're better off just returning a Variant. That significantly cuts down the implementation:

Public Function ToArray(ByVal target As Range) As Variant
    Select Case True
        Case target.Rows.Count = 1
            'horizontal 1D range
            ToArray = Application.WorksheetFunction.Transpose(Application.WorksheetFunction.Transpose(target)).Value
        Case target.columns.Count = 1
            'vertical 1D range
            ToArray = Application.WorksheetFunction.Transpose(target).Value
        Case Else
            '2D array: let Excel to the conversion itself
            ToArray = target.Value
    End Select
End Function

Note I renamed the function to a more straightforward ToArray which lets the argument speak for itself, and renamed convertRange to the more idiomatic (it comes up a lot in worksheet event handlers) target (it's also a noun, which is more appropriate than something that looks like a verb for naming a variable).

The caller now has access to the actual types - with everything it means: if a value's type IsError, then the caller needs to deal with it accordingly. If a value IsNumeric, then the caller can perform arithmetic operations on it without incurring implicit type conversions (aside from unwrapping the value from the Variant). If the value IsDate, then the caller can work with dates without ever having to deal with how VBA might be representing that date value in a String.

And performance-wise, it's now as fast as it's going to get (pretty much instant), regardless of the size of the returned array.

I'm not too fond of Select Case True. Case conditions are still going to be evaluated sequentially until one matches, so at the end of the day it's not much different from a more conventional construct:

Public Function ToArray(ByVal target As Range) As Variant
    If target.Rows.Count = 1 Then
        'horizontal 1D range
        ToArray = Application.WorksheetFunction.Transpose(Application.WorksheetFunction.Transpose(target.Value))
    ElseIf target.columns.Count = 1 Then
        'vertical 1D range
        ToArray = Application.WorksheetFunction.Transpose(target.Value)
    Else
        '2D array: let Excel to the conversion itself
        ToArray = target.Value
    End If
End Function

...which removes an indentation level, and puts the conditions where we'd normally expect them. We're also explicitly assigning to the .Value of the range, transposed or not, instead of implicitly pulling the ranges' default member.


Extracting specific words from PANDAS dataframe I'm new to data analysis and doing some online training. I have a task to extract specific words from specific column in data frame, then count those words and then just to do some min/max/mean ant etc... I didn't find specific any method for that in Pandas so I have tried to create function for that. I have done this so far:
import re
import string

def countWords(data_frame, selected_words):
    words_dict = {}

    for sentence in data_frame:
        remove = string.punctuation
        remove = remove.replace("'", "") # don't remove hyphens
        pattern = r"[{}]".format(remove) # create the pattern

        test = re.sub(pattern, "", str(sentence)) #compile

        splited_words = str(test).split(' ')

        for word in splited_words:
            word = word.strip()
            word = word.lower()
            if word in selected_words:
                if word not in words_dict:
                    words_dict[word] = 1
                else:
                    words_dict[word] += 1
    return words_dict

It works as expected, but the performance is not as I expected. What could be done better in this code to improve performance?
It takes roughly ~5s to perform for 15257065 words in 183531 sentences.
Sample input
selected_words = ['awesome', 'great', 'fantastic', 'amazing', 'love', 'horrible', 'bad', 'terrible', 'awful', 'wow', 'hate']
data_frame = 'These flannel wipes are OK, but in my opinion not worth keeping. I also ordered someImse Vimse Cloth Wipes-Ocean Blue-12 countwhich are larger, had a nicer, softer texture and just seemed higher quality. I use cloth wipes for hands and faces and have been usingThirsties 6 Pack Fab Wipes, Boyfor about 8 months now and need to replace them because they are starting to get rough and have had stink issues for a while that stripping no longer handles.'

If you're dealing with a lot of data, and especially if your data fits in a dataframe, you should use dataframe methods as much as possible.

Your sample data is not a dataframe, but since you specifically mentioned Pandas and dataframes in your post, lets assume that your data is in a dataframe. Using Pandas' str methods for pre-processing will be much faster than looping over each sentence and processing them individually, as Pandas utilizes a vectorized implementation in C.

Also, since you're trying to count word occurrences, you can use Python's counter object, which is designed specifically for, wait for it, counting things.

The current code:

def countWords(data_frame, selected_words):
    words_dict = {}

    for sentence in data_frame:
        remove = string.punctuation
        remove = remove.replace("'", "") # don't remove hyphens
        pattern = r"[{}]".format(remove) # create the pattern

        test = re.sub(pattern, "", str(sentence)) #compile

        splited_words = str(test).split(' ')

        for word in splited_words:
            word = word.strip()
            word = word.lower()

could be reduced to something like:

def count_words(df, selected_words):
    ...
    df.sentences = df.sentences.replace(r"[{}]".format(string.punctuation.replace("'","")),"")
    df.sentences = df.sentences.str.strip().str.lower().str.split()
    for sentence in df.sentences:
       ...

Then if you were to use a Counter, you could filter and update the Counter in 1 line using a generator expression.

from collections import Counter

def count_words(df, selected_words):
    words_count = Counter()

    ...

    for sentence in df.sentences:
        words_count.update(x for x in sentence if x in selected_words)

Alternatively, if you are going to be searching for different word groups, you could count all the words and filter afterwards.

One more thing to note is that selected words in the sample input is a list. However, searching over a list will normally require O(n) time. In this case, searching over m sentences, it would then take n*m time. This can be improved by changing the list to a set, which has O(1) lookup, therefore reducing the time complexity of the search to just O(m).

This can be even further improved if you have the physical memory for it, by skipping the for loop and the counter and doing the entire thing in Pandas. Pandas' str.split function takes a parameter, expand, that splits the str into columns in the dataframe. When combined with .stack(), this results in a single column of all the words that occur in all the sentences.

The column can then be masked to filter for just the selected words, and counted with Pandas' series.value_counts() function, like so:

words = df.sentences.str.split(expand=True).stack()
words = words[words.isin(selected_words)]
return words.value_counts()

In fact, it would probably be faster to skip all the for loops altogether and implement it like this, as vectorized implementations will be much faster than loops. If you don't have enough memory for this, you can process it in chunks and it should still be faster than using for loops.


A Simple Cache class “There are only two hard things in Computer Science: cache
  invalidation and naming things.” -- Phil Karlton

That being said, I created this SimpleCache class which I intend to use to cache database queries and results over a relatively short period of time.

I'm just asking if there are any immediate faults or errors with this?

(The class is internal because I'm using it inline in another class)

internal sealed class SimpleCache
{
    private static Dictionary<string, CacheItem> _cache = new Dictionary<string, CacheItem>();

    public void Add(string key, object value)
    {
        _cache.Add(key, new CacheItem() { Value = value, Created = DateTime.Now.Ticks });
    }

    public object this[string key]
    {
        get
        {
            if(_cache.ContainsKey(key))
            {
                if ((_cache[key].Created + 30000) > DateTime.Now.Ticks) //30000 was chosen by magic
                {
                    return _cache[key].Value;
                }
                    _cache.Remove(key);
            }
            return null;
        }
    }

    internal sealed class CacheItem
    {
        public object Value { get; set; }
        public long Created { get; set; }
    }
}

You have a static dictionary as backing store which means that all cache instances share it. Not saying that this is wrong and it might be intended but you should be aware of it.
Your cache apparently is not thread-safe. You need to protect access to the dictionary with locks or if you are using .NET 4 or later use ConcurrentDictionary. If you make the backing dictionary non-static then you might not need to make it thread-safe if you can ensure that you never access the same cache instance from multiple threads at the same time.
Items only get evicted when they are being accessed again. This means if you only ever access items once they will stay in there forever.
Make the magic number 30000 at least a const member or maybe even a tunable property/field (in which case you should prefer making it a TimeSpan as it's easier to use than plain ticks)
Your Add method will throw an exception if the entry in the cache already exists. You either need to check if it exists and just update the entry (or do nothing, whatever makes sense) or replace the entry by using _cache[key] = .. rather than _cache.Add().
Depending on your use case you might want to rename Created into LastAccessed and update it whenever someone accesses the entry (read/write) with the same key (which means items will be evicted a certain period after they have been last accessed rather than created).
Last but not least you might want to look into the MemoryCache class if you are using .NET 4 or later.


LRU Cache with a static variable for garbage value I have tried to implement a Least Recently Used cache with only C++ STL containers. The main thing that I keep asking my self the static variable called garbage_val. Is it a good practice to have such a static variable just for garbage values?

template<typename Key, typename Value>
class LRU_Cache
{
struct Node
{
    Key k;
    Value v;
};

public:
static Value garbage_val;

LRU_Cache(unsigned int capacity)
{
    capacity_ = capacity;
}

Value get(Key key)
{
    auto node = cache_.find(key);

    if(node == cache_.end())
    {
        return garbage_val;
    }

    Value val = (*(node->second)).v;
    recentlyList_.erase(node->second);

    Node n; n.v = val; n.k = key;

    recentlyList_.push_back(n);
    cache_[key] = --recentlyList_.end();

    return val;
}

void set(Key key, Value val)
{
    auto node = cache_.find(key);

    if(node != cache_.end())
    {
        recentlyList_.erase(node->second);
    }
    else
    {
        evict_if_needed();
    }

    Node n; n.v = val; n.k = key;
    recentlyList_.push_back(n);
    cache_[key] = --recentlyList_.end();
}

void evict_if_needed()
{
    if(cache_.size() >= capacity_)
    {
        auto node = cache_.find(recentlyList_.begin()->k);
        recentlyList_.pop_front();
        cache_.erase(node);
    }
}

virtual ~LRU_Cache(void)
{
}

void print()
{
    std::cout << "Objects in Memory:" << std::endl;
    for(auto& c : cache_)
    {
        std::cout << "(" << c.first << "," << (*(c.second)).v << ")" << std::endl;
    }

    std::cout << "Recently used:" << std::endl;
    for(auto& r : recentlyList_)
    {
        std::cout << "(" << r.k << "," << r.v << ")" << std::endl;
    }
}
private:
LRU_Cache(void){}

std::unordered_map<Key, typename std::list<Node>::iterator> cache_;
std::list<Node> recentlyList_;
unsigned int capacity_;
};
template<typename Key,typename Value> Value LRU_Cache<Key,Value> ::garbage_val;

Is it a good practice to have such a static variable just for garbage values?

Maybe not:

garbage_val is a Value, so if you return it, then the caller doesn't know whether the get succeeded.
If garbage_val is supposed to be a magic number (an impossible Value), different users of the class might want different magic numbers ... so why isn't garbage_val an instance member instead of a static member?
Normally container classes expect the caller to check that iterator != end() before dereferencing the iterator.

Instead, the following methods might be appropriate:

// throws an exception if key does exist.
Value get(Key key) { ... }
// tests whether key exists: use this before calling get.
bool contains(Key key) { ... }
// return true and initializes value iff key exists.
// if key doesn't exist then valueOut is not initialized.
bool tryGet(Key key, Value& valueOut) { ... }


Grouping elements in array by multiple properties During work, I was given this task: to group elements with similar properties in the array.

In general, the problem is as follows:

var list = [
    {name: "1", lastname: "foo1", age: "16"},
    {name: "2", lastname: "foo", age: "13"},
    {name: "3", lastname: "foo1", age: "11"},
    {name: "4", lastname: "foo", age: "11"},
    {name: "5", lastname: "foo1", age: "16"},
    {name: "6", lastname: "foo", age: "16"},
    {name: "7", lastname: "foo1", age: "13"},
    {name: "8", lastname: "foo1", age: "16"},
    {name: "9", lastname: "foo", age: "13"},
    {name: "0", lastname: "foo", age: "16"}
];

If I group this elements by lastname and age, I will get this result:

var result = [
    [
        {name: "1", lastname: "foo1", age: "16"},
        {name: "5", lastname: "foo1", age: "16"},
        {name: "8", lastname: "foo1", age: "16"}
    ],
    [
        {name: "2", lastname: "foo", age: "13"},
        {name: "9", lastname: "foo", age: "13"}
    ],
    [
        {name: "3", lastname: "foo1", age: "11"}
    ],
    [
        {name: "4", lastname: "foo", age: "11"}
    ],
    [
        {name: "6", lastname: "foo", age: "16"},
        {name: "0", lastname: "foo", age: "16"}
    ],
    [
        {name: "7", lastname: "foo1", age: "13"}
    ]
];

After some experimentation, I came to the following solution:

    Array.prototype.groupByProperties = function(properties){
        var arr = this;
        var groups = [];
        for(var i = 0, len = arr.length; i<len; i+=1){
            var obj = arr[i];
            if(groups.length == 0){
                groups.push([obj]);
            }
            else{
                var equalGroup = false;
                for(var a = 0, glen = groups.length; a<glen;a+=1){
                    var group = groups[a];
                    var equal = true;
                    var firstElement = group[0];
                    properties.forEach(function(property){

                        if(firstElement[property] !== obj[property]){
                            equal = false;
                        }

                    });
                    if(equal){
                        equalGroup = group;
                    }
                }
                if(equalGroup){
                    equalGroup.push(obj);
                }
                else {
                    groups.push([obj]);
                }
            }
        }
        return groups;
    };

This solution works, but is this a right and best way? It still looks a little ugly to me.

I felt compelled to write that you probably should combine forEach and map with the answer of Alexey Lebedev.

function groupBy( array , f )
{
  var groups = {};
  array.forEach( function( o )
  {
    var group = JSON.stringify( f(o) );
    groups[group] = groups[group] || [];
    groups[group].push( o );
  });
  return Object.keys(groups).map( function( group )
  {
    return groups[group];
  })
}

var result = groupBy(list, function(item)
{
  return [item.lastname, item.age];
});


Laravel time-punching database structure I am trying to build a database structure for a time punching system. What I'm trying to figure out is if what I have is the ideal structure, or if something else exists that I'm overlooking.

I want the records to be connected in some way so that I can pull out all of the records into a table and display them by date and time.

Here is my migration table:

Schema::create('punches', function(Blueprint $t)
        {
            $t->increments('id');
            $t->integer('user_id');
            $t->dateTime('time');
            $t->boolean('in_punch');
            $t->timestamps();
        });

I want to be able to have the in punch and the out punch connected, so I don't feel like this is the best way to go about doing it, but I can't come up with anything better. Can you?

I'm assuming what you want, ultimately, is show a list of all tuples (user, punch_in_time, punch_out_time). If so, the schema you showed does work, though the query would be ugly. One answer might be to have two tables:

ActivePunches(user_id, punch_in_time)

and

CompletedPunches(user_id, punch_in_time, punch_out_time)

When a user who isn't in the active list punches in, you add them to ActivePunches. When an active user punches out, you delete their active record and move it to completed. All other state transitions are illegal. You could also collapse these two into a single table (with an extra state column), but the nature of the problem indicates you might want to keep records for a long time, in which case you want to avoid reading a huge index, so this separation gives you a bit of a performance gain.


Spreadsheet generated through Google Drive file iteration I put together a script which goes through all of the files in Google Drive, and writes a spreadsheet with all of the files with their name, containing folder, URL, and date last updated.

function Start_Up() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getActiveSheet();
  sheet.clear();
  sheet.appendRow(['Name', 'Folder', 'URL', 'Updated'])

  var start_time = new Date();
    MailApp.sendEmail({
      to: 'insert e-mail',
      subject: "Master File Update - Started",
      htmlBody: "The update of the master equipment document spreadsheet was started at: " + start_time});

  var Script_Properties = PropertiesService.getScriptProperties();
  Script_Properties.deleteAllProperties();
  Iterate_Files();
}

function Delete_Triggers() {
  var Triggers = ScriptApp.getProjectTriggers();
  for (var i = 0; i < Triggers.length; i++) {
    ScriptApp.deleteTrigger(Triggers[i]);
  }
}

function Iterate_Files() {
  var Script_Properties = PropertiesService.getScriptProperties();
  var continuationToken = Script_Properties.getProperty('C_Token');

  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getActiveSheet();

  Delete_Triggers();

  var Start_Time = new Date().getTime();
  var Seconds = 0;

  if (continuationToken) {
    var files = DriveApp.continueFileIterator(continuationToken);
  } else {
    var files = DriveApp.getFiles();
  }

  var output = [];

  while (files.hasNext() && Seconds < 240) {
    var file = files.next();
    var Current_Time = new Date().getTime();
    var Seconds = Math.floor((Current_Time - Start_Time)/1000);

    var file_name = file.getName();
    if (file.getParents().hasNext()) {
      var folder_name = file.getParents().next().getName();
    } else {
      folder_name = 'Root';
    }
    var file_url = file.getUrl();
    var file_last_updated = file.getLastUpdated();
    output.push([file_name, folder_name , file_url, file_last_updated]);
  }
  if (output.length) {
    var last_row = sheet.getLastRow();
    sheet.getRange(last_row +1, 1, output.length, 4).setValues(output);
  }

  if (files.hasNext()) {
    var triggerID = null;
    continuationToken = files.getContinuationToken();
    Script_Properties.setProperty('C_Token', continuationToken);
    ScriptApp.newTrigger('Iterate_Files')
    .timeBased()
    .after(1 * 60 * 1000)
    .create();
  } else {
    Script_Properties.deleteAllProperties();
    var end_time = new Date();
    MailApp.sendEmail({
      to: 'insert email',
      subject: "Master File Update - Complete",
      htmlBody: "The update of the master equipment document spreadsheet was completed at: " + end_time});

    ScriptApp.newTrigger('Start_Up')
    .timeBased()
    .everyDays(1)
    .atHour(0)
    .create();
  }
}

It currently runs through 50,000+ files in a large number of folders and I am hoping that some of you may see areas which I may be able to improve performance in order to reduce run time.

** The sheet does not necessarily need to be cleared and re-created as long as there is a viable method of tracking which files have been indexed previously.

Tracking Previously Indexed Files

From my tests it appears that DriveApp.getFiles() returns the files in the order that they were last modified. This is not guaranteed in the Google Scripts specifications; however, this information could be used to drastically speed up your script. Just a few things need to be considered.

Storing the last time the script was run

You could store the time you last ran the script as a ScriptProperty, which you could get right before you delete them all at the start. Then you could iterate through the files until you find one with a file_last_updated date prior to when you last ran the script.

while (files.hasNext() && Seconds < 240) {
  var file = files.next();

  var file_last_updated = file.getLastUpdated();

  if (file_last_updated > Last_Time_Script_Was_Run) {
    // find file and update it
    // if not found then add new one
  }
}

Permanently deleted files

Another thing to note is that if you only check the most recently modified files your script will never notice when a file has been permanently deleted. The only way files are permanently deleted is when they are deleted from the trash (or by an authorized script). You could keep track of these by occassionally rechecking every single file in your drive, or by only permanently deleting files with a separate script that updates your sheet of drive files. Look into this SO question: Permenantly Deleting Files for more info.

Updating files on the sheet

You'll need to add the file id to your spreadsheet so that the script will be able to find the file data it needs to update. Array lookup may be too slow since you have so many files; you could use an object to map the file id to its index. But try both to be sure.

function Start_Up() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getActiveSheet();
  var fileData = sheet.getDataRange().getValues();

  fileData.shift(); // remove header row
  // say ID is the 4th index

  var indexMap = {};
  for (var i = 0; i < fileData.length; i++) {
    indexMap[fileData[i][4]] = i; // map the id to the index
  }

  Iterate_Files(fileData, indexMap);
}

function Iterate_Files(fileData, indexMap) {
  // ...

  // when updating a file
  var id = file.getId();

  if (indexMap[id] === undefined) { // add new file
    fileData.push([...]);
  }
  else { // update existing file
    fileData[indexMap[id]] = [...];
  }

  // ...
}

Minor optimizations

You can eke out a little extra performance by changing how you check the time. I got a 10 second speed up checking ~1200 files by doing the following.

var file,
    file_name,
    folder_name,
    file_url,
    file_last_updated;

while (files.hasNext() && Date.now() - Start_Time < 240000) {
  file = files.next();

  file_name = file.getName();
  if (file.getParents().hasNext()) {
    folder_name = file.getParents().next().getName();
  } else {
    folder_name = 'Root';
  }
  file_url = file.getUrl();
  file_last_updated = file.getLastUpdated();
  output.push([file_name, folder_name , file_url, file_last_updated]);
}


Mastermind game - Evaluating the guess in Ruby I am a novice coder and I am very new to algorithms. Something about my code leads me to believe that it is unnecessarily verbose and/or inefficient. I am building a command line Mastermind game, and part of the project is to provide feedback for a user's guess. In the game, the codemaker creates a secret code with four "pegs" of any of the six predefined colors.

The codebreaker has 12 chances to guess the correct code while gradually improving their guess with the help of feedback from the codemaker each time. The feedback consists of four "key pegs", which must be either black or white.

The codemaker puts down a black peg to indicate that the player chose the correct position and the correct color. A white key peg indicates that the user selected a color that exists in the secret code but is in the wrong position.

However, only one white peg is put down for each correct color guess, even if there is many of that color in the secret code.

For example, if:

secret_code = ["Red", "Blue", "Green", "Red"]
guess = ["Blue", "Green", "Red", "Red"],
#=> feedback is ["White, "White", "Black", "White"] in any order

Here is another example:

secret_code = ["Red", "Blue", "Red", "Red"]
guess = ["Blue", "Red", "Green", "Green"]

p computer.provide_feedback(secret_code, guess)
#=> ["White", "White", " ", " "]

The first step of my code is to turn the two arrays into hashes with the colors as values and an array of their indices as the values. This way I can compare the frequency and position of each color in each array.

The next step is to iterate through the guess hash, and for each iteration create an intersection array that contains the elements that exist in both. The number of intersected elements determines the number of black pegs to be placed into the feedback array.

To find the number of white pegs,  the program checks if the array for the color indices in the guess array is less in size than the secret_code indices to avoid counting more of that color than is in the secret_code. Then the program finds the number of elements left over that aren't intersected, and that determines the number of white pegs.

Here is the code for this specific portion of my game:

def provide_feedback(secret_code, guess)
  secret_indices = hash_of_indices(secret_code)
  guess_indices = hash_of_indices(guess)
  feedback = format_feedback(calculate_feedback(secret_indices, guess_indices))
  feedback
end

def hash_of_indices(array)
  array.each_with_index.inject(Hash.new {Array.new}) do |hash, (elem, i)|
    hash[elem] += [i]
    hash
  end
end

def calculate_feedback(secret_hash, guess_hash)
  feedback = []
  black = "Black"
  white = "White"
  guess_hash.each do |k, v|
    intersection = (v & secret_hash[k])
    intersection.length.times { feedback << black }
    if v.length <= secret_hash[k].length
      (v.length - intersection.length).times { feedback << white }
    end
  end
  feedback
end

def format_feedback(feedback)
  formatted = feedback
  formatted << " " until formatted.length == 4
  formatted
end

There are definitely some inefficiencies in your code, but it's a good start. The first thing I'd say is that there is no reason for you to create variables black and white in calculate_feedback. All they hold is the names of the colors and it's no more efficient. The issue is that you seemed to have started to code this before fully thinking of the implementation.

From a basic perspective, here are the rules:

Guesser has 12 guesses
Each guess gets compared to the correct code
If the guess is the correct color in the correct position a black peg comes up in that spot, otherwise a white peg comes up (at most once per color).

So, let's break this down into an algorithm.

Create secret code and create counter for user's guesses
Get user's guess
Compare user's guess to secret code.
Go back to step 2 until the user either guessed the code correctly or has hit 12 guesses.

The biggest part of the algorithm to focus on is part 3, which is comparing the user's guess to the secret code. Luckily, because you're using Ruby, you have some great resources for this. Let's break this step down into two parts.

First: Find out how many black pegs should be there. This can be done with one line in ruby.

black = code.zip(guess).count{|i| i.inject(:eql?)}

This might look a bit confusing but what it does is it takes the secret code (represented by the array code and zips it into an array with guess. So for the above example code.zip(guess) would give us [["Red", "Blue"], ["Blue", "Green"], ["Green", "Red"], ["Red", "Red"]]. Then count{|i| i.inject(:eql?)} means count all of the arrays within the array where the elements are equal. This is only true for ["Red", "Red"] and so it gives us a count of 1 which is the number of black pegs to be returned. Now, we have to talk about the white pegs. Because there can be at most 1 per color guessed, we should consider eliminating duplicates in the array of the user's guess. Thus, we can do this

white = guess.uniq.count{|i| code.include?(i)}

So great, with only two lines we have the number of white and black pegs we need for each turn. Now let's put this all together into a concise program.

def provide_feedback(code, guess)
  black = code.zip(guess).count{|i| i.inject(:eql?)}
  white = guess.uniq.count{|i| code.include?(i)}
  result = Array.new(4, '')
  black.times { result.unshift('black').pop }
  white.times { result.unshift('white').pop }
  result
end

Of course, this is still a bit more verbose than I'd prefer. Why not tighten it up a bit more by removing the black and white variables all together.

def provide_feedback(code, guess)
  result = Array.new(4, '')
  code.zip(guess).each{|i| result.unshift('black').pop if i.inject(:eql?)}
  guess.uniq.each{|i| result.unshift('white').pop if code.include?(i) && result[-1] == ''}
  result
end

That's the most concise and Ruby way I could think of.


Android Movie Class With AsyncTask I've got a class called Movie and within this class I use an AsyncTask to get a Bitmap from a url passed in the constructor.

To store the image I use new DownloadImage().execute(url).get();. However I'm concerned about this blocking the UI Thread as now its a synchronous call. Is there another way I can go about saving the image in the Bitmap variable?

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.os.AsyncTask;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutionException;

public class Movie
{
    //Variable for a movie
    private String name;
    private String rating;
    private String genre;
    private String plot;
    private String pathToMovie;

    private int movieId;
    private int runtime;
    private int year;

    private Bitmap image;

    public Movie(String name, String rating, String genre, String plot, String pathToMovie, int movieId, int runtime, int year, String imagePath) throws ExecutionException, InterruptedException
    {
        //Set the variables
        this.name = name;
        this.rating = rating;
        this.genre = genre;
        this.plot = plot;
        this.pathToMovie = pathToMovie;
        this.movieId = movieId;
        this.runtime = runtime;
        this.year = year;

        //Download the image from the imagePath
        this.image = getImageFromUrl(imagePath);
    }

    /*
     * A function to download the image from the imagePath provided
     */
    private Bitmap getImageFromUrl(String url) throws ExecutionException, InterruptedException
    {
        return new DownloadImage().execute(url).get();
    }

    //Define getters
    public String getName(){ return this.name; }
    public String getRating(){ return this.rating; }
    public String getGenre(){ return this.genre; }
    public String getPlot(){ return this.plot; }
    public String getPathToMovie(){ return this.pathToMovie; }
    public int getMovieId(){ return this.movieId; }
    public int getRuntime(){ return this.runtime; }
    public int getYear(){ return this.year; }
    public Bitmap getImage(){ return  this.image; }

    //Set up a AsyncTask to download the images from the url
    private class DownloadImage extends AsyncTask<String, Void, Bitmap>
    {
        @Override
        protected Bitmap doInBackground(String... params)
        {
            //Get the image from the url
            try
            {
                //Create a new URL based on the string provided
                URL url = new URL(params[0]);

                //Create a new HTTP connection from the URL
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();

                //Get the content of the page
                InputStream inputStream = connection.getInputStream();

                //Use a BitmapFactory to convert the InputStream into a bitmap
                return BitmapFactory.decodeStream(inputStream);

            }
            catch (IOException e)
            {
                e.printStackTrace();
                return null;
            }
        }
    }
}

You could try to write your app in callback passing style. That means methods that take a while (e.g. methods for fetching data from the web) take a callback argument that contains the code that will run once the operation is finished.

This program uses two ExecutorServices. One processes everything in one single thread. The other one runs stuff in parallel. All the code you run with the parallel ExecutorService should never access any objects that are modified by the rest of the program unless you know how to do synchronization correctly. But you don't need any synchronization at all here. Just ensure all the code that modifies the state of your program runs only in the single threaded ExecutorService and everything will be fine.
You may notice that final is used a lot in this code. That's because variables that are implicitly passed to an anonymous class need to be final.

class Tools {
  public final static ExecutorService async = Executors.newSingleThreadExecutor();
  public final static ExecutorService parallel = Executors.newFixedThreadPool(8);

  public static void shutdown() {
    Tools.async.shutdown();
    Tools.parallel.shutdown();
  }

  public static void getImageFromUrl(final String urlString, final Async<Bitmap> async) {
    Tools.parallel.execute(new Runnable() {
      public void run() {
        try {
          System.out.println(Thread.currentThread() + " - Loading image: " + urlString);
          async.send(null);
          /*
          URL url = new URL(urlString);
          HttpURLConnection connection = (HttpURLConnection) url.openConnection();
          connection.setDoInput(true);
          connection.connect();
          InputStream inputStream = connection.getInputStream();
          async.send(BitmapFactory.decodeStream(inputStream));
          */
        } catch(Exception e) {
          async.error(e);
        }
      }
    });
  }
}

abstract class Async<T> {
  abstract protected void accept(T t);
  public void send(final T t) {
    final Async<T> self = this;
    Tools.async.execute(new Runnable() {
      public void run() {
        self.accept(t);
      }
    });
  }

  public void error(Throwable err) {
    err.printStackTrace();
  }
}

class Ref<T> {
  private T value;
  public Ref(T value) {
    this.value = value;
  }
  public T get() {
    return value;
  }
  public void set(T value) {
    this.value = value;
  }
}

class Test {
  public static void main(String[] args) {
    Tools.async.execute(new Runnable() {
      public void run() {
        mainProgram();
      }
    });
  }

  private static void mainProgram() {
    final ArrayList<Movie> movies = new ArrayList<>();
    final Ref<Integer> numImages = new Ref<>(10);
    for(int i = 0; i < 10; i++) {
      final int imageNr = i;
      Tools.getImageFromUrl("http://image-website/image" + i, new Async<Bitmap>() {
        public void accept(Bitmap image) {
          System.out.println(Thread.currentThread() + " - Creating movie object for image: " + imageNr);
          movies.add(new Movie("", "", "", "", "", 0, 0, 0, image));
          numImages.set(numImages.get() - 1);
          if(numImages.get() == 0) {
            allMoviesLoaded(movies);
          }
        }
      });
    }
  }

  private static void allMoviesLoaded(ArrayList<Movie> images) {
    System.out.println("All movies loaded");
    Tools.shutdown(); //ends the program
  }
}


Ordering an un-ambiguous scrambled date A date is un-ambiguous when each number may be
    decided to be day or month or year given the range
    limitation of these numbers.

For example

\$14\$ cannot be a month number
\$2008\$ cannot be a day number

@param un_ambiguous_date: an un-ambiguous scrambled date,
    of the format X/Y/Z where X, Y, Z correspond to
    day, month, year but not necessarily in this order.

@return The date in the order 'DAY/MONTH/YEAR'.

I am particularly interested in full input validation and nice error producing, so tell me any lack of clarity/corner case missed.

For example usage see the doctests included with the function:

def order_date(un_ambiguous_date):
    """
    @param un_ambiguous_date: an un-ambiguous scrambled date,
    of the format X/Y/Z where X, Y, Z correspond to
    day, month, year but not necessarily in this order.

    @return: The date in the order 'DAY/MONTH/YEAR'.

    A date is un-ambiguous when each number may be
    decided to be day or month or year given the range
    limitation of this numbers.
    (For example 14 cannot be a month number, and
    2008 cannot be a day number)

    >>> order_date('3/2015/13')
    '13/3/2015'

    >>> order_date('2012/20/4')
    '20/4/2012'

    # Here both 3/4/1000 and 4/3/1000 are possible.
    >>> order_date('3/4/1000')
    Traceback (most recent call last):
    ...
    ValueError: Ambiguous date was given

    >>> order_date('3/3/2050')
    '3/3/2050'

    >>> order_date('1/1/1')
    Traceback (most recent call last):
    ...
    ValueError: The date cannot be valid

    >>> order_date('12/6')
    Traceback (most recent call last):
    ...
    ValueError: The date is too short, format should be X/Y/Z

    >>> order_date('2000/2000')
    Traceback (most recent call last):
    ...
    ValueError: The date is too short, format should be X/Y/Z

    >>> order_date('Foo/Bar/Baz')
    Traceback (most recent call last):
    ...
    TypeError: The date should be made up of '/' separated INTEGERS

    """
    try:
        x, y, z = un_ambiguous_date.split('/')
    except ValueError:
        raise ValueError("The date is too short, format should be X/Y/Z")

    try:
        x, y, z = map(int, (x, y, z))
    except ValueError:
        raise TypeError("The date should be made up of '/' separated INTEGERS")

    day = [i for i in (x,y,z) if i < 31]
    month = list(set(i for i in (x,y,z) if i < 12))
    year = [i for i in (x,y,z) if i > 31]
    day = list(set(day) - set(month))
    if not day:
        day = month
    # print(day, month, year)
    if any(len(x) > 1 for x in (day, month, year)):
        raise ValueError("Ambiguous date was given")
    try:
        return '/'.join(map(str, (day[0], month[0], year[0])))
    except IndexError:
        raise ValueError("The date cannot be valid")

Wrong bounds

Your filters on your day/month aren't right:

day = [i for i in (x,y,z) if i < 31]
month = list(set(i for i in (x,y,z) if i < 12))

31 is a valid day and 12 is a valid month, so those should be <=. Additionally, you're not excluding negative numbers - so you'll want 1 <= i <= 31 for the first filter and 1 <= i <= 12 for the second.

Dealing with the tuple

Since just about everywhere you deal with (x,y,z) as a tuple, I would just keep it as a tuple the whole way and not unpack it. You only unpack it to check the length, so we can just make that check explicit. Also, if I passed in something like 1/2/3/4/5, you'd tell me that my date was too short, so this can get both right:

elems = un_ambiguous_date.split('/')
if len(elems) != 3:
    raise ValueError("The date is too {}, format should be X/Y/Z".format(
        'short' if len(elems) < 3 else 'long'))

try:
    elems = map(int, elems)
except ValueError:
    raise ...

day = [i for i in elems if 1 <= i <= 31]
# etc.

The last join

Instead of:

return '/'.join(map(str, (day[0], month[0], year[0])))

I would just use format:

return '{}/{}/{}'.format(day[0], month[0], year[0])

It's shorter and more readable.

Combine the last two checks

I would write a helper function that returns the first element of a single-element list:

def front(lst):
    if not lst:
        raise ValueError("The date cannot be valid")
    if len(lst) > 1:
        raise ValueError("Ambiguous date was given")

    return lst[0]

And then you can just write:

return '{}/{}/{}'.format(front(day), front(month), front(year))


Any better way to read Json array I have a json file - WorkflowNames.json with contents as -
["ImportOrder", "ValidateOrder", "ProcessOrder", "ArchiveOrder"]

My C# code to read this json file is -
private Dictionary<string, bool> GetWorkflowNames()
{
  var appDataFolder = ConfigurationMgr.GetAppPath("App_Data");
  var jsonFilePath = Path.Combine(appDataFolder, "WorkflowNames.json");
  JArray workflowNames = (JArray)JsonConvert.DeserializeObject(System.IO.File.ReadAllText(jsonFilePath));

  var workflowNamesDictionary = new Dictionary<string, bool>();
  foreach (JToken workflowName in workflowNames)
  {
    workflowNamesDictionary.Add(workflowName.ToString(), false);
  }

  return workflowNamesDictionary;
}

My code runs fine. But because this is my first attempt to read data from a json file, I am not sure about these -

As a json standard, any data in json file should be represented as key value pair. If I have just an array to read from json file, is it okay to declare as above?
Is there any better way, can I improve/simplify above C# code?

Thanks a lot!

Json.Net has support for collections built-in. You should be able to use the generic version of DeserializeObject like this:
private Dictionary<string, bool> GetWorkflowNames()
{
    var appDataFolder = ConfigurationMgr.GetAppPath("App_Data");
    var jsonFilePath = Path.Combine(appDataFolder, "WorkflowNames.json");
    var jsonString = System.IO.File.ReadAllText(jsonFilePath);
    var workflowNames = JsonConvert.DeserializeObject<List<string>>(jsonString);
    return workflowNames.ToDictionary(name => name, _ => false);
}

There are still a few things I would clean up in your code:
Add a using for System.IO and use File without the namespace. You could also use a static using like this using static System.IO.File; and access ReadAllText directly but I generally dislike this unless the class is very focussed and heavily using File.
You'll notice that I introduced a local variable jsonString as I don't like hiding the file access in the call to deserialize the json. I try to stick rigidly to one thing happening per line. Simple and clear code is best when you want to maintain it 2 years later.
I'd also recommend using .ToDictionary as it shortens the code and makes it very obvious what you're doing. Having said that, I would have this return an IEnumerable<string> instead of a dictionary. It's not clear why this returns a dictionary and GetWorkflowNames sounds like it would be perfectly reasonable to return the list.


Grabbing SQL records: Nullable bool to bool So I have a method that does a lookup in an existing List<T>, populated elsewhere by grabbing the records from a SQL table holding configuration data for each state where we do business. This method just looks up in the list by state abbreviation and then returns the value of a Boolean field in the record.

public bool StateRoundsToQuarterHour(int recordID, string stateAbbrev)
    {
        bool? result = null;

        try
        {
            // Query our existing list of StateConfig objects for a match, then return the value of RoundMinutes.
            result = (from x in listStateConfig
                           where x.State == stateAbbrev
                           select x.RoundMinutes).First();

        }
        catch (Exception e)
        {
            // if state not found, email error and continue
            string strMessage = String.Format("Error: {0} Inner Exception {1}", Convert.ToString(e.Message) + Environment.NewLine, Convert.ToString(e.InnerException));

            // log and email error
            ErrorContinue(recordID, strMessage);

        }

        // as long as we found a result, we're happy
        if(result != null)
        {
            return (bool)result;
        }
        else
        {
            string strMessage = String.Format("State {0} does not exist in table, but RecordID {1} belongs to that state.", stateAbbrev, recordID);

            // log and email error
            ErrorContinue(recordID, strMessage);

            return false;   // if the state doesn't exist, we'll default to rounding is not required
                            // We send an alert about the state not existing, so we'll be able to act on it
        }

    }

The List may not contain a result, so in that case the query will not find anything and remain null. I'm not entirely happy with the method using a nullable Boolean internally and then casting it to non-nullable to use in the return, but I don't want the return type of the method to be nullable. Is this a reasonable approach? Where can this be improved?

// as long as we found a result, we're happy
if(result != null)
{
    return (bool)result;
}

This could be written as simply:

if (result.HasValue)
{
    return result.Value;
}

bool? is shorthand for Nullable<bool>, a generic value type with reference type semantics. Basically Nullable<T>.Value is a T, so there's no need to cast anything.

Also, being a value type, initializing it is redundant.

bool? result;

Is entirely sufficient.

Avoid cluttering your code with comments that don't bring anything to the table:

// as long as we found a result, we're happy

Good comments should say why the code does what it does - don't bother commenting just to state the obvious, or to rephrase what the code is already saying.

If this needs a comment every time it's used:

// log and email error
ErrorContinue(recordID, strMessage);

...then perhaps the ErrorContinue method needs a better, more descriptive name?

You're catching a System.Exception here:

    try
    {
        // Query our existing list of StateConfig objects for a match, then return the value of RoundMinutes.
        result = (from x in listStateConfig
                       where x.State == stateAbbrev
                       select x.RoundMinutes).First();

    }
    catch (Exception e)
    {
        //...
    }

But it looks like you're only handling the InvalidOperationException that .First() would throw when there aren't any items matching the where criteria.

If the query is meant to return only 1 record, use .Single(), not .First(). And if the query can return no records, use .SingleOrDefault().

The problem is that you're projecting the result and Selecting .RoundMinutes, which is a value type and can't be null, so SingleOrDefault() would return false for an bool value, because default(int) == 0.

You could instead select the actual StateConfig object, and boil the code down to this:

public bool StateRoundsToQuarterHour(int recordId, string stateAbbrev)
{
    var config = _stateConfig.SingleOrDefault(x => x.State == stateAbbrev);
    if (config != null)
    {
        return config.RoundMinutes;
    }
    else
    {
        var message = string.Format("State '{0}' does not exist in table, but RecordId {1} belongs to that state.", stateAbbrev, recordId);
        _logger.Warn(message);
        return false;
    }
}

Notice Id vs. ID, _logger.Warn vs ErrorContinue, message vs. strMessage, and _stateConfig vs listStateConfig. Don't try to encode the type of a variable into its identifier name, that's bad Hungarian notation, and it's not the type that's useful but what the variable it actually used for.

I'm prefixing private fields (I assumed listStateConfig was a private field here) with an underscore, but you could alternatively qualify them with the this keyword - that's personal preference.


Unique compile time (constexpr) type ID without RTTI I am making a library where I need to generate a unique ID for a type where the ID must be known at compile time. I first relied on the address of a template function, but it proved itself unreliable both with MSVC and Clang on windows.

Then I came up with the address of a static data member inside a template class.

I want to support most use cases as possible here's what comes to my mind:

Eager optimizations that would merge the definition of static variables or inline functions
DLL and shared libraries
Link time optimizations

My tests were successful, but it wasn't an exotic setup with multiple level dlopen or stuff like that. I'm not an expert with the kind of use case I want to support so it's hard to tell if I can ensure my claims are okay.

My design work by declaring a static data member of type T* inside a template class, then taking its address as the value of the ID.

namespace detail {

/**
 * Template class that hold the declaration of the id.
 *
 * We use the pointer of this id as type id.
 */
template<typename T>
struct type_id_ptr {
    // Having a static data member will ensure (I hope) that it has only one address for the whole program.
    // Furthermore, the static data member having different types will ensure (I hope) it won't get optimized.
    static const T* const id;
};

/**
 * Definition of the id.
 */
template<typename T>
const T* const type_id_ptr<T>::id = nullptr;

} // namespace detail

/**
 * The type of a type id.
 */
using type_id_t = const void*;

/**
 * The function that returns the type id.
 *
 * It uses the pointer to the static data member of a class template to achieve this.
 * Altough the value is not predictible, it's stable (I hope).
 */
template <typename T>
constexpr auto type_id() noexcept -> type_id_t {
    return &detail::type_id_ptr<T>::id;
}

It there any caveats to be aware with this design?

Here's some usage of this and motivation for this code:

constexpr auto id_of_int_type = type_id_t{type_id<int>()};
constexpr auto id_of_float_type = type_id_t{type_id<float>()};

static_assert(id_of_int_type != id_of_float_type);

This can be compiled with -fno-rtti.

Also, it can fully be used at compile time. Here's the equivalent with RTTI:

constexpr auto test = typeid(int); // won't compile

This code won't compile since typeid cannot be used at compile time. Also, disabling RTTI also disables static RTTI.

The code is useful because it can be used in data structure or to be couple with compile time type erasure.

std::map<type_id_t, void*> anything;

// sorry for raw new
anything[type_id<std::string>()] = new std::string{"hello"};

// compile time example
static auto static_int = int{};
static auto static_double = double{};

// type_id as the keys in a compile time map
constexpr auto anything_compiletime = frozen::unordered_map<type_id_t, void*, 2>{
    {type_id<int>(), &static_int},
    {type_id<double>(), &static_double}
};

I'm convinced that your design will work correctly. Uniqueness of static variables is guaranteed, and they won't be optimized away if you define and odr-use them (taking the address of a variable is odr-using it). Running it through stack-overflow would be a good idea though, because it will probably catch the eye of one of those 200K+ reputation guru who answer all the tricky language questions.

What I can't understand is what you're trying to achieve with this. The only useful property of this compile-time id is its uniqueness, so it doesn't achieve anything more than the type itself: what is the difference between if (type_id<A>() == type_id<B>()) and if (std::is_same_v<A, B>)? I would argue that it achieves a lot less, because types have other useful traits (for a partial but ready-made list, just take a look at the type_traits header in the standard library).

Besides, your id generator isn't truly generic: type_id<int&>() won't compile because a pointer can't point to a reference (thus static const int&* const id is illegal). Of course there's always the possibility to remove the reference, but it means that you'll use type_traits to make your type_id work -so it underlines that you should use well-established, standard type traits instead of this new compile-time type_id.

I'd suggest, if it is possible, that you post here a larger part of your code,
 containing use cases, and let our collective brain work on the solution of the broader problem.

Edit: I understand now better what you want to do. I really like the simplicity of use, and I find the hack very clever. Actually, if it was uglier, limitations like no-references-allowed wouldn't matter much, because everyone would see it as work-around. But since it seems so fluent, it could quickly become pervasive in the code; then limitations matter, all the more when they result in obscure error messages.

Anyway, I believe I would have come up with a less ambitious design, which would also be easier to maintain and understand (this concrete implementation relies on C++17 but it wouldn't be to difficult to implement in previous standards):

#include <iostream>
#include <vector>

template <typename... Types>
struct Type_register{};

template <typename Queried_type>
constexpr int type_id(Type_register<>) { static_assert(false, "You shan't query a type you didn't register first"); return -1; }

template <typename Queried_type, typename Type, typename... Types>
constexpr int type_id(Type_register<Type, Types...>) {
    if constexpr (std::is_same_v<Type, Queried_type>) return 0;
    else return 1 + type_id<Queried_type>(Type_register<Types...>());
}

int main() {
   Type_register<int, float, char, std::vector<int>, int&> registered_types;
   constexpr auto test1 = type_id<int&>(registered_types);
   constexpr auto test2 = type_id<int*>(registered_types);
}


Generic property with AOP-functionality in Java After playing around with Java 8 and Generics for some time, I came across an idea while reading some posts about Apple's new programming language Swift.

Swift has AOP-like methods for properties (willSet and didSet) and I thought of creating something similar in Java with the help of the new functional interfaces of Java 8.

/**
 * Generic wrapper for a property with the possibility to apply functions before, after and instead of getting/setting the value
 *
 * @author Thomas Eizinger
 * @param <T> The type of the wrapped value
 */
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;

public class Property<T> {

    private T value;

    private BiConsumer<T, T> beforeSet = (u, v) -> {};
    private Function<T, T> onSet = (v) -> (v);
    private Consumer<T> afterSet = (v) -> {};

    private Consumer<T> beforeGet = (v) -> {};
    private Function<T, T> onGet = (v) -> (v);
    private Consumer<T> afterGet = (v) -> {};

    public void set(T value) {
        this.beforeSet.accept(this.value, value);
        this.value = this.onSet.apply(value);
        this.afterSet.accept(this.value);
    }

    public T get() {
        this.beforeGet.accept(this.value);
        this.value = this.onGet.apply(this.value);
        this.afterGet.accept(this.value);
        return this.value;
    }

    public void beforeSet(BiConsumer<T, T> beforeSet) {
        this.beforeSet = beforeSet;
    }

    public void onSet(Function<T, T> onSet) {
        this.onSet = onSet;
    }

    public void afterSet(Consumer<T> afterSet) {
        this.afterSet = afterSet;
    }

    public void beforeGet(Consumer<T> beforeGet) {
        this.beforeGet = beforeGet;
    }

    public void onGet(Function<T, T> onGet) {
        this.onGet = onGet;
    }

    public void afterGet(Consumer<T> afterGet) {
        this.afterGet = afterGet;
    }
}

Example usage:

public class Foo {

    private Property<Integer> bar;

    public Foo() {
        bar = new Property<>();
        bar.beforeSet((oldValue, newValue) -> System.out.printf("bar will be set from %d to %d.%n", oldValue, newValue));
    }

    public Integer getBar() {
        return bar.get();
    }

    public void setBar(Integer bar) {
        this.bar.set(bar);
    }
}

Some usecases I could think of would be:

Notifying observers
Constraint checks before setting values
Converting values (e.g. tolowercase for strings)

What do you think of this?  Does this put too much logic into properties?

Edit:

I changed the following things based on the review and published the code on github:

Added null-checks before adding new delegates.
New delegates are appended after the existing one.
Changed onGet to Consumer<T> and removed beforeGet and afterGet.
Changed name to PropertyDecorator

My first thought is: Interesting.

The Property<T> class as it is right now

First, some feature-requests or changes you can consider:

You could combine beforeSet and onSet into a BiFunction<T, T, T> (which is the same as BinaryOperator<T>).
It could potentially be useful to use the afterSet as a BiConsumer, to also let it know about what the previous value was.
What if a previous function has been set for afterSet/beforeSet/etc.? I think you should do a null-check there and either throw an exception if it has already been set, or auto-add it (using the default methods that exists on the interfaces), such as this.afterSet = this.afterSet.andThen(afterSet);
I'm not a big fan of the onGet feature. In my experience, getters should do what they do best: Get the actual value. Having the possibility to modify the value that should be returned seems risky. Doing conversion like String.toLowerCase() for example should lie where it is being used, or the property should be set to lower case right from the start IMO.
Actually, thinking about it... I'm not sure about any of the get-features... I just don't see a specific real use case for them.

The system itself

I'm going to list a couple of good things and a couple of bad things with this approach:

Good things:

Allows you to manipulate the "behavior" of a property in quite some detail.
Allows you to manipulate the "behavior" of a property in quite some detail.
Allows you to manipulate the "behavior" of a property in quite some detail.

(One time for the beforeSet feature, once for the onSet and once for afterSet. Three-in-one)

Bad things:

Primitive types needs to be wrapped into it's non-primitive type, like int -> Integer. This leads to slower code as there will be some auto-boxing, and it will allow the value null where you might not want that value, or you have to handle the null with a beforeSet or similar. Although you could potentially separate classes for  IntProperty, BooleanProperty, etc. I don't think you'd want to do all those classes.
When should I make my Java classes use this approach or not? Should I introduce them when I feel like I need them or should I play safe and use this approach on all my properties, even though when I will probably never need them? I can imagine there will be some headache going on no matter what option I would choose.
It's breaking the Java beans style, which isn't a bad thing by itself. It can cause a bit of a problem when using libraries that depends a lot on reflection, but there are normally ways to work around that. (I.e. telling the library to ignore the private property and use the getters and setters provided).

A different approach that's capable of doing the same thing

Consider Google's EventBus code. With the right event classes, this can accomplish the same things. Example code following: (not tested, but something similar would work)

public class Foo {

    private int bar;
    private EventBus events = new EventBus();

    public Foo() {
        bar = 42;
        events.registerListener(this);
    }

    @Subscribe
    private void onSetChanged(BarChangeEvent event) {
        System.out.printf("bar will be set from %d to %d.%n", event.getOldValue(), event.getNewValue()));
    }

    public int getBar() {
        return bar.get();
    }

    public void setBar(int bar) {
        events.post(new BarChangeEvent(this.bar, bar));
        this.bar = bar;
    }
}

Of course, there's bad things to say about this approach as well. One example is that it always creates a new object whenever bar is set. For most projects of course, the @Subscribe method is probably not inside the Foo class. Instead the class will have to expose the EventBus somehow (or the EventBus can be injected into the Foo class).

Still another approach

This is the fastest approach, but unfortunately it is the least flexible approach as well.

The simple "do-it-in-the-setter approach"

public class Foo {

    private int bar;

    public Foo() {
        bar = 42;
    }

    public int getBar() {
        return bar;
    }

    public void setBar(int bar) {
        System.out.printf("bar will be set from %d to %d.%n", this.bar, bar);
        this.bar = bar;
    }
}

Summary

You might have use for your Property<T> code, if so then great. I personally would probably not use it. (I tend to use the Event-driven approach when I need to, not for each and every property of course. Sometimes I might even use the "put-it-in-the-setter-approach")

  Does this put too much logic into properties?

Personally, I think it does yes. But that's just my two three cents.


PDcurses library menu.h extention I am currently learning how to use PDcurses in VC++ 2015 Community, and I noticed that menu.h is not implemented so I decided to extend the library for my own use (feel free to just copy the code if it's what you were looking for).

The only question I have is: was my use of namespaces (both named and unnamed) correct? And is this a good approach as I do not see a reason to make a singleton or something involving classes?

NOTE: I did research the web about dividing functions into namespaces like I did in the code, but I can't find if it's the correct approach for this specific task.

menu.h

#ifndef MENU_H
#define MENU_H

#include "curses.h"

namespace menu
{
    int renderMenu(WINDOW* menu_win, const char* title, const char* items[], int n_items);
    WINDOW* menuWin(const char* title, const char* items[], int n_items, int y, int x);
    void initMenu();
}

#endif

menu.cpp

#include "menu.h"
#include <string>

namespace
{
    void renderItems(WINDOW* win, int selected, const char* items[], int n_items)
    {
        for (int index{}; index < n_items; ++index) {
            if (index == selected) {
                wattron(win, A_BOLD);
                mvwprintw(win, 3 + index, 2, items[index]);
                wattroff(win, A_BOLD);
            }
            else
                mvwprintw(win, 3 + index, 2, items[index]);
        }

        wrefresh(win);
    }

    int navigateMenu(WINDOW* win, const char* items[], int n_items)
    {
        int selected{};
        renderItems(win, selected, items, n_items);

        keypad(win, TRUE);
        while (true) {
            switch (wgetch(win)) {
              case KEY_DOWN:
                    if (selected < n_items - 1)
                        ++selected;
                    else
                        selected = 0;
                  break;
              case KEY_UP:
                    if (selected > 0)
                        --selected;
                    else
                        selected = n_items - 1;
                  break;
                case 10: /*enter key*/
                    return selected;
                    break;
            }

            renderItems(win, selected, items, n_items);
        }
    }
}

int menu::renderMenu(WINDOW* menu_win, const char* title, const char* items[], int n_items)
{
    std::string separator{ '+' + std::string(getmaxx(menu_win) - 2, '-') + '+' };
    mvwprintw(menu_win, 1, (getmaxx(menu_win) - strlen(title)) / 2, title);
    wborder(menu_win, '|', '|', '-', '-', '+', '+', '+', '+');
    mvwprintw(menu_win, 2, 0, separator.c_str());
    wrefresh(menu_win);

    return navigateMenu(menu_win, items, n_items);
}

WINDOW * menu::menuWin(const char* title, const char* items[], int n_items, int y, int x)
{
    int width{};
    for (int index{}; index < n_items; ++index)
        if (width < static_cast<int>(strlen(items[index])))
            width = strlen(items[index]);
    if (width < static_cast<int>(strlen(title)))
        width = strlen(title);
    width += 4;

    int height{ 4 + n_items };

    return newwin(height, width, y, x);
}

void menu::initMenu()
{
    curs_set(FALSE);
    noecho();
    cbreak();
    refresh();
}

source.cpp <--example of use

#include "menu.h"
#include <string>

int main()
{
    const char* items[]{
        {"option a"},
        {"option b"},
        {"option c"}
    };

    const char* title{ "Main Menu" };

    initscr();
    menu::initMenu();

    WINDOW* menu = menu::menuWin(title, items, 3, 2, 2);
    int choice = menu::renderMenu(menu, title, items, 3);
    /*use choice to preform an action*/

    mvprintw(0, 0, "%s was chosen.", items[choice]);
    refresh();

    getch();
    endwin();
    return 0;
}

An if inside the loop is usually counterproductive. Consider highlighting the choice afterwards:

    for (int index{}; index < n_items; ++index) {
        mvwprintw(win, 3 + index, 2, items[index]);
    }
    wattron(win, A_BOLD);
    mvwprintw(win, 3 + selected, 2, items[selected]);
    wattroff(win, A_BOLD);

It is very unclear what the 3 and 2 offsets stand for. Apparently they have something to do with the visual layout. Consider giving them some meaningful names.

Since you are writing in c++, you'd be in much better shape operating on vector<char *> rather than a raw array.


std::tuple foreach implementation I wrote a "foreach" implementation for std::tuple:

#pragma once

#include <tuple>
/**
 * Callback example:

struct Call{
    float k=0;

    template<typename T, int Index>        // lambda function not efficient than this. Tested -O2 clang, gcc 4.8
    inline void call(T &&t){
        std::cout << t.h << " ; " << "id = " << Index << std::endl;
    }
};
*/

namespace TUPLE_ITERATOR{
    template<typename Tuple, int index, int size>
    struct LOOP{
        template <typename Callback>
        static inline void wind(Tuple&& tuple, Callback&& callback){
            callback.template call<decltype(std::get<index>(tuple)), index> (std::get<index>(tuple));
            LOOP<Tuple, index+1, size>::wind( std::forward<Tuple>(tuple), std::forward<Callback>(callback) );
        }
    };

    template<typename Tuple, int size>
    struct LOOP_BACK{
        template <typename Callback>
        static inline void wind_reverse(Tuple&& tuple, Callback&& callback){
            callback.template call<decltype(std::get<size>(tuple)), size>( std::get<size>(tuple) );
            LOOP_BACK<Tuple, size-1>::wind_reverse( std::forward<Tuple>(tuple), std::forward<Callback>(callback) );
        }
    };

    // stop specialization
    template<typename Tuple, int size>
    struct LOOP<Tuple, size, size> {
        template <typename Callback>
        static inline void wind(Tuple&& , Callback&& ){
            // end
        }
    };
    template<typename Tuple>
    struct LOOP_BACK<Tuple, -1>{
        template <typename Callback>
        static inline void wind_reverse(Tuple&& , Callback&& ){
            // end
        }
    };
}

template<typename Tuple, typename Callback>
static void inline iterate_tuple(Tuple&& tuple, Callback&& callback){
    TUPLE_ITERATOR::LOOP< Tuple, 0, std::tuple_size< typename std::decay<Tuple>::type >::value >
            ::template wind<Callback>( std::forward<Tuple>(tuple), std::forward<Callback>(callback) );
}

template<typename Tuple, typename Callback>
static void inline iterate_tuple_back(Tuple&& tuple, Callback&& callback){
    TUPLE_ITERATOR::LOOP_BACK< Tuple, std::tuple_size< typename std::decay<Tuple>::type >::value-1 >
            ::template wind_reverse<Callback>( std::forward<Tuple>(tuple), std::forward<Callback>(callback) );
}

// Call:
// iterate_tuple(Callback(), std::make_tuple(1,2,3,"asdaa"));

But I look at how other folks do that, and I see that they do this in another way. They get an array of indices, and then recursively call the callback function. Is my implementation worse than that? I ask this because if I call tuple_iterator twice, with the same parameters, the compiler starts to use asm "calls". Look HERE, on the red.

void TUPLE_ITERATOR::LOOP<std::tuple<std::pair<int, Data>,
std::pair<int, Data> >, 0, 2>:

Loki's solution does not enforce the order in which the function calls are performed, because the order in which function arguments are evaluated is unspecified. Here's a C++14 solution that ensures the function is called from left to right:

#include <cstddef>
#include <tuple>
#include <utility>

template <typename Tuple, typename F, std::size_t ...Indices>
void for_each_impl(Tuple&& tuple, F&& f, std::index_sequence<Indices...>) {
    using swallow = int[];
    (void)swallow{1,
        (f(std::get<Indices>(std::forward<Tuple>(tuple))), void(), int{})...
    };
}

template <typename Tuple, typename F>
void for_each(Tuple&& tuple, F&& f) {
    constexpr std::size_t N = std::tuple_size<std::remove_reference_t<Tuple>>::value;
    for_each_impl(std::forward<Tuple>(tuple), std::forward<F>(f),
                  std::make_index_sequence<N>{});
}

I use swallow{f(x)...} to force the evaluation order. It works because the order in which the arguments to a brace initializer are evaluated is the order in which they appear. You can then use it like:

#include <iostream>

int main() {
    for_each(std::make_tuple(1, '2', 3.3), [](auto x) {
        std::cout << x << std::endl;
    });
}

EDIT

I modified the code so it works on both GCC and Clang. Here's a more in-depth explanation of for_each_impl.

First, we make sure that we call f inside a braced initializer, so the evaluation order is from left to right:

using swallow = int[];
swallow{f(std::get<Indices>(tuple))...};

But then, what if f does not return an integer value? What if it returns void for example? So we use the comma operator to make sure the expression is an integer which can be used inside the braced initializer:

swallow{(f(std::get<Indices>(tuple)), int{})...};

The expression (f(stuff), int{})... is a parameter pack expansion. It expands to (f(stuff_1), int{}), (f(stuff_2), int{}), ..., (f(stuff_n), int{}), so each expression is really an int, except that some side effect has been performed before. Then, to avoid nasty overloads of the comma operator by whatever is returned by f, we insert a void between f(...) and int{}. Since operator,(SomeType, void) can't be overloaded, this ensures that the builtin operator, is used, which is what we want. This might seem overkill, but we do this in highly generic code where we must assume that f(...) could overload operator,:

swallow{(f(std::get<Indices>(tuple)), void(), int{})...};
                                      ^~~~ Make sure the builtin operator, is used

Then, what happens if for_each_impl is sent 0 arguments? We're gonna try to create a 0-sized array, so we must make sure the array always has at least one element in it. We use a dummy int for this:

swallow{1, (f(std::get<Indices>(tuple)), void(), int{})...};
        ^~~~ Now the array always has at least one element in it

We're almost done, but now there's an anoying compiler warning saying "You're creating a temporary array 'swallow' which is never used". To silence it, I cast the swallow{...} to void. Finally, just add perfect forwarding of the Tuple and you're done:

(void)swallow{1, (f(std::get<Indices>(std::forward<Tuple>(tuple))), void(), int{})...};
^^^^^^ Silence warning                ^^^^^^^^^^^^^^^^^^^ Perfect forwarding

Note that the way I use std::forward here could be unsafe in other circumstances. This is because tuple could be double-moved-from if the function I forwarded it to had different characteristics. Consider:

swallow{f(function_that_moves_from_its_arg<Indices>(std::forward<Tuple>(tuple)))...};

Now, tuple might be moved-from several times:

swallow{
    f(function_that_moves_from_its_arg<Index1>(std::forward<Tuple>(tuple))), // move here
    f(function_that_moves_from_its_arg<Index2>(std::forward<Tuple>(tuple))), // move here
    f(function_that_moves_from_its_arg<Index3>(std::forward<Tuple>(tuple))), // move here
    ...
}

However, I know std::get is a friendly function and so there's should be no problem in doing this. There's an alternative way to do it "safely", but it involves using std::tuple_element and it's more complicated.


Map with case insensitive get, remove and containsKey I am looking for a Map implementation (with String keys and any generic type for values) that would support getting, removing and checking the existence of keys in a case insensitive manner while preserving the original keys for the extraction with keySet() or entrySet(). So running put("Some Text", object) I want to be able to retrieve/remove/test object via get("sOmE tExt"), remove("some text"), containsKey("Some TeXT"), yet running keySet() I want to get {"Some Text"}.

The map will be used in a highly concurrent context, but if you have really great ideas based around a standard HashMap please suggest. The implementation should have no external dependencies, that is use only standard Java.

So far I came up with this fairly straightforward implementation. However, I am not sure what could be potential deficiencies of this implementation in a concurrent setting. So far I can see one: keySet, entrySet and values are no longer views, but one should not iterate over keys extracting values by key in a concurrent setting anyway.

Any other issues with this implementation or can you suggest a better one?

public class Context implements Map<String, String> {

    private final ConcurrentHashMap<String, Entry<String, String>> data = new ConcurrentHashMap<>();

    public Context() {
        this(null);
    }

    public Context(@Nullable Context context) {
        this((Map<String, String>) context);
    }

    public Context(@Nullable Map<String, String> context) {
        if (context != null) {
            putAll(context);
        }
    }

    @Override
    public int size() {
        return data.size();
    }

    @Override
    public boolean isEmpty() {
        return data.isEmpty();
    }

    @Override
    public boolean containsKey(@Nonnull Object key) {
        return data.containsKey(String.valueOf(key).toLowerCase());
    }

    @Override
    public boolean containsValue(@Nonnull Object value) {
        Collection<String> vals = values();
        return vals.contains(String.valueOf(value));
    }

    @Override
    public String get(@Nonnull Object key) {
        Entry<String, String> val = data.get(String.valueOf(key).toLowerCase());
        return val != null ? val.getValue() : null;
    }

    @Override
    public String put(@Nonnull String key, @Nonnull String value) {
        Entry<String, String> val = data.put(key.toLowerCase(), new SimpleEntry<>(key, value));
        return val != null ? val.getValue() : null;
    }

    @Override
    public String remove(@Nonnull Object key) {
        Entry<String, String> val = data.remove(String.valueOf(key).toLowerCase());
        return val != null ? val.getValue() : null;
    }

    @Override
    public void putAll(@Nonnull Map<? extends String, ? extends String> map) {
        Map<String, Entry<String, String>> transformed = new HashMap<>();
        for (Entry<? extends String, ? extends String> entry: map.entrySet()) {
            transformed.put(entry.getKey().toLowerCase(), new SimpleEntry<>(entry.getKey(), entry.getValue()));
        }
        data.putAll(transformed);
    }

    @Override
    public void clear() {
        data.clear();
    }

    @Nonnull
    @Override
    public Set<String> keySet() {
        return data.values().stream().map(Entry::getKey).collect(Collectors.toSet());
    }

    @Nonnull
    @Override
    public Collection<String> values() {
        return data.values().stream().map(Entry::getValue).collect(Collectors.toList());
    }

    @Nonnull
    @Override
    public Set<Entry<String, String>> entrySet() {
        return new HashSet<>(data.values());
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Context context = (Context) o;
        return Objects.equals(data, context.data);
    }

    @Override
    public int hashCode() {
        return Objects.hash(data);
    }
}

You can't do that with HashMap. Use a TreeMap instead:

new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER)

For highly concurrent version, use ConcurrentSkipListMap:

new ConcurrentSkipListMap<String, String>(String.CASE_INSENSITIVE_ORDER)

Since you don't care about actual ordering, the String.CASE_INSENSITIVE_ORDER is fine for this. If locale-sensitive ordering is required, you need to supply a Collator instead, e.g.

Collator.getInstance(Locale.forLanguageTag("es-ES"))


String "Contains" char function I wrote this function which does the following from scratch w/o looking for ways that it is typically done:

Accepts a char c to search for.
Accepts a char* str to search within.
Accepts a buffer pointer, and stores all indices of c that are in str inside the provided buffer.
Returns the # of times that c was found in str.

Please critique and also - Are there better alternatives to export the indices other than using a buffer ptr?

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int str_contains(const char c, const char* str, int* output_buffer){
    int i, str_len;
    str_len = strlen(str);
    int *holder = malloc(str_len*sizeof(int));
    int holder_iteration = 0;
    for(i = 0; i < str_len; i++){
        if(str[i] == c){
            holder[holder_iteration++] = i;
        }
    }
    memcpy(output_buffer,holder,holder_iteration*sizeof(int));
    free(holder);
    return holder_iteration;
}

int main(){
    char* myString = "Welcome to the jungle, baby. Do you like to juggle or jump around?";
    int* output = malloc(500*sizeof(int));
    int number = str_contains('a',myString,output);

    printf("# of times: %d\nIndices: \n",number);
    int i;
    for(i = 0; i < number; i++){
        printf("%d\n",output[i]);
}

free(output);
    return(EXIT_SUCCESS);
}

The final memcpy may overflow output_buffer. I recommend to change the signature to

int str_contains(const char * str, char c, int *indices, size_t indices_size);

The caller shall compare the return value with the size of buffer it passed and act accordingly.
Dynamic memory is uncalled for. You may safely collect indices directly into the passed buffer.
There is no need for strlen.
When appropriate, use pointers.

All that said,

int str_contains(const char * str, char c, size_t * indices, size_t indices_size)
{
    size_t occurrences = 0;
    for (char * cursor = str; *cursor; cursor++) {
        if (*cursor == c) {
            if (occurrences < indices_size) {
                indices[occurrences] = cursor - str;
            }
            occurrences++;
        }
    }
    return occurrences;
}