Upgrade Firefox Quantum from tarball I wrote a little script to automate upgrading Firefox to a new version under Debian, since I don't want to install it from unstable and the snap version has rendering issues.

Any comments are welcome, is there anything I have missed or any potential problems?

#!/bin/bash

# firefox_upgrade - program to upgrade firefox quantum

error_exit()
{
    echo "$1" 1>&2
    exit 1
}

firefox_path=""
firefox_file=""

# parsing path and filename
if [ $# -ne 1 ]; then
    error_exit "usage: $0 firefox_quantum_path"
else
    firefox_path="$1"
    firefox_file="${firefox_path##*/}"
fi

# checking if input is a valid file
if [ ! -f "$firefox_path" ]; then
    error_exit "Invalid file! Aborting."
fi

# removing previous install, if existent
firefox_bin="/opt/firefox"
if [ -e "$firefox_bin" ]; then
    rm -rf $firefox_bin
else
    echo "$firefox_bin doesn't exist."
fi

# removing previous symlink, if existent
firefox_link="/usr/bin/firefox-quantum"
if [ -f "$firefox_link" ]; then
    rm $firefox_link
else
    echo "$firefox_link doesn't exist."
fi

# copying the tar to /opt
rsync -ah --progress $firefox_path /opt/$firefox_file

# unpacking the tar if successfully changed directory
if cd /opt; then
    tar -jxvf $firefox_file
else
    error_exit "Could not change directory! Aborting."
fi

# if unpack was successful, set permissions, create symlink, and remove tar
if [ "$?" = "0" ]; then
    chmod 755 /opt/firefox
    ln -s /opt/firefox/firefox /usr/bin/firefox-quantum
    rm $firefox_file
else
    error_exit "Could not extract file! Aborting."
fi
exit 0

Pretty nice script, I have mostly minor suggestions.

Always double-quote variables used in command arguments

The parameters in these command should be double-quoted to protect from word splitting and globbing:

rsync -ah --progress $firefox_path /opt/$firefox_file
...
rm $firefox_link
...
tar -jxvf $firefox_file
...
rm $firefox_file

Avoid changing the working directory in scripts

Changing working directories is usually error-prone and confusing,
look for ways to do what you need without changing the working directory.

if cd /opt; then
    tar -jxvf $firefox_file
else
    error_exit "Could not change directory! Aborting."
fi

Another way to write this without changing the directory (and correct quoting):

tar -jxvf "/opt/$firefox_file" -C /opt

It's very good that you check the exit codes of commands,
and this writing style will actually help you do that,
by simplifying near the end:

if ! tar -jxvf "/opt/$firefox_file" -C /opt; then
    error_exit "Could not extract file! Aborting."
fi

chmod 755 /opt/firefox
ln -s /opt/firefox/firefox /usr/bin/firefox-quantum
rm "/opt/$firefox_file"

Declare constants at the top of the file

There are some constant values that are very important for the program's behavior, but they are buried within the code.
It would be better to move these to somewhere near the top of the file,
where they are easy to see and to change.

firefox_bin="/opt/firefox"
firefox_link="/usr/bin/firefox-quantum"

There are some other values that are not in variables,
and it would be good to define variables for them,
for example the ones in this command:

ln -s /opt/firefox/firefox /usr/bin/firefox-quantum

Technique

Here, the else branch is not necessary,
because if the condition is true,
the script will exit anyway.
I suggest to just drop the else,
simply move its body after the conditional (just like you did in other places).

if [ $# -ne 1 ]; then
    error_exit "usage: $0 firefox_quantum_path"
else
    firefox_path="$1"
    firefox_file="${firefox_path##*/}"
fi

To set a variable empty, you can simply write like this:

firefox_path=
firefox_file=

It's usually not a good idea to exit 0 at the end of a script.
This forces exit code 0 (success).
The exit code of a script is the exit code of the last command.
By forcing it to 0,
the failure of the last command will get incorrectly covered up.


Better alternative to $(this).off("click") I have a notification system that looks like this:

function notificationMethod(message){
    // do stuff

    // once everything else is setup, attach a click handler to the "Okay" button
    $('#notificationOkay').click(function () {
        unBlockScreen();
        $(this).off("click"); // once they click the "Okay" button, remove the click event
    });
}

The reason that I'm putting the .click() handler in the notificationMethod() as opposed to the $(document).ready() is to be able to keep the notification code separate from the rest of the code that it has nothing to do with (other than it's on the same page). However, looking at my code it feels odd to have the .off("click") inside of the .click().

Is there anything particularly wrong with this approach?

For a handler that only fires once using jQuery you can use .one().

A click handler would look something like:

function notificationMethod(message){
    // do stuff

    // once everything else is setup, attach a click handler to the "Okay" button
    $('#notificationOkay').one("click", unBlockScreen);
}


Better size aligning? I have the following two vectors in C++11:

vector<unsigned char> left = { 1, 2, 3, 4, 5, 6 }; // it is meant to represent the number: 123456
vector<unsigned char> right = { 1, 2, 3, 4 }; // meant to be number: 1234

After a function processes them, they become:

left = { 6, 5, 4, 3, 2, 1 };
right = { 4, 3, 2, 1 };

Now, I need to complete the shorter one with zeros at the end until they are equal in size(). I have thefollowing method:

void bigint::process_operands( vector<unsigned char> & left, vector<unsigned char> & right )
{
    size_t left_size = left.size();
    size_t right_size = right.size();

    if( left_size < right_size )
    {
        size_t size_diff = right_size - left_size;

        for( size_t i = 0; i != size_diff; ++i )
            left.push_back( '0' );
    } else if( right_size < left_size )
    {
        size_t size_diff = left_size - right_size;

        for( size_t i = 0; i != size_diff; ++i )
            right.push_back( '0' );
    }
}

Is there any better implementation?

Firstly, given that you're using vector without namespace qualification (that is, not as std::vector), I assume you have a using namespace std; in this code. This is generally a bad idea, but especially so in this case. You use vector<unsigned char> & right (and vector<unsigned char> left), however, there is a std::right (and a std::left) defined in <ios>. This could potentially lead to some very confusing compiler errors.

Using a few tricks from <algorithm>, we can shorten the above code considerably.

void bigint::process_operands(vector<unsigned char> & left_, vector<unsigned char> & right_)
{
   auto& shorter = (left_.size() < right_.size()) ? left_ : right_;
   std::fill_n(std::back_inserter(shorter), std::abs(left_.size() - right_.size()), '0');
}

This is much more terse, but I find that using the standard library actually makes this code easier to read and more clear as to exactly what it is doing.


Splitting text into lines from a max width value for CANVAS Ok so this works as is, and is not actually slow at all (from what I can see) - However I don't like the taste of nested while loops and was wondering if anyone could give some insight on a different approach? Or how to improve mine to take away the while() { while() {}}

Here it is:

/* takes a string and a maxWidth and splits the text into lines */
 // ctx is available in the parent scope.
function fragmentText(text, maxWidth) {
    var words = text.split(' '),
        lines = [],
        line = "";
    if (ctx.measureText(text).width < maxWidth) {
        return [text];
    }
    while (words.length > 0) {
        while (ctx.measureText(words[0]).width >= maxWidth) {
            var tmp = words[0];
            words[0] = tmp.slice(0, -1);
            if (words.length > 1) {
                words[1] = tmp.slice(-1) + words[1];
            } else {
                words.push(tmp.slice(-1));
            }
        }
        if (ctx.measureText(line + words[0]).width < maxWidth) {
            line += words.shift() + " ";
        } else {
            lines.push(line);
            line = "";
        }
        if (words.length === 0) {
            lines.push(line);
        }
    }
    return lines;
}

The first thing I notice is an excessive use of measureText, which I am inclined to assume is a relatively expensive operation.  At a minimum, every word is measured twice - once to verify it fits within the maxWidth constraint, and once again to verify it fits on the current line. Of course, as the line grows, all previous words are measured again by virtue of the current line being measured on each loop.

Second, when a word doesn't fit on the current line, it must be processed again (it isn't shifted off the array in this condition).

With this kind of problem, I prefer to separate tasks - that is, measure first (no need to measure twice), build second. I would prefer to loop through the word list a couple of times to minimize the calls to measureText. I have rewritten the function with this in mind. The function is much longer now, but I feel it is easier to follow and to maintain when edge cases arise.

var emmeasure = ctx.measureText("M").width;
var spacemeasure = ctx.measureText(" ").width;

/* takes a string and a maxWidth and splits the text into lines */
 // ctx is available in the parent scope.
function fragmentText(text, maxWidth) {
    if (maxWidth < emmeasure) // To prevent weird looping anamolies farther on.
        throw "Can't fragment less than one character.";

    if (ctx.measureText(text).width < maxWidth) {
        return [text];
    }

    var words = text.split(' '),
        metawords = [],
        lines = [];

    // measure first.
    for (var w in words) {
        var word = words[w];
        var measure = ctx.measureText(word).width;

        // Edge case - If the current word is too long for one line, break it into maximized pieces.
        if (measure > maxWidth) {
            // TODO - a divide and conquer method might be nicer.
            var edgewords = (function(word, maxWidth) {
                var wlen = word.length;
                if (wlen == 0) return [];
                if (wlen == 1) return [word];

                var awords = [], cword = "", cmeasure = 0, letters = [];

                // Measure each letter.
                for (var l = 0; l < wlen; l++)
                    letters.push({"letter":word[l], "measure":ctx.measureText(word[l]).width});

                // Assemble the letters into words of maximized length.
                for (var ml in letters) {
                    var metaletter = letters[ml];

                    if (cmeasure + metaletter.measure > maxWidth) {
                        awords.push({ "word":cword, "len":cword.length, "measure":cmeasure });
                        cword = "";
                        cmeasure = 0;
                    }

                    cword += metaletter.letter;
                    cmeasure += metaletter.measure;
                }
                // there will always be one more word to push.
                awords.push({ "word":cword, "len":cword.length, "measure":cmeasure });
                return awords;
            })(word, maxWidth);

            // could use metawords = metawords.concat(edgwords)
            for (var ew in edgewords)
                metawords.push(edgewords[ew]);
        }
        else {
            metawords.push({ "word":word, "len":word.length, "measure":measure });
        }
    }

    // build array of lines second.
    var cline = "";
    var cmeasure = 0;
    for (var mw in metawords) {
        var metaword = metawords[mw];

        // If current word doesn't fit on current line, push the current line and start a new one.
        // Unless (edge-case): this is a new line and the current word is one character.
        if ((cmeasure + metaword.measure > maxWidth) && cmeasure > 0 && metaword.len > 1) {
            lines.push(cline)
            cline = "";
            cmeasure = 0;
        }

        cline += metaword.word;
        cmeasure += metaword.measure;

        // If there's room, append a space, else push the current line and start a new one.
        if (cmeasure + spacemeasure < maxWidth) {
            cline += " ";
            cmeasure += spacemeasure;
        } else {
            lines.push(cline)
            cline = "";
            cmeasure = 0;
        }
    }
    if (cmeasure > 0)
        lines.push(cline);

    return lines;
}

Performance:
I executed this test on my machine in IE9. Note the assumption of a table called "splittertest" with the columns: Words, MaxWidth, New (ms), Old (ms). The original function is called fragmentText_old in this test.

var tests = [{"twc":50, "tmw":500},
             {"twc":50, "tmw":50},
             {"twc":500, "tmw":500},
             {"twc":500, "tmw":50},
             {"twc":5000, "tmw":500},
             {"twc":5000, "tmw":50},
             {"twc":10000, "tmw":500},
             {"twc":10000, "tmw":50}];
var results = [];

for (var tt in tests) {
    var test = tests[tt];

    var testline = (function(twc) {
        var testwords = [];
        for (var x = 0; x < twc; x++) {
            var len = 3 + Math.floor(Math.random()*11);
            var letters = [];
            for (var y = 0; y < len; y++)
                letters.push(String.fromCharCode("a".charCodeAt() + y));
            testwords.push(letters.join(""));
        }
        return testwords;
    })(test.twc).join(" ");

    var st, dur1, dur2;

    st = new Date().getTime();
    var ss = fragmentText(testline, test.tmw);
    dur1 = new Date().getTime() - st;

    st = new Date().getTime();
    var sso = fragmentText_old(testline, test.tmw);
    dur2 = new Date().getTime() - st;

    results.push("
" + test.twc + "	" + test.tmw + "	" + dur1 + "	" + dur2 + "
");
}

$("#splittertest").append(results.join(""));

The results show mine about twice as fast when there is no chance a word will exceed the maxWidth, and exponentially faster when words frequently exceed the maxWidth.

Words  MaxWidth  New (ms)  Old (ms)
50     500       1         1
50     50        3         5
500    500       3         7
500    50        16        331
5000   500       31        76
5000   50        195       167820 (2.8 mins)
10000  500       60        155
10000  50        337       1121565 (18.7 mins)

It's worth noting that the results are significantly less on subsequent runs in the same browser because of some caching done - probably within the canvas context.


Thread-safe cache using a linked list Are the final templated functions allocate and deallocate thread safe? The Cache object is a thread_local and that also makes FreeList a thread_local, the only parts that I'm still in doubt are the calls to std::malloc and std::free. Are they always thread safe or that depends on the implementation? Is it better to put a lock on them?

I think that the cached memory doesn't need locks since all the objects here are thread_local and each thread has a local copy of it. The only problem really are std::malloc and std::free, are they already synchronized?

Here's a self contained example of all of my code:

#include <iostream>

class FreeList {
    struct Node {
        Node * next;
    };

    Node * this_head;

public:
    static constexpr auto const NODE_SIZE = sizeof(Node);

    FreeList() noexcept
        : this_head() {
    }

    FreeList(FreeList &&) = delete;
    FreeList(FreeList const &) = delete;

    FreeList & operator =(FreeList &&) = delete;
    FreeList & operator =(FreeList const &) = delete;

    void push(void * const address) noexcept {
        auto const head = static_cast<Node *>(address);
        head->next = this_head;
        this_head = head;
    }

    auto pop() noexcept {
        void * const head = this_head;
        if (head) {
            this_head = this_head->next;
        }
        return head;
    }
};

template <uint64_t const SIZE>
class Cache {
    static_assert(SIZE >= FreeList::NODE_SIZE);

    FreeList this_free_list;

public:
    Cache() noexcept
        : this_free_list() {
    }

    Cache(Cache &&) = delete;
    Cache(Cache const &) = delete;

    ~Cache() noexcept {
        while (auto const address = this_free_list.pop()) {
            // Do I need a lock here?
            std::free(address);
        }
    }

    Cache & operator =(Cache &&) = delete;
    Cache & operator =(Cache const &) = delete;

    auto allocate() {
        if (auto const address = this_free_list.pop()) {
            return address;
        }
        // Do I need a lock here?
        if (auto const address = std::malloc(SIZE)) {
            return address;
        }
        throw std::bad_alloc();
    }

    void deallocate(void * const address) noexcept {
        if (address) {
            this_free_list.push(address);
        }
    }
};

template <typename TYPE>
auto & get() noexcept {
    thread_local TYPE local;
    return local;
}

template <typename TYPE>
auto & get_cache() noexcept {
    return get<Cache<sizeof(TYPE)>>();
}

// Are these thread safe?

template <typename TYPE>
auto allocate() {
    auto const address = get_cache<TYPE>().allocate();
    return static_cast<TYPE *>(address);
}

template <typename TYPE>
void deallocate(void * const address) noexcept {
    get_cache<TYPE>().deallocate(address);
}

int main() {

    auto x = allocate<int64_t>();

    *x = 5;

    std::cout << *x << '\n';

    deallocate<int64_t>(x);

}

Thread safety
std::malloc and std::free are thread-safe by themselves... But Freelist and Cache aren't, unless exclusively accessed through allocate or deallocate.
In all other cases some synchronization is needed in FreeList::push and FreeList::pop (or alternatively, Cache::allocate and Cache::deallocate).

There are some options to make those two classes thread-safe for all access paths:

Move get, get_cache, Cache and FreeList into a class as private nested classes / member functions (so they aren't publicly accessible anymore) and make allocate and deallocate a friend of that class. (private/anonymous namespace won't work since that one has to ve just as accessible as allocate/deallocate because it has to reside in a header.)
Why move get and get_cache? Because references and pointers to thread_local objects can be shared with other threads - so a threads might get access to another threads thread_local Cache inside get.
thread_local objects are only thread-safe if no reference or pointer to them gets shared with other threads (which might happen accidentally, e.g. by a mismanaged lambda capture).
This means allocate and deallocate are not thread-safe as long as references to the underlying Cache (via get or get_cache) could be shared by someone else. And since allocate and deallocate have exactly the same level of access as get or get_cache the posted implementation is not thread-safe in the general case.

Add some locking inside FreeList, or make FreeList lock-free by making this_head a std::atomic<Node*>.
This would make the critical section inside Cache::allocate and Cache::deallocate thread-safe as well.

Memory management

Cache::allocate won't provide correctly aligned memory for alignments greater than std::max_align_t (std::malloc is only specified to support alignments to this value). This might cause problems if higher alignments are needed, e.g. for SSE or AVX instructions.
std::aligned_alloc could be used as a replacement. (Beware: std::aligned_alloc isn't available for MSVC yet.)

It isn't possible to create objects whose size is less than sizeof(void*) - so exchanging int64_t for int32_t inside main will fail to compile on 64-bit systems. This could be fixed by always allocating chunks of memory that are at least sizeof(void*) (or FreeList::NODE_SIZE, if you prefer).

Naming

Cache doesn't actually cache objects - only chunks of memory. FreeListAllocator might be a better name.

get is a very generic name. (get_)thread_local_instance or singleton might be more descriptive.

Similar, get_cache might better be get_allocator or get_thread_local_allocator.

General stuff

With some slight modifications Cache could be changed into a standard library compatible std::pmr::memory_resource - which would allow it to be used with standard containers.

If I had to design this, I'd likely make FreeList an adaptor over another allocator (taken as template parameter) who would be asked for memory if the list was empty. This design would allow easy composition of different allocation strategies. There's an excellent talk by Andrei Alexandrescu about this topic.


Transfer of data instead of copy.paste.clear used I am using this code in a worksheet to check the condition, and based on the condition, copying the entire row of values in a different range of particular condition if true.

For copying I am clearing the destination range each time and copying the same data with updated information on the same destination. This makes the code running longer. Can I make the code to copy only the updated cells and merge onto the destination ranges where the old data exists?

Private Sub Worksheet_Change(ByVal Target As Range)
Application.ScreenUpdating = False
If (Target.Row >= 120 And Target.Row < 1400) And (Target.Column >= 1 And Target.Column <= 4) Then
    Dim rngSinglecell As Range
    Dim rngQuantityCells As Range
    Dim intCount As Integer

    Sheets("CE1 Data").Range("K2:S1400").Clear

    Set rngQuantityCells = Sheets("CE1 Data").Range("B120", Range("B120").End(xlDown))

    For Each rngSinglecell In rngQuantityCells

    If rngSinglecell.Value = "Primary" Then

    Range(Range("A" & rngSinglecell.Row), Range("D" & rngSinglecell.Row)).Copy Range("K" & Rows.Count).End(xlUp).Offset(1)

    ElseIf rngSinglecell.Value = "Backup" Then

    Range(Range("A" & rngSinglecell.Row), Range("D" & rngSinglecell.Row)).Copy Range("P" & Rows.Count).End(xlUp).Offset(1)

    End If
Next

End If

Application.ScreenUpdating = True
Application.CutCopyMode = False
End Sub

I think apart from the performance your code also has some other issues. Let me first come to the most problematic, then make some suggestions regarding the performance, and finally make some general comments.

The biggest problem I see here is that procedure also copies functions. This can be very problematic if the references within the formulas are not absolute references. Then they will point somewhere totally different than before.

From the point above, I guess that you are only intending to copy values. In this case, you can avoid using the the rather slow copy function and simply copy the values accessing them via the Value or Value2 property of the cells. (The latter is faster and behaves more reliably, see this question on Stack Overflow.)

To speed up things even somewhat more, you can read the entire range you like to copy into an array via Value2 and then process it. You can also set entire ranges from arrays by setting the Value property of a range. Using arrays is the fastest thing you can do to copy large ranges. (See this blog post testing the various ways to copy the values in ranges in Excel.)

Now, the general comments on the code:

The use of Target in the procedure, or at least its name, is rather confusing. Apparently, it is only used in the condition that is tested and it is never used as a target to copy or the like. It seems as if the check might belong into another procedure calling this one.
Your code will throw an error whenever Sheet(CE1 Data) is not the active sheet. The problem is that in:

Set rngQuantityCells = Sheets(CE1 Data).Range(B120, Range(B120).End(xlDown))

the second Range is not qualified, i.e. it is always implicitly referring to the active sheet. It would be a good practice to always qualify calls to Range, even if it's from ActiveSheet.
If the sheet Sheet(CE1 Data) is not active, the paste range will not be inside the cleared range because the paste range will be on the active sheet. (This obviously only applies after qualifying the offending Range from the second comment.)
You might want to save the worksheet in a variable and not query the Sheets collection all the time. Personally, I would even inject the worksheet to use as a parameter of type Worksheet.
Given that you apparently only use this procedure from the worksheet Sheet(CE1 Data), you might consider using a With statement to access the sheet.
You are using quite a number of magic numbers in the procedure, like the bounds in which Target may be or the explicit ranges. It might be better to use constants or named ranges. If you ever want to change from where this procedure reads or to where it writes, named ranges would make your life easier.

Finally, you might consider to remove most blank lines and indent according to nesting like in:

For Each rngSinglecell In rngQuantityCells
    If rngSinglecell.Value = Primary Then
        Range(Range(A & rngSinglecell.Row), Range(D & rngSinglecell.Row)).Copy Range(K & Rows.Count).End(xlUp).Offset(1)
    ElseIf rngSinglecell.Value = Backup Then
        Range(Range(A & rngSinglecell.Row), Range(D & rngSinglecell.Row)).Copy Range(P & Rows.Count).End(xlUp).Offset(1)
    End If
Next

EDIT:

I did not really realize that you wrote a handler for the worksheet changed event. So, the parameter Target has to be there. However, it would be good practice to separate the two current responsibilities of your handler, to decide what kind of thing to do on a worksheet changed event and to copy over the cells. This can be achieved by extracting everything inside the conditional into its own sub, which preferably should not depend on the active sheet. Then my comments above apply to that sub.

One more thing: Your idea to change only the data that changed has a few issues. Whenever you change a value in column B, you have to rewrite everything because rows will potentially drop out or enter one of the two target lists. Moreover, the Target of the worksheet changed event can contain more then one cell. In this case it might actually be faster to simply copy everything instead of figuring out which row to change in the target lists for every cell in Target.

Considering that Target may contain more than one cell, you might also want to consider whether your condition on Target is correct in all circumstances.


Random Quote in java Problem Statement:

  Create a class diagram and Java code for the following system and
  scenario, taking into account the possibility of future extensions.
  "The system is a command line utility that prints a short 'quote of
  the day' on the user's terminal when run. To begin with the quote is
  selected randomly from a set of hard-coded strings within the program
  itself, but that might change later on -- the quotes might be based on
  the user's history, the time of day, the date, etc.. Scenario:

  User types "java QuoteOfTheDay" on the command line.
  System prints out a quote of the day, with an attribution.

This is my code for the following:

Class Containing the main method

package quoteOfTheDay;
import java.util.Random;

public class QuoteOfTheDay {

    public static void main(String[] args) {
        System.out.println();

        Random rand = new Random();

        System.out.println(Quote.QUOTES[rand.nextInt(Quote.QUOTES.length)]);

    }
}

Quote Class containng the quotes.

    package quoteOfTheDay;

public class Quote {
    public static final String  QUOTES[] = {
            "Be yourself; everyone else is already taken.― Oscar Wilde",
            "A room without books is like a body without a soul. ― Marcus Tullius Cicero",
            "Be the change that you wish to see in the world. ― Mahatma Gandhi",
            "If you tell the truth, you don't have to remember anything. ― Mark Twain",
            "If you want to know what a man's like, take a good look at how he treats his inferiors, not his equals.― J.K. Rowling",
            "To live is the rarest thing in the world. Most people exist, that is all.― Oscar Wilde",
            "Without music, life would be a mistake. ― Friedrich Nietzsche",
            "Always forgive your enemies, nothing annoys them so much. ― Oscar Wilde",
            "Life isn't about getting and having, it's about giving and being. –Kevin Kruse",
            "Whatever the mind of man can conceive and believe, it can achieve. –Napoleon Hill",
            "Strive not to be a success, but rather to be of value. –Albert Einstein",
            };
}

Is this the right approach? Am I missing some things from the problem requirements? I am open for any kind of suggestions.

The using of a public field should be avoided and instead you should use a method to get the value.

If you take into account that the class will be extended (like written in the problem statement), I would suggest that you add a getRandomQuote() method to the Quote class.

Also you should make your String array QUOTES private. I don't know what the conventions for the array braces [] are , but I would write it private static final String[] QUOTES

A Random should be created once and then used as often one needs.So I would suggest to create it at the constructor.

private Random random;
public Quotes(){
    random = new Random();
}

public String getRandomQuote(){
// return your random quote here

}

You should always name your variables and methods in a meaningful easily readable way. So I have renamed rand to random.


Computing the RPY tensor with C++/Eigen (linear algebra) I'm mostly used to writing scientific code in MATLAB / Python / Julia and my experience with C++ is very limited. I've implemented a fairly simple computation of the Rotne-Prager-Yamakawa tensor in dimensionless form using the Eigen library in C++11 (currently using the Visual Studio toolchain).

#include <iostream>
#include <random>
#include <chrono>
#include <Eigen/Dense>

using namespace Eigen;
using namespace std;
using namespace std::chrono;

MatrixXd rotne_prager(Vector3d coords[], double r, const int p)
{
    MatrixXd rpy = MatrixXd::Zero(3 * (p + 1), 3 * (p + 1));
    Vector3d rvec;
    double Rij;
    double distance_ratio;
    for (int i = 0; i < p + 1; i++)
    {
        for (int j = 0; j < p + 1; j++)
        {
            rvec(0) = coords[j](0) - coords[i](0);
            rvec(1) = coords[j](1) - coords[i](1);
            rvec(2) = coords[j](2) - coords[i](2);
            Rij = sqrt(rvec(0)*rvec(0) + rvec(1)*rvec(1) + rvec(2)*rvec(2));
            distance_ratio = r / Rij;
            if (Rij > 2 * r)
            {
                rpy.block<3, 3>(3 * (i + 1) - 3, 3 * (j + 1) - 3) = 0.75 * distance_ratio * (1.0 - 2.0*distance_ratio * distance_ratio) * rvec * rvec.transpose();
                rpy.block<3, 3>(3 * (i + 1) - 3, 3 * (j + 1) - 3).diagonal().array() += 0.75 * distance_ratio * (1.0 + 2.0 / 3.0 * distance_ratio * distance_ratio);
            }
            else
            {
                rpy.block<3, 3>(3 * (i + 1) - 3, 3 * (j + 1) - 3) = 3.0 / 32.0 / distance_ratio * rvec*rvec.transpose();
                rpy.block<3, 3>(3 * (i + 1) - 3, 3 * (j + 1) - 3).diagonal().array() += 1.0 - 9.0 / 32.0 / distance_ratio;
            }
        }
    }
    return rpy;
}

int main()
{
    random_device rd;
    mt19937 gen(rd());
    uniform_real_distribution<> dis(0, 1);
    Eigen::setNbThreads(8);

    auto start = high_resolution_clock::now();

    const int p = 4000;
    Vector3d coords[p + 1];
    for (int i = 0; i < p + 1; i++)
    {
        coords[i](0) = dis(gen); coords[i](1) = dis(gen); coords[i](2) = dis(gen);
    }
    MatrixXd rpy = rotne_prager(coords, 0.01, p);
    auto end = high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
    cout << "p = " << p << ", time elapsed: " << duration << " ms" << endl;
}

The code produces correct results, but I'm sure it could have been written much better. I'd appreciate any performance optimization tips as well as any suggestions about writing more idiomatic (insofar as that term even applies in the C++ world) and concise code.

Using p + 1 instead of just p

You declare

const int p = 4000;

but use p+1 at all the places that matter. I think you should just use

const int p = 4001;

and replace all usages of p + 1 by just p.

Simplify a few expressions

You have repeated usage of 3 * ( i + 1) - 3 and 3 * ( j + 1) - 3. They can simply be 3*i and 3*j.

Give some computations a name

You have the following expressions:

0.75 * distance_ratio * (1.0 - 2.0*distance_ratio * distance_ratio) * rvec * rvec.transpose()

0.75 * distance_ratio * (1.0 + 2.0 / 3.0 * distance_ratio * distance_ratio)

3.0 / 32.0 / distance_ratio * rvec*rvec.transpose()

1.0 - 9.0 / 32.0 / distance_ratio

I don't know that they compute but they compute four different things. It will be easier to understand your code if you can give those computations a name and put them in a function.

double firstTerm(double distance_ratio,
                 Vector3d const& rvec)
{
   return (0.75 * distance_ratio * (1.0 - 2.0*distance_ratio * distance_ratio) * rvec * rvec.transpose());
}

and use it

   rpy.block<3, 3>(3*i, 3*j) = firstTerm(distanc_ratio, recv);

PS I am not suggesting firstTerm as a function name. It just illustrates the concept.

Avoid multiple statements in one line

The line

    coords[i](0) = dis(gen); coords[i](1) = dis(gen); coords[i](2) = dis(gen);

is less readable than:

    coords[i](0) = dis(gen);
    coords[i](1) = dis(gen);
    coords[i](2) = dis(gen);

You could also put them in a for loop to avoid code repetition.

 for ( int j = 0; i < 3; ++j )
    coords[i](j) = dis(gen);

Using const int as an argument type`

I am not a fan of using const int as an argument type. Just int works without any problem. YMMV.

The sqrt line

        Rij = sqrt(rvec(0)*rvec(0) + rvec(1)*rvec(1) + rvec(2)*rvec(2));

can be modified to

double square(double in)
{
    return in*in;
}

Rij = sqrt(square(rvec(0)) + square(rvec(1)) + square(rvec(2));

I think this not only avoids code repetition but also uses the right abstraction in the computation.


Find top two clothing sizes in the array I was recently asked this question in an interview. Here is the solution I came up with. Please let know if I could have done this differently or in a more efficient manner.

The question is as follows:

  Determine The Top Two Clothes Sizes In The Following Array

["XS","S","S","M","L","XL","XLL","XL","XL","M","M","M","XS","XS","XS","XS"]

  The solution should be [ 'XS', 'M' ] since XS occurs 5 times and M
  occurs 4 times.

function determineTopTwo(arr){
let map = {};
let resultArr = [];
let result = [];
for(let i = 0; i < arr.length; i++){
    if(!map[arr[i]]){
        map[arr[i]]=1;
    }else{
        map[arr[i]]++;
    }
}

for(key in map){
    resultArr.push([map[key],key]);
}
let newArr = resultArr.sort((a,b)=>{
    return a[0]-b[0];
});

result.push(newArr[newArr.length-1][1], newArr[newArr.length-2][1]);
return result;
}

You didn't specify if you were allowed to use ecmascript-6 features or not but presumably you were, since you used let and arrow functions. As an interviewer, I would note that you used those features, yet you iterated over the array using a regular for loop instead of using for...of. That isn't necessarily a bad thing since it demonstrates that you know how to increment a counter in a standard loop and then use that for indexing into the array, but you don't have to if you use a for...of loop.

The technique for sorting the array is good, though because Array.prototype.sort() "sorts the elements of an array in place and returns the array"1 there isn't really a need to store the value in newArr because resultArr is sorted.

let newArr = resultArr.sort((a,b)=>{
    return a[0]-b[0];
});

You could have just returned the first two elements of resultArr.

Also, const could have been used for any variable that is never re-assigned - including arrays that merely have elements pushed into them - to avoid accidental re-assignment.

1https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort


OOP, FP and IMP condensed in Rock, Paper and Scissors Rock Paper and Scissors is a pretty basic program.

The reason I wrote this program is because I wanted to see what a small script that used all of the main programming paradigms looked like.

My code contains:

OOP: A Player object.
FP: First class functions : player.intelligence is a function is stored in a variables and I use anonymous lambdas
IMP: The code asks for input freely, asking for input freely in a functional paradigm is not possible, so this is the imperative part.

Tell me if you like it or if you think it is too complex for an easy task and should be simplified.

from collections import namedtuple
import random

RPS = ["rock", "paper", "scissors"]

Player = namedtuple('Player', 'name intelligence')

def rock_paper_scissors(player_1, player_2):
    a, b = player_1.intelligence(), player_2.intelligence()
    print("\n{} chose {}\n{} chose {}\n".format(
        player_1.name, RPS[a-1], player_2.name, RPS[b-1]))
    return "Tie" if a == b else \
      "The winner is " + (player_1.name if (a - b) % 3 == 1 else player_2.name)

def human_intelligence(prompt):
    return RPS.index(input("The Player 1 move: ").lower())+1

def random_ai():
    return random.choice((1,2,3))

Human vs Computer

print(rock_paper_scissors(
    Player("The Human", lambda: human_intelligence("The human's move : ")),
    Player("The Computer", random_ai)
    )
)

Human vs Human

print(rock_paper_scissors(
    Player("The Player 1", lambda: human_intelligence("Player 1 move : ")),
    Player("The Player 2", lambda: human_intelligence("Player 2 move : "))
    )
)

Computer vs Computer

print(rock_paper_scissors(
    Player("The Computer 1", random_ai),
    Player("The Computer 2", random_ai)
    )
)

I'm almost sorry to say, that it feels like you are naming things just because you can name them according to some coding principle.

Calling a named tuple OOP, is stretching it very thin. Yes, it encapsulates something but it doesn't have any options to do actions on the object, and it's not a very good use of it. Could possibly use OOP if you used inheritance for the human player and the computer player incorporating the choice logic.

But then again, that would ruin your so-called FP approach with lambdas and storing of functions. Which again is stretching it rather thin, as you don't use a functional approach avoiding state handling and mathemical functions on lists.

So in the end it is mostly imperative programming, which most paradigms ends up with at some level deep within. And it's imperative programming with a very slight touch of OOP, and a very slight touch of FP.

As this however is Code Review, lets add some review issues as well:

User interface is almost non-existent – You don't provide the user with any information on what to enter, nor do you have error handling of any sort. Only after studying the code intensely I see that you enter either "rock", "paper" or "scissors", which is looked up, incremented, and finally decremented to be displayed back within rock_paper_scissors(). Slightly confusing...
Not the best of variable names – The names RPS, a and b are not according to style guidelines, nor very descriptive.
Neat version to select winner – Simple in code, although undescribed, version to select the winner
Add vertical spacing to rock_paper_scissors() – Instead of everything jammed together, I would love to have a little vertical space to help me distinguish the statements of this function.

To summarize, your script does implement a function to play rock, paper or scissors, but it is, in my opinion, too condensed and should be expanded upon rather than simplified any more.


Putting called delegate into AsyncState parameter - Pros/cons? I have the following interface:

public interface ILogger
{
    void Log(string message, string title, StatusType type, DateTime timestamp);
    IAsyncResult LogAsync(string message, string title, StatusType type, DateTime timestamp, AsyncCallback callback);
    void EndLogAsync(IAsyncResult result);
}

Implemented as a file-based logger...

...

    public FileInfo LogFileInfo { get; internal set; }

    public void Log(string message, string title, StatusType type, DateTime timestamp)
    {
        lock (syncObj)
        {
            CheckLogFileSize(); //rotates LogFileInfo through numbered log files

            using (var stream = LogFileInfo.AppendText())
            {
                stream.WriteLine(GetFormattedString(message, title, type, timestamp));
                stream.Flush();
            }
        }
    }

    public IAsyncResult LogAsync(string message, string title, StatusType type, DateTime timestamp, AsyncCallback callback)
    {
        var action = new Action<string, string, StatusType, DateTime>(Log);
        return action.BeginInvoke(message, title, type, timestamp, callback, action);
    }

    public void EndLogAsync(IAsyncResult result)
    {
        ((Action)result.AsyncState).EndInvoke(result);
    }

Notice the AsyncState parameter of BeginInvoke; I pass the delegate to its own invocation, so that I can reference it again on the flip side to end the invocation using the same delegate reference I called BeginInvoke on.

The questions:

Is it even necessary to keep the actual invoked delegate reference around, or can I simply new up another reference to that method in the EndLogAsync method?
Is this an acceptable use of the AsyncState, given that I have no other use for it?

To answer your question:

you can access the delegate instance by reading ((AsyncResult)asyncResult).AsyncDelegate property (see Executing a Callback Method When an Asynchronous Call Completes section of Calling Synchronous Methods Asynchronously). But it will be easier to cache the instance of the delegate in a readonly field and use it in both methods.
yes, you can use AsyncState however you want, and sometimes people use it for passing the delegate being invoked

Note that you're using a separate thread (on a threadpool) each time you write something to log, so there will be contention between multiple threads if you write to log quickly enough. I would recommend using existing logging frameworks like NLog or log4net to avoid inventing a wheel.


Enum list to STL container Can someone improve upon this function of mine?  EnumToSTLContainer is supposed to make a copy of any STL container whose elements are from a specified enum list.

#include <iostream>
#include <vector>
#include <set>

enum MyEnum {A, B, C, D, E, FirstMyEnum = A, LastMyEnum = E};

template <typename CONTAINER>
CONTAINER EnumToSTLContainer (typename CONTAINER::value_type first, typename CONTAINER::value_type last) {
    CONTAINER v;
    for (int N = first;  N <= last;  N++)
        v.push_back(static_cast<typename CONTAINER::value_type>(N));  // But only works for STL containers with push_back defined.
    return v;
}

int main() {
    const std::vector<MyEnum> enumVector = EnumToSTLContainer<std::vector<MyEnum>> (FirstMyEnum, LastMyEnum);
    for (MyEnum x : enumVector)
        std::cout << x << ' ';  // 0 1 2 3 4
//  const std::set<MyEnum> enumSet = EnumToSTLContainer<std::set<MyEnum>> (FirstMyEnum, LastMyEnum);  // won't compile
}

This only works for STL containers with push_back() defined, and need to specify first and last element of the enum list. It does not work if enum values are not consecutive.

Perhaps obtaining an initializer_list using variadic templates would work, which can then return the desired STL container?

First of all, you should use std::underlying_type_t<Cont::value_type> instead of int and please don't use UPPER for template parameters (UPPER is mostly for preprocessor, sometimes used for constants and/or static variables), rather use PascalCasing, e.g. Container.

Your implementation looks good to me otherwise, but you know it can only be used with containers with member push_back. If you want to create it from initializer_list, then it would be something different (e.g. EnumRangeInitList). You may find some inspiration in std::integer_sequence.


Determining if a sequence is a palindrome To complement this Java question on palindrome identification, I came up with this C++(14) version:

#include <iterator>
#include <algorithm>
#include <functional>

namespace detail
{
    template <typename RandomIt, typename BinaryPredicate>
    bool is_palindrome(RandomIt first, RandomIt last, BinaryPredicate pred,
                       std::random_access_iterator_tag)
    {
        return std::equal(first, std::next(first, std::distance(first, last) / 2),
                          std::make_reverse_iterator(last), pred);
    }

    template <typename BidirIt, typename BinaryPredicate>
    bool is_palindrome(BidirIt first, BidirIt last, BinaryPredicate pred,
                       std::bidirectional_iterator_tag)
    {
        if (first == last || first == --last) return true;

        for (; first != last; ++first, --last) {
            if (!pred(*first, *last)) return false;
            if (std::next(first) == last) break;
        }

        return true;
    }
} // namespace detail

template <typename BidirIt, typename BinaryPredicate>
bool is_palindrome(BidirIt first, BidirIt last, BinaryPredicate pred)
{
    return detail::is_palindrome(first, last, pred,
                                 typename std::iterator_traits<BidirIt>::iterator_category {});
}

template <typename BidirIt>
bool is_palindrome(BidirIt first, BidirIt last)
{
    using V = typename std::iterator_traits<BidirIt>::value_type;
    return detail::is_palindrome(first, last,
                                 std::equal_to<V> {},
                                 typename std::iterator_traits<BidirIt>::iterator_category {});
}

template <typename SequenceType, typename BinaryPredicate>
bool is_palindrome(const SequenceType& sequence, BinaryPredicate pred)
{
    return is_palindrome(std::cbegin(sequence), std::cend(sequence), pred);
}

template <typename SequenceType>
bool is_palindrome(const SequenceType& sequence)
{
    return is_palindrome(std::cbegin(sequence), std::cend(sequence));
}

Used as such:

#include <iostream>
#include <string>
#include <list>

int main()
{
    std::cout << std::boolalpha;
    std::string str {"abba"};
    std::cout << is_palindrome(str) << std::endl;
    std::list<char> lst {str.cbegin(), str.cend()};
    std::cout << is_palindrome(lst) << std::endl;
    return 0;
}

Performance is my primary concern here. Comments and suggested improvements are welcome!

Following is my solution. It's much less code. It also handles the case of string literals correctly (e.g., is_palindrome("aba")).

In modern C++ (11 and onward), there is no need to differentiate predicate and non-predicate versions of generic algorithms. The fact that the standard library does overload predicate and non-predicate versions is simply due to historical reasons. See this S.O. topic for details.

#include <functional>
#include <iterator>
#include <utility>

template <typename Iterator, typename Pred = std::equal_to<void>>
bool is_palindrome(Iterator beg, Iterator end, Pred pred = Pred{}) {
  if (beg == end) return true;
  end = std::prev(end);
  if (beg == end) return true;
  do {
    if (! pred(*beg++, *end--)) return false;
  }
  while (beg != end && beg != std::next(end));
  return true;
}

template <typename T, typename Pred = std::equal_to<void>>
bool is_palindrome(const T& x, Pred pred = Pred{}) {
  return is_palindrome(std::begin(x), std::end(x), std::move(pred));
}

template <std::size_t n, typename Pred = std::equal_to<void>>
bool is_palindrome(const char (&x)[n], Pred pred = Pred{}) {
  return is_palindrome(x, x + n - 1, std::move(pred));
}


Executing functions and declaring flags with a long battery of if conditions I'm only asking because almost the entire code base I've inherited here, in C# and PHP, looks like this:

if (varOne == flag) {
    run_some_sql();
    set_some_flag = true;
}

if (varTwo == flag) {
    run_some_sql();
    set_some_flag = true;
}

if (varThree == flag) {
    run_some_sql();
    set_some_flag = true;
}

if (varFour == flag) {
    run_some_sql();
    set_some_flag = true;
}

if (varFive == flag) {
    run_some_sql();
    set_some_flag = true;
}

if (varSix == flag) {
    run_some_sql();
    set_some_flag = true;
}

if (varSeven == flag) {
    run_some_sql();
    set_some_flag = true;
}

if (varEight == flag) {
    run_some_sql();
    set_some_flag = true;
}

For about ten thousand lines.

I haven't lost my mind, right?  Is this bad? There's only about five loops in the entire code base of about 50,000 lines.

I would normally go about this sort of thing by storing the data into an associated array, and loop over that, rather than adding a new if statement for every variable.

Have I totally lost my mind? Eight people worked on this before me, and I'm seriously worried here. Is there ever a good reason to do this sort of thing?

This is bad.  Very bad.

It appears the original implementer doesn't quite understand arrays.  You should definitely refactor this.  Michael K's answer has the right approach.  In C# syntax:

// Hopefully these variables are already in an array or list already, otherwise:
MyType[] myVariables = new MyType[] { varOne, varTwo, /* ... */ varEight };

foreach (MyType variable in myVariables)
{
    if (variable == flag)
    {
        run_some_sql();
        set_some_flag = true;
    }
}

Note that if run_some_sql() only needs to be executed once, you can break out early and save some computation time:

foreach (MyType variable in myVariables)
{
    if (variable == flag)
    {
        run_some_sql();
        set_some_flag = true;

        break;
    }
}

If it is the case that you only need to execute run_some_sql() once, you can make the code even simpler using new LINQ syntax:

if (myVariables.Any(v => v == flag))
{
    run_some_sql();
    set_some_flag = true;
}

While refactoring, I'd also recommend choosing some better variable names than varOne, varTwo, flag, etc.  Though I assume these are just your examples. :)


Preload content in StageWebView I would like to get some feedback on my AS3 code below. It's for an Adobe Air mobile app to preload a website in a StageWebView container.
That container will be moved on screen later in the app process. My goal is to show the website content to the user as fast as possible.

// OFF SCREEN - PRELOAD
var webView:StageWebView = new StageWebView();
webView.stage = this.stage;
webView.viewPort = new Rectangle( -5000, 0, stage.stageWidth, stage.stageHeight);
webView.loadURL("http://www.example.com/foobar.php");

// ONSCREEN
function showWeb(e:Event=null){
webView.viewPort = new Rectangle( 0, 0, stage.stageWidth, stage.stageHeight);
}

btn.addEventListener(MouseEvent.CLICK,  showWeb)

Is there something I could do better?
I'm using Adobe Air 3.6 and Flash CS6.

Thank yoo

I don't think there's anything that can be improved to your approach.

Minor improvements do apply;

function showWeb(e:Event=null){
webView.viewPort = new Rectangle( 0, 0, stage.stageWidth, stage.stageHeight);
}

could use some indentation,

btn.addEventListener(MouseEvent.CLICK,  showWeb)

contains a double space and is missing a semicolon.

But I don't think it's possible to preload the StageWebView via some function.

What you DO want to take care of is any errors that might be thrown your way.

For that, add a listener: (code from this SO answer)

webView.addEventListener(ErrorEvent.ERROR, onError);
function onError(e:ErrorEvent):void
{
    trace("Page is not available.");
}


Method for get base URI How can I improve the following code?

private const string OAuthTokenUri = "oauth2/token";

private static string GetOAuthTokenUri(string uriAddress)
{
   var uri = new Uri(uriAddress);
   var baseUri = uri.GetLeftPart(UriPartial.Authority);
   var s = new Uri(new Uri(baseUri), OAuthTokenUri);
   return s.ToString();
}

I call GetOAuthTokenUri() like:

var oauthTokenUri = GetOAuthTokenUri("http://www.example.com/mypage/default.aspx");

As a result I'm getting

http://www.example.com/oauth2/token

Please help to improve GetOAuthTokenUri

Maybe you can do it like this:

private const string OAuthTokenUri = "/oauth2/token";

private static string GetOAuthTokenUri(string uriAddress)
{
   Uri result = null;
   return Uri.TryCreate(new Uri(uriAddress), OAuthTokenUri, out result) ? result.ToString() : string.Empty;
}

Please note the slash I have added to OAuthTokenUri.


Measure a given method's execution time - follow-up A long time ago, I've written a method that would allow me to measure the amount of time a method takes to run. I've decided to tweak this method and make use of TPL since measuring a method may take some time.

public static class ComparableUtils
{
    public static T Min<T>(this T t1, T t2)where T:IComparable
    {
        if (t1.CompareTo(t2) <= 0)
        {
            return t1;
        }
        return t2;
    }

    public static T Max<T>(this T t1, T t2) where T : IComparable
    {
        if (t1.CompareTo(t2) >= 0)
        {
            return t1;
        }
        return t2;
    }
}
public static class TestUtils
{
    private static readonly Stopwatch Watch = new Stopwatch();

    //This determines a minimum amount of iterations needed to perform to get a significative time measurment
    private static Task<int> GetIterations(Action action)
    {
        return Task.Run(() =>
        {
            const int minimumTime = 20;
            int iterations = 0;
            Watch.Start();
            while (Watch.Elapsed.Milliseconds < minimumTime)
            {
                action();
                ++iterations;
            }
            return iterations;
        });
    }

    private static TimeSpan MeasureTime(Action action, int iterations)
    {
        Watch.Restart();
        while (iterations-- > 0)
        {
            action();
        }
        Watch.Stop();
        return Watch.Elapsed;
    }

    public static Task<Time> Measure(Action action, int? iterations = null, int times = 1)
    {
        return Task.FromResult(iterations)
            .ContinueWith(async t => t.Result.GetValueOrDefault(await GetIterations(action)))
            .Unwrap()
            .ContinueWith(t =>
            {
                var iters = t.Result;
                TimeSpan timeTaken = TimeSpan.MaxValue;
                for (int i = 0; i < times; ++i)
                {
                    timeTaken = MeasureTime(action, iters).Min(timeTaken);
                }
                return new Time(timeTaken.Ticks*100/iters);
            });
    }
}

public class Time
{
    private readonly long _nanoSeconds;
    public Time(long nanoSeconds)
    {
        _nanoSeconds = nanoSeconds;
    }

    public override string ToString()
    {
        if (_nanoSeconds < 9999)
        {
            return _nanoSeconds.ToString()+"ns";
        }
        return new TimeSpan(_nanoSeconds / 100).ToString("g");
    }
}

Is this a well conducted measurement algorithm? Is there something that is amiss?

while (Watch.Elapsed.Milliseconds < minimumTime)

It probably won't affect this code, but Milliseconds doesn't do what you probably think it does. I think you want TotalMilliseconds.

public static Task<Time> Measure(Action action, int? iterations = null, int times = 1)
{
    return Task.FromResult(iterations)
        .ContinueWith(async t => t.Result.GetValueOrDefault(await GetIterations(action)))
        .Unwrap()
        .ContinueWith(t =>
        {
            var iters = t.Result;
            TimeSpan timeTaken = TimeSpan.MaxValue;
            for (int i = 0; i < times; ++i)
            {
                timeTaken = MeasureTime(action, iters).Min(timeTaken);
            }
            return new Time(timeTaken.Ticks*100/iters);
        });
}

Generally speaking, if you can use await, you don't need ContinueWith().
What's the point of using Task.FromResult().ContinueWith()? Task.Run() would make much more sense here.
There is actually no reason to use Task and async-await here. You should use that only for truly asynchronous IO operations. If the caller wants to run your long-running CPU-bound code on a separate thread, they can easily do it themselves.
For performance-related code, it feels weird that you're calling GetIterations() even when it's not needed.


Improving a Cheese Filter loading in C# Let's say that i have a database which contain cheese. I love cheese.
Depending on the request my server is getting (c# WebApi), i have to filter user data accordingly.
Maybe the user wants to only get cheese up to a certain date, or from a certain date, or between to dates. Maybe he wants all french cheese, or american cheese.
My model works, but i dont like switchs, and i feel like there is a better way.

The model is as follow :

namespace myAPI.Models
{
    public enum CheeseFilter
    {
        Country,
        DateFrom,
        DateStart,
        DateBetween,
    };

    public class FilterQuery
    {
        public CheeseFilter? filter { get; set; }
        public DateTime? DateStart{ get; set; }
        public DateTime? DateEnd{ get; set; }
        public String Country{ get; set; }

    }
}

This model is what's get filled [FromPost]
Now, i'm creating a tuple which will hold the StoredProcedure name (Basically, a select with where, order by, etc), its parameters, and the choosen filter, like so :

       private Tuple<CheeseFilter, String, List<SqlParameter>> LoadedCheeseWithOptions;

And where i actually fill it :

public bool CheeseFilterTuple()
        {
            bool flag = false;
            List<SqlParameter> options = new List<SqlParameter>();
            String SPName = "ERROR";
            DateTime tmp = new DateTime(); // ForChecking GoodFormating of datetimes
            DateTime tmp2 = new DateTime();
            switch (GetMode().Value)
            {
                case CheeseFilter.DateFrom:
                    flag = !String.IsNullOrWhiteSpace(dateStart) && DateTime.TryParseExact(dateStart, TMP_DATEFORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None, out tmp);;
                    options.Add( new SqlParameter() { Name =  "@DateStart", Value = tmp.ToString("yyyyMMdd")});
                    SPName = "Cheese_FromDate";
                    break;
                case CheeseFilter.DateStart:
                    flag = !String.IsNullOrWhiteSpace(dateEnd) && DateTime.TryParseExact(dateEnd, TMP_DATEFORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None, out tmp);
                    options.Add(new SqlParameter() { Name = "@DateEnd", Value = tmp.ToString("yyyyMMdd") });
                    SPName = "Cheese_To_Date";
                    break;
                case CheeseFilter.BetweenDates:
                    flag = !String.IsNullOrWhiteSpace(dateStart) && DateTime.TryParse(dateStart, out tmp) && !String.IsNullOrWhiteSpace(dateEnd) && DateTime.TryParse(dateEnd, out tmp2);
                    options.Add( new SqlParameter() { Name = "@DateStart",Value =  tmp.ToString("yyyyMMdd")}); //Converting for sqlServer
                    options.Add( new SqlParameter() { Name = "@DateEnd", Value = tmp2.ToString("yyyyMMdd")});
                    SPName = "Cheese_Between_Date";
                    break;

            }
            LoadedCheeseWithOptions = new Tuple<CheeseFilter, string, List<SqlParameter>>(GetMode().Value, SPName, options);
            return flag;
        }

GetMode() is just transforming the CheeseFilter? into a CheeseFilter.

The main issue is that, with this last bit of code here, i feel like with every new filter that I might get asked to create will mean adding another block of code to the pile, which I think is a poor man's solution.

So I'm asking you for some guidelines, or even better ways that'd you handle better this optional filter loading.

Your code is really hard to follow. It reads and modifies a lot of local fields/properties that are somewhere hidden. I tried to refactor it but it's still buggy I believe as some parameters are unclear. Nevertheless it should give you an idea how to improve it.

Using Tuple is a quick and dirty way to test something because you almost instantly forget what the properties are for as they are simply named ItemX. If you plan to use this code longer then just for experiments I'd use a real class.

You should pass all the parameters that the function needs instead reading them from the some fields or properties... unless it's a part of some class which we don't know.

In particular you could create filter criteria for passing the parameters and return a cheese filter as a result.

You don't need to check the date string for null/empty, the TryParse won't throw on null, that's what it is for.

Work on your variable names. tmp, tmp2 are not good at all. Give them real names, like dateStart or dateEnd or even tmpDateStart but just tmp isn't good enough.

Here's an example that I managed to piece together:

public class FilterCriteria
{
    public CheeseFilter? filter { get; set; }
    public string DateStart { get; set; }
    public string DateEnd { get; set; }
    public String Country { get; set; }
}

class CheeseFilter
{
    public FilterCriteria Criteria { get; set; }
    public string SPName { get; set; }
    public List<SqlParameter> SqlParameters { get; set; }
}

public CheeseFilter CreateCheeseFilter(FilterCriteria filterCriteria)
{
    var isValidDateFormat = false;
    var sqlParameters = new List<SqlParameter>();
    var SPName = "ERROR";

    var dateStart = new DateTime(); // ForChecking GoodFormating of datetimes
    var dateEnd = new DateTime();

    switch (GetMode().Value)
    {
        case CheeseFilter.DateFrom:
            isValidDateFormat = DateTime.TryParseExact(filterCriteria.DateStart, TMP_DATEFORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None, out tmp);;
            if (!isValidDateFormat) retrun null;

            sqlParameters.Add(new SqlParameter() { Name =  "@DateStart", Value = tmp.ToString("yyyyMMdd")});
            SPName = "Cheese_FromDate";
            break;

        case CheeseFilter.DateStart:
            isValidDateFormat = DateTime.TryParseExact(filterCriteria.DateStart, TMP_DATEFORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None, out tmp);
            if (!isValidDateFormat) retrun null;

            sqlParameters.Add(new SqlParameter() { Name = "@DateEnd", Value = tmp.ToString("yyyyMMdd") });
            SPName = "Cheese_To_Date";
            break;

        case CheeseFilter.BetweenDates:
            isValidDateFormat =
                DateTime.TryParse(filterCriteria.DateStart, out dateStart) &&
                DateTime.TryParse(filterCriteria.DateEnd, out dateEnd);
            if (!isValidDateFormat) retrun null;

            sqlParameters.Add( new SqlParameter() { Name = "@DateStart",Value =  tmp.ToString("yyyyMMdd")}); //Converting for sqlServer
            sqlParameters.Add( new SqlParameter() { Name = "@DateEnd", Value = tmp2.ToString("yyyyMMdd")});
            SPName = "Cheese_Between_Date";
            break;

    }

    return new CheeseFilter
    {
        Criteria = GetMode().Value
        SPName = SPName
        SqlParameters = options
    };
}


Listing words from text, provide lines where appears, count them I applied for Junior Java Developer in some company.
Got a task:"Listing words (without duplicates) from text, provide lines where appears, count them."
Output should looks like:

Alphacoronavirus - 3 - pozycje -> [1,3,2]

gatunki - 4 - pozycje -> [1,3,2,7]

Koronawirusy - 2 - pozycje -> [3,2]

Wirusów - 1 - pozycje -> [1]

Did not receive any feedback form them for two weeks so i will ask for judgment here.
Waiting for roast

Data structure:

import java.util.ArrayList;
import java.util.List;

public class PatternStats implements Comparable<PatternStats>{
    private String word;
    private int amountOfAppearances = 1;
    private List<Integer> linesContains = new ArrayList<>();

    public PatternStats(String word){
        this.word = word;
    }

    public String getWord() {
        return word;
    }

    public int getAmountOfAppearances() {
        return amountOfAppearances;
    }

    public List<Integer> getLinesContains() {
        return linesContains;
    }

    public void increaseAOA(){
        this.amountOfAppearances++;
    }

    public void addLineToList(int lineNO){
        this.linesContains.add(lineNO);
    }

    @Override
    public int compareTo(PatternStats o) {
        int compareInt = this.word.toLowerCase().compareTo(o.word.toLowerCase());
        if(compareInt < 0) return -1;
        if(compareInt > 0) return  1;
        return 0;
    }
}

WordLister

import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WordListingWithMap {

    private Map<String, PatternStats> patternStatsMap = new HashMap<>();

    public List<PatternStats> listWords(String filePath) {
        patternStatsMap.clear();
        String regex = "\\b[^\\d\\P{L}]+\\b";
        try {
            FileInputStream fis = new FileInputStream(filePath);
            Scanner sc = new Scanner(fis);
            scanTextCollectWords(sc, regex);
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<PatternStats> patternStats = new ArrayList<>(patternStatsMap.values());
        Collections.sort(patternStats);
        return patternStats;
    }

    private void scanTextCollectWords(Scanner sc, String regex) {
        int lineCounter = 0;
        while (sc.hasNextLine()){
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(sc.nextLine());
            lineCounter++;
            while (m.find()) {
                if (patternStatsMap.containsKey(m.group(0))) {
                    increaseExist(m.group(0), lineCounter);
                } else {
                    createNewAddToMap(m.group(0), lineCounter);
                }
            }
        }
    }

    private void createNewAddToMap(String word, int line) {
        PatternStats tempPatternStats = new PatternStats(word);
        tempPatternStats.addLineToList(line);
        patternStatsMap.put(word, tempPatternStats);
    }

    private void increaseExist(String word, int line) {
        if (!patternStatsMap.get(word).getLinesContains().contains(line))
            patternStatsMap.get(word).addLineToList(line);

        patternStatsMap.get(word).increaseAOA();
    }
}

and Main

import java.util.List;

public class Main {

    public static void main(String[] args) {
        final String filePatch = "C:\\vaTast\\src\\zadanie.txt";

        WordListingWithMap wlwm = new WordListingWithMap();
        toPrint = wlwm.listWords(filePatch);
        for (PatternStats each : toPrint){
            System.out.println(each.getWord() + " - " +
                    each.getAmountOfAppearances() + " - pozycje - > " +
                    each.getLinesContains());
        }
    }
}

repo: https://github.com/krukarkonrad/vaRepo/

Your code and output are correct, for me there is a hint in the description of the task :

  Listing words (without duplicates) from text, provide lines where
  appears, count them.

For me the words without duplicates mean that a structure like Set well adapts to the constraint so instead of:

public class PatternStats implements Comparable<PatternStats>{
    private String word;
    private int amountOfAppearances = 1;
    private List<Integer> linesContains = new ArrayList<>();
}

you could define the PatternStats class the following way:

public class PatternStats implements Comparable<PatternStats>{
    private int amountOfAppearances;
    private SortedSet<Integer> linesContains;
    private String word;

    public PatternStats(String word){
        this.amountOfAppearances = 1;
        this.linesContains = new TreeSet<>();
        this.word = word;
    }

    ...other methods
}

Your comparing method:

@Override
public int compareTo(PatternStats o) {
    int compareInt = this.word.toLowerCase().compareTo(o.word.toLowerCase());
    if(compareInt < 0) return -1;
    if(compareInt > 0) return  1;
    return 0;
}

can be rewritten in this way using compareToIgnoreCase:

@Override
public int compareTo(PatternStats o) {
    return word.compareToIgnoreCase(o.word);
}

You can override the toString method returning the output you expect so your class can be rewritten in this way :

PatternStats.java

public class PatternStats implements Comparable<PatternStats>{
    private int amountOfAppearances;
    private SortedSet<Integer> linesContains;
    private String word;

    public PatternStats(String word){
        this.amountOfAppearances = 1;
        this.linesContains = new TreeSet<>();
        this.word = word;
    }

    public String getWord() {
        return word;
    }

    public int getAmountOfAppearances() {
        return amountOfAppearances;
    }

    public SortedSet<Integer> getLinesContains() {
        return linesContains;
    }

    public void increaseAOA(){
        ++amountOfAppearances;
    }

    public void addLineToSet(int lineNO){
        this.linesContains.add(lineNO);
    }

    @Override
    public int compareTo(PatternStats o) {
        return word.compareToIgnoreCase(o.word);
    }

    @Override
    public String toString() {
        return String.format("%s - %d - pozycje - > %s", word, amountOfAppearances, linesContains);
    }

}

In your class WordListingWithMap you are reading a file line by line compiling and using the same regex for every line to match words: you can compile the regex one time like below:

public class WordListingWithMap {
    private static final String REGEX = "\\b[^\\d\\P{L}]+\\b";
    private static final Pattern PATTERN = Pattern.compile(REGEX);
    private int lineCounter;
    private Map<String, PatternStats> patternStatsMap;

    public WordListingWithMap() {
        this.patternStatsMap = new HashMap<>();
        this.lineCounter = 1;
    }

    ...other methods
}

Instead of reading a file using a FileInputStream you can use the Files class to make the code shorter like below:

WordListingWithMap.java

public class WordListingWithMap {
    private static final String REGEX = "\\b[^\\d\\P{L}]+\\b";
    private static final Pattern PATTERN = Pattern.compile(REGEX);
    private int lineCounter;
    private Map<String, PatternStats> patternStatsMap;

    public WordListingWithMap() {
        this.patternStatsMap = new HashMap<>();
        this.lineCounter = 1;
    }

    public List<PatternStats> listWords(String filePath) {
        try(Stream<String> lines = Files.lines(Paths.get(filePath))) {
            lines.forEach(l -> scanTextCollectWords(l, lineCounter++));
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<PatternStats> patternStats = new ArrayList<>(patternStatsMap.values());
        Collections.sort(patternStats);
        return patternStats;
    }

    private void scanTextCollectWords(String line, int lineCounter) {
        Matcher m = PATTERN.matcher(line);

        while (m.find()) {
            String word = m.group(0);
            if (patternStatsMap.containsKey(word)) {
                increaseExist(word, lineCounter);
            } else {
                createNewAddToMap(word, lineCounter);
            }
        }
    }

    private void createNewAddToMap(String word, int line) {
        PatternStats tempPatternStats = new PatternStats(word);
        tempPatternStats.addLineToSet(line);
        patternStatsMap.put(word, tempPatternStats);
    }

    private void increaseExist(String word, int line) {
        patternStatsMap.get(word).addLineToSet(line);
        patternStatsMap.get(word).increaseAOA();
    }
}

Your Main class can be rewritten in this way:

Main.java

public class Main {

    public static void main(String[] args) {
        final String filePath = "zadanie.txt";

        WordListingWithMap wlwm = new WordListingWithMap();
        wlwm.listWords(filePath).forEach(System.out::println);
    }
}


Tic-tac-toe in python with OOP I'm a beginner to intermediate in programming, and created a Tic-tac-toe game in python. I plan to add an AI player and a GUI using pygame.
Any improvements I could make to the code, especially with the logic, or just formatting in general?
my_board = [
    ["1", "2", "X"],
    ["4", "5", "6"],
    ["7", "8", "9"]
]

class Tictactoe():
  def __init__(self, board):
    self.board = board

  def print_board(self):
    print("|-------------|")
    print("| Tic Tac Toe |")
    print("|-------------|")
    print("|             |")
    print("|    " + self.board[0][0] + " " + self.board[0][1] + " " + self.board[0][2] + "    |")
    print("|    " + self.board[1][0] + " " + self.board[1][1] + " " + self.board[1][2] + "    |")
    print("|    " + self.board[2][0] + " " + self.board[2][1] + " " + self.board[2][2] + "    |")
    print("|             |")
    print("|-------------|")
    print()

  def available_moves(self):
    moves = []
    for row in self.board:
      for col in row:
        if col != "X" and col != "O":
          moves.append(int(col))
    return moves

  def select_space(self, move, turn):
    row = (move-1)//3
    col = (move-1)%3
    self.board[row][col] = "{}".format(turn)

  def has_won(self, player):
    for row in self.board:
        if row.count(player) == 3:
            return True
    for i in range(3):
        if self.board[0][i] == player and self.board[1][i] == player and self.board[2][i] == player:
            return True
    if self.board[0][0] == player and self.board[1][1] == player and self.board[2][2] == player:
        return True
    if self.board[0][2] == player and self.board[1][1] == player and board[2][0] == player:
        return True
    return False

  def game_over(self):
    self.available_moves()
    if self.has_won("X") or self.has_won("O") or len(self.available_moves()) ==0:
      return True
    else:
      return False

  def get_player_move(self, turn):
    move = int(input("Player {player} make your turn: ".format(player=turn)))
    self.available_moves()
    while move not in range (1,10) or move not in self.available_moves():
      move = int(input("Invalid move, try again: "))
    return move

def game(board):
  tictactoe = Tictactoe(my_board)
  while not tictactoe.game_over():
    tictactoe.print_board()
    x_move = tictactoe.get_player_move("X")
    tictactoe.select_space(x_move,"X")
    tictactoe.print_board()
    if tictactoe.game_over():
      break

    o_move = tictactoe.get_player_move("O")
    tictactoe.select_space(o_move,"O")
  if tictactoe.has_won("X"):
    print("X wins")
  elif tictactoe.has_won("O"):
    print("O wins")
  else:
    print("tie")

game(my_board)

Indents
PEP 8: Use 4 spaces per indentation level.

Main game loop
The way your game loop is set up now is a bit unelegant. You already implemented all the methods to be able to handle both players, there's only one piece missing:
from itertools import cycle

players = cycle(['X', 'O'])

cycle will provide a generator that infinitely repeats the iterable you pass it. This makes the loop quite a bit cleaner:
while not tictactoe.game_over():
    tictactoe.print_board()

    player = next(players)
    move = tictactoe.get_player_move(player)
    tictactoe.select_space(move, player)

I'd also suggest renaming select_space to something like do_move. Makes it a bit clearer what's going on.

Redundant calls to Tictactoe.available_moves()
In game_over and get_player_move you call self.available_moves() once without using the return value in any way. You can simply delete those lines.

game_over
The pattern
if self.has_won("X") or self.has_won("O") or len(self.available_moves()) ==0:
    return True
else:
    return False

can be simplified to
return self.has_won("X") or self.has_won("O") or len(self.available_moves()) == 0

What you were doing is basically manually returning the resulting bool value of a condition. We can instead simply return the condition directly.

print_board
Python lets you easily avoid an unelegant pattern
print("|    " + self.board[0][0] + " " + self.board[0][1] + " " + self.board[0][2] + "    |")

by using the * operator for unpacking an iterable
print("|   ", *self.board[0], "   |")

Since we need to do this for all rows in self.board we should let Python handle it for us as well:
for row in self.board:
    print("|   ", *row, "   |")

has_won
For a cleaner implementation of this method I would suggest implementing helper functions that provide lists of the rows, columns and diagonals of the board. They might also be useful for future feature additions.
def rows(self):
    return self.board[:]  # creates a mutable copy of the rows

def columns(self):
    return [[row[index] for row in self.board] for index in range(3)]

def diagonals(self):
    first = [self.board[index][index] for index in range(3)]
    second = [self.board[index][len(self.board[index]) - index - 1] for index in range(3)]
    return [first, second]

These methods are also ready to be used for boards of different sizes. Simply replace the 3s by a variable.
has_won is now a lot simpler and more readable:
def has_won(self, player):
    for line in self.rows() + self.columns() + self.diagonals():
        symbols = set(line)
        if player in symbols and len(symbols) == 1:
            return True

    return False

We can take this a step further (as pointed out in the comments) and change has_won to get_winner and return the winning symbol. This will also affect some other parts of your code:
class Tictactoe:
def get_winner(self):
    for line in self.rows() + self.columns() + self.diagonals():
        symbols = set(line)
        if len(symbols) == 1:
            return symbols.pop()

    return None

def game_over(self):
    return self.get_winner() is not None or len(self.available_moves()) == 0

Printing our winner in game:
def game(...):

    # main gameplay here

    if (winner := self.get_winner()) is not None:
        print(f"{winner} wins")
    else:
        print("tie")


Finding all k-subset partitions The following code generates all \$k\$-subsets of a given array. A \$k\$-subset of set \$X\$ is a partition of all the elements in \$X\$ into \$k\$ non-empty subsets.

Thus, for {1,2,3,4} a 3-subset is {{1,2},{3},{4}}.

I'm looking for improvements to the algorithm or code. Specifically, is there a better way than using copy.deepcopy? Is there some itertools magic that does this already?

import copy
arr = [1,2,3,4]

def t(k,accum,index):
    print accum,k
    if index == len(arr):
        if(k==0):
            return accum;
        else:
            return [];

    element = arr[index];
    result = []

    for set_i in range(len(accum)):
        if k>0:
            clone_new = copy.deepcopy(accum);
            clone_new[set_i].append([element]);
            result.extend( t(k-1,clone_new,index+1) );

        for elem_i in range(len(accum[set_i])):
            clone_new = copy.deepcopy(accum);
            clone_new[set_i][elem_i].append(element)
            result.extend( t(k,clone_new,index+1) );

    return result

print t(3,[[]],0);

A very efficient algorithm (Algorithm U) is described by Knuth in the Art of Computer Programming, Volume 4, Fascicle 3B to find all set partitions with a given number of blocks.  Your algorithm, although simple to express, is essentially a brute-force tree search, which is not efficient.

Since Knuth's algorithm is not very concise, its implementation is lengthy as well.  Note that the implementation below moves an item among the blocks one at a time and need not maintain an accumulator containing all partial results.  For this reason, no copying is required.

def algorithm_u(ns, m):
    def visit(n, a):
        ps = [[] for i in xrange(m)]
        for j in xrange(n):
            ps[a[j + 1]].append(ns[j])
        return ps

    def f(mu, nu, sigma, n, a):
        if mu == 2:
            yield visit(n, a)
        else:
            for v in f(mu - 1, nu - 1, (mu + sigma) % 2, n, a):
                yield v
        if nu == mu + 1:
            a[mu] = mu - 1
            yield visit(n, a)
            while a[nu] > 0:
                a[nu] = a[nu] - 1
                yield visit(n, a)
        elif nu > mu + 1:
            if (mu + sigma) % 2 == 1:
                a[nu - 1] = mu - 1
            else:
                a[mu] = mu - 1
            if (a[nu] + sigma) % 2 == 1:
                for v in b(mu, nu - 1, 0, n, a):
                    yield v
            else:
                for v in f(mu, nu - 1, 0, n, a):
                    yield v
            while a[nu] > 0:
                a[nu] = a[nu] - 1
                if (a[nu] + sigma) % 2 == 1:
                    for v in b(mu, nu - 1, 0, n, a):
                        yield v
                else:
                    for v in f(mu, nu - 1, 0, n, a):
                        yield v

    def b(mu, nu, sigma, n, a):
        if nu == mu + 1:
            while a[nu] < mu - 1:
                yield visit(n, a)
                a[nu] = a[nu] + 1
            yield visit(n, a)
            a[mu] = 0
        elif nu > mu + 1:
            if (a[nu] + sigma) % 2 == 1:
                for v in f(mu, nu - 1, 0, n, a):
                    yield v
            else:
                for v in b(mu, nu - 1, 0, n, a):
                    yield v
            while a[nu] < mu - 1:
                a[nu] = a[nu] + 1
                if (a[nu] + sigma) % 2 == 1:
                    for v in f(mu, nu - 1, 0, n, a):
                        yield v
                else:
                    for v in b(mu, nu - 1, 0, n, a):
                        yield v
            if (mu + sigma) % 2 == 1:
                a[nu - 1] = 0
            else:
                a[mu] = 0
        if mu == 2:
            yield visit(n, a)
        else:
            for v in b(mu - 1, nu - 1, (mu + sigma) % 2, n, a):
                yield v

    n = len(ns)
    a = [0] * (n + 1)
    for j in xrange(1, m + 1):
        a[n - m + j] = j - 1
    return f(m, n, 0, n, a)

Examples:

def pretty_print(parts):
    print '; '.join('|'.join(''.join(str(e) for e in loe) for loe in part) for part in parts)

>>> pretty_print(algorithm_u([1, 2, 3, 4], 3))
12|3|4; 1|23|4; 13|2|4; 1|2|34; 1|24|3; 14|2|3

>>> pretty_print(algorithm_u([1, 2, 3, 4, 5], 3))
123|4|5; 12|34|5; 1|234|5; 13|24|5; 134|2|5; 14|23|5; 124|3|5; 12|3|45; 1|23|45; 13|2|45; 1|2|345; 1|24|35; 14|2|35; 14|25|3; 1|245|3; 1|25|34; 13|25|4; 1|235|4; 12|35|4; 125|3|4; 15|23|4; 135|2|4; 15|2|34; 15|24|3; 145|2|3

Timing results:

$ python -m timeit "import test" "test.t(3, [[]], 0, [1, 2, 3, 4])"
100 loops, best of 3: 2.09 msec per loop

$ python -m timeit "import test" "test.t(3, [[]], 0, [1, 2, 3, 4, 5])"
100 loops, best of 3: 7.88 msec per loop

$ python -m timeit "import test" "test.t(3, [[]], 0, [1, 2, 3, 4, 5, 6])"
10 loops, best of 3: 23.6 msec per loop

$ python -m timeit "import test" "test.algorithm_u([1, 2, 3, 4], 3)"
10000 loops, best of 3: 26.1 usec per loop

$ python -m timeit "import test" "test.algorithm_u([1, 2, 3, 4, 5, 6, 7, 8], 3)"
10000 loops, best of 3: 28.1 usec per loop

$ python -m timeit "import test" "test.algorithm_u([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], 3)"
10000 loops, best of 3: 29.4 usec per loop

Notice that t runs much slower than algorithm_u for the same input.  Furthermore, t runs exponentially slower with each extra input, whereas algorithm_u runs almost as fast for double and quadruple the input size.


Generate Random String and Writing to File my task is to generate random strings and store in a file till the size of file is less than 10MB. My approach towards this problem is as follows.

import java.io.File;
import java.io.FileWriter;

public class Application {
    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        File file = new File("Hello.txt");
        file.createNewFile();
        FileWriter writer = new FileWriter(file);

        while (file.length() <= 1e+7) {
            writer.write(Generator.generateRandomString(12, Generator.Mode.ALPHANUMERIC));
            writer.write("\n");
            writer.write(Generator.generateRandomString(12, Generator.Mode.NUMERIC));
            writer.write("\n");
            writer.write(Generator.generateRandomString(12, Generator.Mode.ALPHA));
            writer.write("\n");
        }
        writer.flush();
        writer.close();
        long end = System.currentTimeMillis();
        System.out.println((end - start) / 1000f + " seconds");
    }
}

It takes about 100.495 seconds to complete on my i3 processor with 4GB of RAM. So my question is, how to improve this performance? Why is the performance so poor? Is there any another workaround for this?

It's the repeated calls to file.length() that is slowing you down.

Let's try this

while (file.length() <= 1e+7) {
  writer.write("abcdefghijkl");
  writer.write("\n");
  writer.write("abcdefghijkl");
  writer.write("\n");
  writer.write("abcdefghijkl");
  writer.write("\n");
}

On my machine that took ~51s.

Now let's try this:

for (int length = 0; length <= 1e+7; length += 39) {
  writer.write("abcdefghijkl");
  writer.write("\n");
  writer.write("abcdefghijkl");
  writer.write("\n");
  writer.write("abcdefghijkl");
  writer.write("\n");
}

Approximately 0.3s. And a quick sanity check:

$ du -h Hello.txt
9.6M    Hello.txt

There's a problem with the original method, which is the interaction of file.length() and using a buffered writer. Let's try to write up to 400 bytes:

while (file.length() <= 400) {
  writer.write("abcdefghijkl");
  writer.write("\n");
}

We actually end up with a lot more because of the buffered writer:

$ du -b Hello.txt
8203    Hello.txt

A similar problem is also present in the method presented here: we end up writing 403 bytes, not because of buffering but because of how we're counting. If you want to be precise about the total file size, you will need to modify it.


Better way of calculating Project Euler #2 (Fibonacci sequence) Even Fibonacci numbers

  Problem 2

  Each new term in the Fibonacci sequence is generated by adding the
  previous two terms. By starting with 1 and 2, the first 10 terms will
  be:

  1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

  By considering the terms in the Fibonacci sequence whose values do not
  exceed four million, find the sum of the even-valued terms.

object Problem_2 extends App {
    def fibLoop():Long =
    {
        var x = 1L
        var y = 2L
        var sum = 0L
        var swap = 0L

        while (x < 4000000)
        {
            if (x % 2 ==0) sum += x
            swap = x
            x = y
            y = swap + x
        }
        sum
    }
    def fib:Int = {
        lazy val fs: Stream[Int] = 0 #:: 1 #:: fs.zip(fs.tail).map(p => p._1 + p._2)
        fs.view.takeWhile(_ <= 4000000).filter(_ % 2 == 0).sum
    }

    val t1 = System.nanoTime()
    val res = fibLoop
    val t2 = (System.nanoTime() - t1 )/1000
    println(s"The result is: $res time taken $t2 ms ")
}

Is there a more functional way of calculating the Fibonacci sequence and taking the sum of the even values below 4 million?

Is the imperative method 1000x faster?

No iteration is required to calculate this result.

Every third Fibonacci number is even.  The Fibonacci numbers can be expressed in closed form as:

Fib(n) = 1/sqrt(5) * (phi^n - psi'^n)

where

phi = (1 + sqrt(5) / 2)

and

psi = (1 - sqrt(5) / 2)

F(n) is even when n is a multiple of 3.

Therefore the sum of even fibonacci numbers is equal to the sum of two geometric series, and can be calculated directly and exactly.

P.S. A little experimentation shows that

sum(i=0..n) Fib(3*i) = (Fib(3*n + 2) - 1) / 2

e.g.

2 + 8 + 34 = 44 = (89 - 1) / 2


Populate null fields in an object through reflection I have recently implemented this utility class for going through an instance's member fields recursively and assigning them default values if they are null. Here is the implementation in the NullHandler class:

public static class NullHandler
{
    public static void PopulateNullFields<T>(T obj)
    {
        var fields = obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic);

        foreach(var field in fields)
        {
            var defaultValue = field.GetValue(obj);

            if(defaultValue == null)
            {
                defaultValue = GetDefaultValue(field.FieldType);
            }

            var subFields = field.FieldType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic);

            if(subFields.Count() > 0 && !field.FieldType.IsValueType && field.FieldType != typeof(string))
            {
                PopulateNullFields(defaultValue);
            }

            field.SetValue(obj, defaultValue);
        }
    }

    public static object GetDefaultValue(Type t)
    {
        if(Nullable.GetUnderlyingType(t) != null)
        {
            t = Nullable.GetUnderlyingType(t);
        }

        if(t == typeof(string))
        {
            return "";
        }
        else if(t == typeof(DateTime))
        {
            return new DateTime();
        }
        else if (t.IsValueType)
        {
            return Activator.CreateInstance(t);
        }
        else if(t.IsArray)
        {
            var cinfo = t.GetConstructors().FirstOrDefault(x => x.GetParameters().Count() == 1);

            if(cinfo != null)
            {
                return cinfo.Invoke(new object[] { 0 });
            }
            else
            {
                throw new InvalidOperationException("Unable to find array constructor for this array type.");
            }
        }
        else if(t.IsEnum)
        {
            return Enum.GetValues(t).GetValue(0);
        }
        else
        {
            var cinfo = t.GetConstructors().Where(x => x.GetParameters().Count() == 0).FirstOrDefault();
            if (cinfo != null)
            {
                return Activator.CreateInstance(t);
            }
            else
            {
                throw new InvalidOperationException("No default constructor with no parameter is found for the type.");
            }
        }
    }
}

The code is currently in use in our XML serialization routine, where we have a requirement for another system that expects an XML file with null values included. The .NET XmlSerializer class omits null properties in the generated XML unless the properties are decorated with the XmlElement(IsNullable = true) attribute.

While we would have rather added the attributes to the model class itself, the model class is (a) created from code-generation, and we would lose the changes if we needed to regenerate the model class, and (b) the generated model class is at least ~3000 LOC, making it time-consuming to manually add the needed attributes ourselves.

Here is a sample of how the NullHandler utility class is in use on our project:

using (var stringWriter = new StringWriter())
using (var xmlStringWriter = XmlWriter.Create(stringWriter, settings))
{
     NullHandler.PopulateNullFields(item.Result.Payee);
     serializer.Serialize(xmlStringWriter, item.Result);

     // ...save XML to database
}

I would like to get feedback if there are areas where the code can be improved. I would specifically like to know how I can improve the reusability of the NullHandler class by accounting for any possibly missed cases (most especially in the GetDefaultValues method). Feedback to improve the class's readability would be appreciated as well.

A different option is to fix this at the creation of the XmlSerializer.  The XmlSerializer constructor can take a parameter for XmlAttributeOverrides

You could create a method to auto add the XmlElementAttribute, if missing, or set the IsNullable to true.

public static XmlAttributeOverrides AddIsNullableTrue(Type type)
{
    var xmlOverrides = new XmlAttributeOverrides();
    foreach (
        var prop in
            type.GetProperties()
                .Where(p => !p.PropertyType.IsValueType || p.PropertyType == typeof (string)))
    {
        var xmlAttributes = new XmlAttributes();
        var attr = prop.GetCustomAttribute<XmlElementAttribute>();
        if (attr != null)
        {
            attr.IsNullable = true;
        }
        else
        {
            attr = new XmlElementAttribute() {IsNullable = true};
        }
        xmlAttributes.XmlElements.Add(attr);
        xmlOverrides.Add(type, prop.Name, xmlAttributes);
    }
    return xmlOverrides;
}

Now when you create your XmlSerializer you just need to pass in the XmlAttributeOverrides

XmlSerializer SerializerObj = new XmlSerializer(typeof(TestClass), AddIsNullableTrue(typeof(TestClass)));

This example is assuming the class is called TestClass.  Now you don't need to populate null fields and fields will be output to XML that are null.


Removing final elements of a path to a file I have the use case of needing to find the parent path of a sub path for which I have written the following function:

#! /usr/bin/env python3

from os.path import sep

def pathbase(main, sub):
    if main.endswith(sub):
        parent = main[:-len(sub)]

        while parent.endswith(sep):
            parent = parent[:-1]

        return parent

    else:
        raise ValueError('Main path does not end on sub-path')

path1 = '/foo/bar/spamm/eggs'
path2 = 'spamm/eggs'

print(pathbase(path1, path2))

But I find that this is awfully verbose and that I re-invented the wheel with it.
Also it breaks if the paths have an unequal amount of trailing slashes, so my method would need to normalize both paths first, which would make it even more verbose.
Is there already some library method which does that, that I may have overlooked?

Edit: Due to the problems regarding the undesired partial node-match mentioned in some answers and comments I refactored the method to this:

from os.path import basename, dirname, normpath

def pathbase(main, sub):
    """Extract basename of main
    relative to its sub-path sub
    """

    norm_main = normpath(main)
    norm_sub = normpath(sub)

    while basename(norm_main) == basename(norm_sub):
        norm_main = dirname(norm_main)
        norm_sub = dirname(norm_sub)
    else:
        if basename(norm_sub):
            raise ValueError('"{sub}" is not a sub-path of {main}'.format(
                sub=sub, main=main))

    return norm_main

First, have in mind what @Daerdemandt suggested in comments (using os.path.relpath - even though I think this is returning the matches but I might be wrong)

From the docs:

  Return a relative filepath to path either from the current directory
  or from an optional start directory. This is a path computation: the
  filesystem is not accessed to confirm the existence or nature of path
  or start.

  start defaults to os.curdir.

  Availability: Unix, Windows.

After some reading of the os module, I don't think this is possible either. Sincerely, it is an unusual path manipulation which leads to the reason of not having it in the above mentioned module.

Apart from this, we can cut down you method and make it straight-forward:

import sys

def pathbase(path1, path2):
    try:
        if path1.endswith(path2):
            return path1[:-len(path2)]
        raise TypeError
    except TypeError:
        print('Main path does not end on sub-path')
        sys.exit(0)

path1 = '/foo/bar/spamm/eggs'
path2 = 'spamm/eggs'

print(pathbase(path1, path2))

There's not much to say about this. I just simplified your code by removing the while part which didn't make too much sense to me. I also removed the else part and raised a TypeError which I used in an try-except block.

Some minor style things

you could've call your method: get_base_path()
you could've name your arguments: main_path and sub_path

In the end, everything would look just like:

import sys

def get_base_path(main_path, sub_path):
    try:
        if main_path.endswith(sub_path):
            return main_path[:-len(sub_path)]
        raise TypeError
    except TypeError:
        print('Main path does not end on sub-path')
        sys.exit(0)

main_path = '/foo/bar/spamm/eggs'
sub_path = 'spamm/eggs'

print(get_base_path(main_path, sub_path))

The above returns:

  /foo/bar/