This is not at all a bad effort for someone new to the C++ language.  Here are some things that may help you improve your program.
Use the required #includes
The code uses std::fill which means that it should #include <algorithm>.  It was not difficult to infer, but it helps reviewers if the code is complete.
Eliminate global variables where practical
The code declares and uses a global variable, board.  Global variables obfuscate the actual dependencies within code and make maintainance and understanding of the code that much more difficult.  It also makes the code harder to reuse.  For all of these reasons, it's generally far preferable to eliminate global variables and to instead pass pointers to them.  That way the linkage is explicit and may be altered more easily if needed.  One could create the board within main and then pass a pointer or reference to it to the other routines that need it, or better yet, see the next suggestion.
Use a C++ object
Rather than using the global variable board and then having separate functions that manipulate that variable such as drawBoard() and placeMarker() in an object-oriented language such as C++ we can gather these together into an object.  That might look something like this:
class Board {
public:
    Board();
    void drawBoard();
    void placeMarker(bool isPlayerOne, int row, int col);
    bool checkValidInput(int row, int col);
    bool checkWon(int row, int col);
    static constexpr char PLAYER_ONE_MARKER = 'X';
    static constexpr char PLAYER_TWO_MARKER = 'O';
    static constexpr char UNFILLED_MARKER = ' ';
    static constexpr size_t numrows = 3;
    static constexpr size_t numcols = 3;
    static constexpr unsigned max_turns = numrows * numcols;
private:
    char board[3][3];
};

Eliminate "magic numbers"
There are a few numbers in the code, such as 3 and 2 that have a specific meaning in their particular context.  By using named constants such as numrows or numcols, the program becomes easier to read and maintain.
Don't use std::endl if you don't really need it
The difference betweeen std::endl and '\n' is that '\n' just emits a newline character, while std::endl actually flushes the stream.  This can be time-consuming in a program with a lot of I/O and is rarely actually needed.  It's best to only use std::endl when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one.  Avoiding the habit of using std::endl when '\n' will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.
Consider using a standard container
There is little reason in modern C++ to use a plain array rather than a standard container such as std::array.  I'd suggest that board could be this instead:
std::array<char,max_turns> board;

The initialization would then be much more easily written:
std::fill(board.begin(), board.end(), UNFILLED_MARKER);

Note that this form would require the conversion of row,column coordinates but if this is placed in an object, that detail can easily be isolated to within the object.
Don't use ALL_CAPS for constants
The use ALL_CAPS for constants defined as macros has been common practice for decades.  To avoid misleading readers of your program, non-macro constants should not be ALL_CAPS.  See ES.9 for details.


getProcID and getProcessHandle functions

I fairly routinely (not so much here as at work, for example) kind of "scold" people for creating classes where they really only need or want a single function.

This, however, is kind of the opposite case: functions where you really want classes. In particular, RAII can provide a real benefit here, and for that you need a class with a dtor.

I'm not excited about the situation with reporting errors by putting them into a string (and hoping that an empty string indicates success). I'd rather follow the model of "succeed or throw".

To keep that simple, I think it can also benefit from defining an assure (or something on that order) that's at least roughly similar to assert, except that it remains intact in release builds, and (perhaps) throws an exception instead of just aborting if a problem is seen. For example:

#define assure(cond, msg) do { if (!(cond)) throw std::runtime_error(msg); } while (0)

With that in hand, I'd probably start with a WindowHandle type something like this:

class WindowHandle {
    HWND handle;
public:
    WindowHandle(std::wstring const &windowName)
        : handle(FindWindowW(nullptr, windowName.c_str()))
    {
        assure(handle != 0, "Window not found");
    }
    operator HWND() { return handle; }
};

Note that (at least as far as I know, or MSDN seems to indicate) you normally don't want to call CloseHandle on the handle returned from FindWindow. If you did want to, you'd do that in the destructor.

Likewise, a process ID would look something like this:

class ProcId {
    WindowHandle handle;
    DWORD id;
public:
    ProcId(std::wstring const &window_name)
        : handle(window_name)
    {
        GetWindowThreadProcessId(handle, &id);
        assure(id != 0, "Error retrieving process ID");
    }
    operator DWORD() { return id; }
};

Finally, we get to the process handle (where we finally do need to use Closehandle):

class procHandle {
    ProcId id;
    HANDLE handle;
public:
    procHandle(std::wstring const &name, DWORD access = PROCESS_ALL_ACCESS)
        : id(name),
        handle(OpenProcess(access, FALSE, id)   )
    {
        // according to MSDN, returns NULL in case of error
        assure(handle != NULL, "Error retrieving process handle");
    }

    ~procHandle() { CloseHandle(handle); }

    operator HANDLE() { return handle; }
};

Note how each of these builds on the previous, so each only does one thing (i.e., we're following the single responsibility principle). Also note how the code to open a process handle becomes completely trivial:

procHandle p(L"SomeWindowName");

If we add in code to print out the error message if something goes wrong, it's still only marginally more complex:

try {
    procHandle p(L"Start");
    // Code to use process handle goes here.
} // handle will be closed automatically when we exit the scope
catch (std::exception const &e) {
    std::cerr << e.what() << "\n";
}

At least to me, this seems both easier to understand, and easier to use (and harder to use incorrectly).


Parse and sort domain names and their prices

One thing that makes a script like this more readable, maintainable and extendable is giving names to things. The easiest way to do that is using functions.

First I would make a function that reads and cleans your file:

def get_domain_prices(file_name):
    with open(file_name) as f:
        for line in f:
            yield line.strip()

This is a generator producing each cleaned line as needed. There is no need to read the whole file into memory here since you process it line by line anyway.

Next, your if conditions are mutually exclusive (a line can only start with one character), so you could use elif the second time to save yourself one check if the first one is true.

For the parsing of the "then $39.00/year" I would use a regex. This format is fixed enough for this to be easy and also complicated enough that splitting and replacing becomes cumbersome. The regex just searches for the string "then $x.yy/year", where before the decimal point there must be one or more digits and after the decimal point there are exactly two digits.

import re

for line in get_domain_prices('domain_prices.txt'):
    if line.startswith('.'):
        if len(prices_after_first_year) < len(domains):
            prices_after_first_year.append(prices[-1])
        domains.append(line.split()[0])
    elif line.startswith('$'):
        prices.append(float(line.replace('$', '')))
    elif line.startswith("then"):
        price = float(re.search(r'then \$(\d+.\d\d)/year', line).groups()[0])
        prices_after_first_year.append(price)

I also merged this checking into the elif chain and put a safe guard in the first condition to check if the previous domain had th price after one year set and if not add the price of that domain.

sorted can take a zip object, there is no need to cast it to list first (even in Python 3). If you re-structured the order in the zip (and in the write) you don't need to set the key and rely on the normal sorting of tuples (beware that this might produce a different order for domains with the same price, because then they are ordered by the next element of the tuple).

Since I guess you are using Python 3 (and if you are not yet, you should), I used f-strings (Python 3.6+) below to make the writing a bit easier.

sorted_domain_prices = sorted(zip(prices, prices_after_first_year, domains))
with open('sorted_domain_prices.txt', 'w') as f:
    for price, after, domain in sorted_domain_prices:
        f.write(f"{domain}\t{price}\t{after}\n")

Putting it all together:

import re

def clean_lines(file_name):
    with open(file_name) as f:
        for line in f:
            yield line.strip()

def parse_domain_prices(file_name):
    for line in clean_lines(file_name):
        if line.startswith('.'):
            if len(prices_after_first_year) < len(domains):
                prices_after_first_year.append(prices[-1])
            domains.append(line.split(' ')[0])
        elif line.startswith('$'):
            prices.append(float(line.replace('$', '')))
        elif line.startswith("then"):
            price = float(re.search(r'then \$(\d+.\d\d)/year', line).groups()[0])
            prices_after_first_year.append(price)
    return prices, prices_after_first_year, domains

def write_domain_prices(sorted_domain_prices, file_name):
    with open(file_name, 'w') as f:
        for price, after, domain in sorted_domain_prices:
            f.write(f"{domain}\t{price}\t{after}\n")

if __name__ == "__main__":
    data = parse_domain_prices('domain_prices.txt')
    write_domain_prices(sorted(zip(*data)), 'sorted_domain_prices.txt')

Here I modified the order in which the tuple is returned to be able to directly pass it to zip. I also added a if __name__ == "__main__": guard to allow importing parts of this script from another script without running it.

As a last step you should consider adding docstrings that describe what each function does so you can still remember in 6 months.


Generate Cartesian product of List in Java

You should read about the diamond operator.  You don't need to write the types on the right hand side in some circumstances.
I avoid varargs because they confuse the type system.  My guess is that you are not using an IDE because mine (Netbeans) flags both the diamond operators and the varargs.
You can indeed shorten your code because you don't really need to do a conditional check on the empty list if you start with the right conditions:

public static <T> List<List<T>> computeCombinations2(List<List<T>> lists) {
    List<List<T>> combinations = Arrays.asList(Arrays.asList());
    for (List<T> list : lists) {
        List<List<T>> extraColumnCombinations = new ArrayList<>();
        for (List<T> combination : combinations) {
            for (T element : list) {
                List<T> newCombination = new ArrayList<>(combination);
                newCombination.add(element);
                extraColumnCombinations.add(newCombination);
            }
        }
        combinations = extraColumnCombinations;
    }
    return combinations;
}

Note that the scanning order changed: the first element stays fixed until all other combinations of the other elements are exhausted.  I prefer that order actually.
It think it would be cleaner to split this in two methods.  There is a sub-task of adding one list of elements to an existing set of combinations and the main task which must call the sub-task on all lists:

public static <T> List<List<T>> computeCombinations3(List<List<T>> lists) {
    List<List<T>> currentCombinations = Arrays.asList(Arrays.asList());
    for (List<T> list : lists) {
        currentCombinations = appendElements(currentCombinations, list);
    }
    return currentCombinations;
}

and the sub-task (using Java 8):

public static <T> List<List<T>> appendElements(List<List<T>> combinations, List<T> extraElements) {
    return combinations.stream().flatMap(oldCombination
            -> extraElements.stream().map(extra -> {
                List<T> combinationWithExtra = new ArrayList<>(oldCombination);
                combinationWithExtra.add(extra);
                return combinationWithExtra;
            }))
            .collect(Collectors.toList());
}

Actually, for this method, Java 8 does not make it shorter and makes it less readable than the old style.  I am leaving it nonetheless so you (and others) can get more familiar with Java 8.
Minor point: I think you use too many blank lines in your code.


Just a nitpick about naming: the "find" in findSquareSum is meaningless, and perhaps even misleading, since it's not searching for anything.  Just squareSum would be fine.  Even better, call it something like sumSquaresOfDigits to be explicit about what the function does.


Listing words from text, provide lines where appears, count them

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);
    }
}


I think that if you accept definition Fowler uses you should name them "stubs":

  Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in
  for the test. Stubs may also record information. (Mocks Aren't Stubs )

Given the structure of the code if you want to cover with a suite of test should at least test how it works under a large set of input:

Empty array
Single element array
Array filled with null element
Array with a arbitrary number of element

with a different test for each of this cases

For this reason I suppose you should write a function that "allocate" an array, to avoid code repetition in the test (also tests must have code that you can maintain!). So I think yes you should put all the logic that can help you inside the test.

I'm not a fan of test not that test themselves, but in this case all the test make sense only if you invoke FreeItemMock with a reference to a bool, so yes I think make sense to test it, but I suggest you put it destructor, before changing the value, in this you are sure that you transaction from false to true is a really transaction and not a false to false


Game Engine :: Entity Component Design - Handling Input

Not having seen a given pattern usually means that you didn't use exactly the right search string, or you've modified a pattern that already exists enough so it looks different, so I wouldn't worry about finding solutions that you haven't seen before.

Having a class handling input is the way that I'd initially go to design the structure, unless there was a particularly compelling reason to do it in another way. I'd have my key presses push an Event onto a stack, which can be popped somewhere else. So for instance, if the 'W' key was pressed, I'd push a "Forwards" event (or whatever was relevant), onto a message stack. This check would be within an Update() function of the Input class.

Later on, I'd pass either that message, or an interpretation of that message to the entity that it was relevant to so that it could handle the instruction. This would mean that as long as the message name doesn't change, it shouldn't affect the rest of the system what form of input you're using, as long as it sends those messages.


There's no reason to look up the day's name in the DAYNAMES array. You already have the wday values, so you can just compare those directly.

I.e. if

Date::DAYNAMES[x] == Date::DAYNAMES[y]

it follows that

x == y

so:

(date1..date2).select { |date| date.wday == date1.wday }

Or, simpler, you can specify a step for the range and just skip one week at a time:

(date1..date2).step(7).to_a

Now, a week is typically 7 days long, but there have been a few cases of nations choosing to officially move to the other side of the international dateline, causing a week to not be 7 days long in their calendar. It's rare of course, but something to be aware of.


Here's a simple tree that can demonstrate a couple things:

    5
   / \
  3   7
 / \   \
1   6   8

minValue and maxValue are written so that the algorithm can catch the 6 that is out of place. And it seems like even the original versions of those functions are not doing that right. Your new algorithm will check the left value (3) and say it's okay, then check the 3-1-6 subtree and also say it's okay, when there's obviously a 6 that is on the left side and that is bigger than the root.

Your new algorithm, however, is broken in the same way as the old algorithm that uses minValue and maxValue is broken, so you translated code with functions into code with no functions "correctly" (didn't change anything).


The method can be shortened a bit. It'll probably have some effect on perfomance as well.

public static Timestamp convertTimeZone(final Timestamp fromDate, final TimeZone fromTZ, final TimeZone toTZ ){

  // primitive long should be enough for his task
  final long timeInDate = fromDate.getTime();
  final int fromOffset = fromTZ.getOffset(timeInDate);
  final int toOffset = toTZ.getOffset(timeInDate);

  return new Timestamp(timeInDate + (toOffset - fromOffset));
}


There is a lot of room for improvement in your code.
First, I'd like to address an unusual request you made:

Please don't recomend using functions.

Why not? They are a fundamental notion in programming, and can't really be avoided. Glossing over the fact that you already use a bunch of functions like print, input, append, etc., and assuming you are referring to functions that you define yourself in the code, it is still a puzzling request. Functions can make your code cleaner, easier to read, easier to maintain and more reusable, so why would you want to avoid them?
Take for example the part of the code where you ask for user input: the same code is copied and pasted twice. There are improvements to be made to that snippet. Implementing one these improvements would mean changing the code in two places. If it were encapsulated in a function, you would need to make that change only once, reducing the risk for errors.
Also, when reviewing your code, or when re-reading it yourself for further reference, encountering a properly named function is likely to be easier to process than what would effectively be the body of the function. I could see something like ask_for_input(player1) and focus on how the game move in handled, and then check out how you approach asking the user for input, independently from the previous logic. You could potentially reuse your ask_for_input function as is in future projects. Finally, you could then trivially replace the ask_for_input function with some sort of computer player if you want to expand this program.

As for the rest of the code, I won't provide a functional code, as there are already a lot of reviews on the site for "rock-paper-scissors" programs in Python. I'm sure you can find good, clean code that fits the bill.
However, I'll address a few design choices you made that can be improved upon, in no particular order.
Naming conventions
The PEP 8 Style Guide for Python Code recommends naming variables in lowercase snake_case, and constants in ALL_CAPS. Your variables and constants names are a mix of snake_case and CamelCase. While you may chose not to adhere to PEP 8 (although it's good practice to keep your code consistent with what is expected), at least pick a convention and stick with it.
PEP 8 is also a comprehensive style guide, and include cases that you may not even have thought about (like using a different style for constants, making the identifiable at first glance), so it is at the very least an interesting read.
Main loop
Most of your logic is enclosed in a while loop:
while True:
    ply_round += 1
    # ...
    if ply_round == 5:
        break

A while loop is clearly not the best fit here, as you effectively iterate over an incrementing index. A for loop would be functionally the same, while eliminating some overhead:
for ply_round in range(1, 6):
    # ...

Or better yet, use a named constant or a variable to specify how many rounds are played, so that you can see at first glance what the number means.
enumerate
You use enumerate a lot in your for loops. enumerate returns a tuple of (index, value), and you usually just use one of them. Instead of using enumerate, use for item in list if you only need the item, or for i in range(len(list)) if you only need the index.
Some times (although it is not your case here), you can't avoid using a throwaway variable. It is common practice to use _ in these cases, clearly showing that you don't need that variable.
Sanitizing inputs
When getting user input, you should check if the inputted value matches what the program expects. In your case, the program expects on of the values r, p, or s. If the user enters anything else, the program continues on and gives no output, while still incrementing the round counter.
This is made even worse because the prompts first ask for R, P or S, then for Rock, Paper or Scissors. The user has no way to know what the expected input is.
At the very least, you should change the prompts to ask for the correct value, and use .lower() on the inputs, so that the case doesn't matter. Then, if the value isn't what is expected, discard the value and ask again, instead of silently accepting wrong inputs.
At this point, you should really put the input code into a function, or else your program will get absolutely unreadable.
Backwards logic
Consider this piece of code:
for j, v in enumerate(choice):
    if choice[j] in ply_1:
        print(f'you choose {choice[j]}')

Ignoring the enumerate issue addressed earlier, what happens here is:

you loop over accepted inputs
check if the accepted input is in the actual input (which should be 1 character long)

It makes much more sense to do this the other way (check if the actual input is in the accepted range), and it's simpler too:
if ply_1 in choice:
    # do something

Winner determining logic
To determine which player wins, you basically check every possible case individually. That is a lot of code for a rather simple task. In fact, is is about on fourth of your code, and you only handle the most basic case of 2 players and 3 weapons. What if you wanted to improve your game to allow for more players or more weapons (think "rock-paper-scissors-lizard-spock")? Then it would become absurdly long.
Possible solutions can include a lookup table, a dictionary associating each weapon to the weapon it beats, implementing a Weapon class with comparison operators, or maybe other things.
At the very least, you can check for ties with if user_Ply[0] == user_Ply[1] instead of comparing both to multiple common values.
Using a list instead of multiple variables
I feel like two variables, named for example player_1_move and player_2_move, would be more readable and more suited than putting them both in a list.
Anti-cheat measures
Player 2 can see what move player 1 made, making it trivial for him to win every round.
I'm aware that this is a programming exercise and no-one wants to actually play rock-paper-scissors on a terminal, but clearing the console would simply make sense to me.


Your ROT algorithm is slightly wrong. The real ROT returns The alphabet rotated in the corresponding case. But in yours, even if you give Uppercase(TUVWXYZ), it returns lowercase for large rotations. That is not exact ROT.
This can be seen from this screenshot
This may be helpful:  https://www.geeksforgeeks.org/rot13-cipher/. Here instead of chr() and ord() Dictionaries are used which is very efficient and less error prone.


Split string into parts of varying lengths

This is a pretty good solution but like you say, the reverse is annoying, so let's see if we can fix that.

We want a sequence of tuples (start, length) that we can pass to Substring. We already have the lengths, so we just need to figure out the starts. The skeleton of our solution looks like this:

let segmentString lengths (input : string) =
    let segments = Seq.zip ??? lengths
    Seq.map (input.Substring : int * int -> string) segments

So where does a segment start? It starts at the sum of the previous lengths. We can use scan (+) 0 to calculate the partial sums of the lengths.

This gives us the final solution

let segmentString lengths (input : string) =
    let segments = Seq.zip (Seq.scan (+) 0 lengths) lengths
    Seq.map (input.Substring : int * int -> string) segments


Beautifulsoup and lxml (xpath) too slow with respect to regex when parsing HTML

Well, your regex solution is obviously badly broken - it will fail if the attributes are in a different order, if they are separated by newlines, if they are delimited by single quotes, etc etc. If you try to replace it with a more correct regex (it will never be 100% correct of course) then you are quite likely to lose some of this speed - perhaps dramatically, if it starts backtracking.

The cost of the XPath solution is not actually in evaluating the XPath, it is (a) parsing the source document and building a tree representation, and (b) compiling the XPath expression. The key to getting a performance improvement is to make sure you are doing these operations only once. I don't know whether that's possible in your overall application scenario.


Python has so many neat stuff to help you with this one, I feel alot can be rewritten:

  I did a lot of C++ and miss std::swap(..)

Luckily you can swap really easy in python

For instance the swap method, can be rewritten like

def swap(a, i, j):
    a[i], a[j] = a[j], a[i]

  Is there a simpler way to trigger the unfolding of the iterator into a list?

Yes there is list slicing.

Just with list slicing only the reversed could be a[k + 1::-1]
Where the last -1 is the step, and -1 means we step over it in reverse
This returns a list and not a generator, thus your reverse could be
return a[:k + 1] + a[k + 1::-1]

@user2357112, I feel like a rookie now.

I made a mistake, intuitively while fast typing I thought list reversing would be like this list[start:end:step] but instead it works differently, with exclusion.

[first i to include:first i to exclude:step], and becomes:

return a[:k + 1] + a[:k:-1]


Customer search using LINQ followed by conditional filtering of results

Filtering is actually done correctly, using the best and recommended approach. All LINQ queries are executed lazily, that is they are not executed until you start enumerating them. So all those .Where calls actually just register additional filtering of the records which would translate to entries in the where clause in SQL.

One thing to notice - the call to AsEnumerable() method before .OrderBy is potentially ineffective because it forces the ordering to be done on the client side instead of SQL. I would rewrite it as

    results
        .OrderBy(x => x.COMPANY)
        .AsEnumerable()
        .Select(x => new
        {
            x.ID,
            x.COMPANY,
            x.CONTACT,
            PRICECAT=Prog.getPriceCategory()[(int) x.PRICECAT],
            STATE = Prog.getStatus()[(int)x.STATE],
            x.TERMDESC
        }).ToList();


Testing lower- and upper bound values in Python

Except under unusual circumstances, classes are things or entities -- hence the
term objects -- while functions or methods are actions or operations. You
want to name them accordingly. For that reason, Get_labels strikes me as an
oddly named class. Based on what you've shown us, I might suggest the name
Bounds as an alternative. A side benefit of that name is that it allows you
to shorten up the attribute names without loss of meaning.
A separate method for checking the basic validity of the bounds seems like
over-engineering to me -- unless the checking logic becomes much more complex
or unless it will be used elsewhere in the code. So I would just do simple
validation in __init__() in this case.
Avoid the temptation to use chatty or verbose messages in your code. It won't
help you or your users over the long run -- at least that's my experience. Keep
things direct and rigorously concise. In fact, it's often beneficial to keep
the messages very technical rather than natural in their stylistic orientation.
What I mean by that is rather than describing the problem the way one might
verbally to a human ("The lower bound, which was 1000, must be less than the
upper bound, which as 125"), you are often better off to describe the problem
in a formulaic, schematic, computer-like way. Among other things, that approach
allows you to adopt a conventional format for all error messages in an
application. The error message format shown in the rewrite below could be
described generically as PROBLEM: SELF. A consistent approach makes it
easier to write validation code in the first place and to maintain it over
time. Consistency also conveys professionalism to users.
Along those lines, you can often simplify the creation of such validation
messages by first defining __repr__() for your class, as illustrated below.
For the validations you have so far, a ValueError is a closer
fit than raising a general Exception. Also, you might consider checking
for other kinds of errors: for example, are bounds restricted to integers only?
If you do check for that, raise a TypeError.
Finally, a stylistic and admittedly subjective fine point. Below is a stack
trace from your code as written. We see the verbose message twice, first as an
f-string, and then with parameters filled in. What's wrong with that? Nothing
serious, but it's heavy, tedious, even lacking a certain elegance. At a
minimum, one could say that the repetition of the verbose message is mildly
distracting to the user, putting an extra increment of a visual or cognitive
burden on the user to figure out what's going on. Compare that to the stack
trace from the revised code.
# ORIGINAL.

Traceback (most recent call last):
  File "bounds.py", line 19, in <module>
    get_labels = Get_labels(-1,25,"first")
  File "bounds.py", line 7, in __init__
    self.check_threshold_validity()
  File "bounds.py", line 17, in check_threshold_validity
    raise Exception(f'Sorry, the lower threshold={self.lower_bound} should be larger than 0 for configuration={self.configuration_name}')
Exception: Sorry, the lower threshold=-1 should be larger than 0 for configuration=first

# REVISED.

Traceback (most recent call last):
  File "bounds.py", line 72, in <module>
    b1 = Bounds(1000, 125, 'first')
  File "bounds.py", line 67, in __init__
    raise Exception(msg)
Exception: Upper bound must be greater than lower: Bounds(1000, 125, first)

Code with some possible edits for you to consider:
class Bounds:

    def __init__(self, lower, upper, name):
        self.lower = lower
        self.upper = upper
        self.name = name

        if lower <= 0 or upper <= 0:
            msg = f'Bounds must be positive: {self}'
            raise ValueError(msg)

        if upper <= lower:
            msg = f'Upper bound must be greater than lower: {self}'
            raise ValueError(msg)

    def __repr__(self):
        return f'Bounds({self.lower}, {self.upper}, {self.name!r})'


Removing duplicates without using a temporary buffer

public class WithoutExtraSpace {

Class names should reflect what the class does.  In this case, I would expect a name like ListUtilities or even CrackingTheCodingInterviewExercise.  It's not clear to me what WithoutExtraSpace even means.  Perhaps a reference to the lack of a temporary buffer?  Then it should have been DuplicateRemoverWithoutExtraSpace.  Or just DuplicateRemover.

    LinkedList<Integer> list = new LinkedList<Integer>();
    list.add(9);
    list.add(1);
    list.add(3);
    list.add(2);
    list.add(5);
    list.add(7);
    list.add(8);
    list.add(3);
    list.add(1);
    list.add(8);
    System.out.println(list);

I'd add some whitespace in this section:

    List<Integer> list = new LinkedList<Integer>();

    list.add(9);
    list.add(1);
    list.add(3);
    list.add(2);
    list.add(5);
    list.add(7);
    list.add(8);
    list.add(3);
    list.add(1);
    list.add(8);

    System.out.println("Unsorted:  " + list);

Now I have a declaration block, an initialization block, and the start of the coding block.

I changed the declaration of list.  Instead of being of type LinkedList, I made it of type List, which is the interface name.  This is why we have things that implement interfaces, so we don't have to care what the implementation is.  You happen to be using a LinkedList, but if you change that to an ArrayList or any other implementation, it shouldn't matter.

I added an "Unsorted:" at the beginning of the println.  When I first ran this, I didn't know what the various outputs were.  Now I do.

Avoid code in main

You put a lot of your code in the main method itself.  As a general rule, there should be very little code in main.  Process the arguments, perhaps initialize variables, and then call methods to do the heavy lifting.  This allows you to reuse those pieces that do actual work.  If all the code is in main, then you have to edit main to use it.  Further, you can't just add your class to another project; you'd have to copy the code itself.

    removeDuplicates(list);

    System.out.println("Unique:  " + list);

This is the remainder of the main method.  Now let's work on removeDuplicates.

public static <T extends Comparable<? super T>> void removeDuplicates(List<T> list) {
    Collections.sort(list);

    Iterator<T> itr = list.iterator();
    if (itr.hasNext()) {
        T previous = itr.next();

        while (itr.hasNext()) {
            T current = itr.next();

            if (previous.equals(current)) {
                itr.remove();
            } else {
                previous = current;
            }
        }
    }
}

Rather than lock us into a single implementation, let's use generics to allow us to cover a wide variety of possible types.  Why <T extends Comparable<? super T>>?  The short answer is that's what made my IDE happy.  The reason why it made the IDE happy is that Collections.sort uses it.  So we're basically saying that removeDuplicates will work with any List type that we can sort.

Everywhere in this section of code that used to say Integer now says T instead.

            if (previous.equals(current)) {
                itr.remove();
            }
            previous = current;

I changed this to

            if (previous.equals(current)) {
                itr.remove();
            } else {
                previous = current;
            }

My reasoning is that when we just removed current from the List, why should we be comparing it to other elements?  It's already gone and we shouldn't remove other elements based on something that is no longer in the List.  Note that this has no functional impact, as we know that previous and current are equal if we just removed current.  But I find it easier to follow, and it avoids an unnecessary assignment.  The new logic is that we either remove current from the list (as a duplicate) or we update previous (since there are no more duplicates of it, we need to start looking for duplicates of current).  We don't do both at once.

    System.out.println(list);

I removed the display of the sorted with duplicates list.  It seems more like debugging code than code necessary to solve the problem.  As such, it should be removed before turning in the code for review.

Your Question

  I have used Iterator interface. Can I use it or need to re-implement it?

I don't know the answer to this.  For a definitive answer, you'd have to ask the interviewer.  If you told us what the book actually says, we might be able to give you some guidance.

As a general rule, it's good to ask the interviewer questions that show you understand the problem.  Asking if it is all right to use the iterator() method of List is perfectly reasonable.

Another question that is relevant here is if you are allowed to change the existing order of the List.  Clearly it must be mutable, as you have to remove duplicates.  It's not as clear that order doesn't matter.  It might or might not.

Complexity

Collections.sort is an \$O(n \log n)\$ algorithm in terms of time.  The rest of the method is linear (\$O(n)\$) in time.  You iterate through list once.  This makes the method \$O(n \log n)\$ overall.

In terms of memory complexity, the iteration is \$O(1)\$.  It adds three variables, regardless of the size of list.  The sort is more complex.  It can use up to \$n/2\$ new object references.  That makes it \$O(n)\$ in memory complexity.  This might be a violation of the "no temporary buffer" constraint.

Testing

It looks like you tested this code in place in the main method.  It probably would have been better if you could have written this as unit tests.  As it is, each new test obliterates the old.


Headers and namespaces
#include "bits/stdc++.h"

That's not a standard C++ header; prefer to use standard headers so that others can use your code.
using namespace std;

Bringing all names in from a namespace is problematic; namespace std particularly so. See Why is “using namespace std” considered bad practice?.
Naming
Choose a consistent naming convention and stick to it.  A common one that's closest to the majority of your code is to use PascalCase for types, camelCase for members and snake_case for variables.
Class Base
A default-constructed Base will have default-constructed Id and Name members.  It probably makes no sense to default-construct; I think it's better to explicitly declare a constructor:
public:
    Base(std::string id, std::string name)
      : id(std::move(id)), name(std::move(name))
    {}

Once initialized, there should be no reason to change the name or id, so we can remove the setters.  The accessors can be made const, so we can call them on instances of const Base:
    std::string getName() const { return name; }
    std::string getId() const { return id; }

Class Item
This seems mis-named - it's more like an "order line" that specifies how many items and their price.  Again, a default constructor seems wrong, although defaulting the quantity to 1 makes sense:
public:
    Item(std::string id, std::string name, double price, int quantity = 1)
      : Base(std::move(id), std::move(name)),
        itemPrice(price),
        itemQuantity(quantity)
    {
        if (itemQuantity <= 0)
            throw new std::domain_error("negative quantity");
        if (itemPrice <= 0)
            throw new std::domain_error("negative price");
    }

Whether it's reasonably to modify the price and quantity after construction really depends on your application, so I can't comment on that, but the getters should both be marked const, like the ones for id and name.
Also, I'll add the standard warning that floating-point is usually a poor choice for financial accounting - you'll avoid numeric rounding if you choose instead to represent currency amounts in integer values of the smallest denomination.
Class customer
Although customers may have names and identifiers, does that really make them the same kind of thing as items?  Unless you have a use case where you may want to use them interchangeably, public inheritance isn't really what you need here.  It's a common trap in OO design to assume that because two things are made from similar pieces that they must be similar things.  In some cases, it really is mere coincidence.  By way of analogy, chairs and dogs are both quadrupeds, but blindly choosing to treat them alike is a mistake that could turn around and bite you.
It is extremely kind of you to credit all your new customers with 5000 currency units in their accounts - but it might not be good business sense (even if they are Zimbabwean Third Dollars).  I recommend 0. as a more sensible default.
If the customer object is intended to be an autonomous object, it should be responsible for crediting and debiting the account, rather than setting the amount; I'd expect something more like:
void deposit(Currency amount)
{
    balance += amount;
}
void withdraw(Currency amount)
{
    balance -= amount;
}
Currency balance() const { return amount; }

(Real implementations usually involve some locking, so that concurrent operations don't interfere with each other, but that's a whole review in itself)
Why can a customer buy only one Item?  Usually, an order is composed of several items (each with a quantity) and refers to a customer (who may at a later date order more items - it's bad business to restrict them from doing that).
Something that looks really strange is this:
void print(){
    cout << Custitem.getName() << " " << Custitem.getId() << " " << Custitem.getQuantity() << " " << Custitem.getPrice() << "\n";
    Custbalance -= Custitem.getQuantity()*Custitem.getPrice();
    cout << Custbalance << "\n";
}

Why does the customer have to pay each time you print their order?
Usually, print() would look something like
std::ostream& print(std::ostream& o) const
{
    return o
      << Custitem.getName()
      << " " << Custitem.getId()
      << " " << Custitem.getQuantity()
      << " " << Custitem.getPrice() << "\n"
      << Custbalance << "\n";
}

and the debiting of the account would be a separate (non-const) operation.


I am not most experienced with C++ (java's my best language) but as far as I know, method names are supposed to be camelCase. MatchPattern_Rec should be matchPatternRec.

Also, why are you returning a 1 or a 0? Shouldn't you be returning a bool? (Again, correct me if I'm wrong)

The chain of ternary operators is very unreadable and messy, which causes easy bugs. You are also using ternary in places you can just use || and &&. Use if and switch statements to simplify:

constexpr bool matchPatternRec(const char* pattern, const char* text) {
    if (*pattern == '\0' || *text == '\0') {
        return *pattern == *text;
    }
    switch (*pattern) {
    case '?':
        return matchPatternRec(pattern + 1, text + 1);
    case '*':
        return matchPatternRec(pattern + 1, text) ||
                matchPatternRec(pattern, text + 1);
    case '+':
        return matchPatternRec(pattern + 1, text + 1) ||
                matchPatternRec(pattern, text + 1);
    default:
        return *pattern == *text && matchPatternRec(pattern + 1, text + 1);
    }
}

constexpr int matchPattern(const char* pattern, const char* text) {
    if (*pattern == '\0') {
        return false;
    }
    return (*pattern == '*' && *(pattern+1) == '\0' && *text == '\0') ||
            matchPatternRec(pattern, text);
}


Mutable named tuple with default value and conditional rounding support

In short:

dataclass is the right thing to use as a mutable named tuple. It's basically custom-built to be a great version of that idea.
Use decimal.Decimal for any financial numbers.
Don't re-implement round. There's a built-in version that behaves in nice, configurable ways with the Decimal object.
Not sure what the p.update(**{sale=600}, **dict(rate=0.9073)) is all about, just use p.update(sale=600, rate=0.9073) (except with Decimals)


Basic folder tree with a list of strings

One improvement that comes to mind is:

bool found = false;
foreach(var item in finalList)
{
    if (item.StartsWith(path, StringComparison.Ordinal))
    {
        found = true;
        break;
    }
}

Finding out whether a condition is met for any item in a collection is a common enough problem that LINQ has a method for that: Enumerable.Any. Using that the above code can be written as just:

bool found = finalList.Any(item =>
    item.StartsWith(path,StringComparison.Ordinal);

Which is both shorter and simpler.


Enforcing a constraint that a user may vote on each post at most once

which one is more efficient

Almost surely the unique index will be. Querying back and forth between the server and database is very expensive, and the query that you would have to write to check the table beforehand would do the same thing as the unique constraint - just far less efficiently. The best case is that you'd have to still add an index to the database to get vaguely similar performance, and the connection round-trip expense between the server and database would then be the limiting factor.

All of that said: you aren't asking the more important question, which is

which method gives me a better guarantee of correctness?

Under most circumstances, it's useless to do performance tuning when your data are wrong. The database can guarantee that the data remain valid if you give it a constraint to enforce. If the server is responsible for enforcing the constraint, and it has a race condition or other nasty concurrency edge case, you're setting yourself up for a very difficult debugging session trying to find why duplicates are getting into your database.


Increasing visible text with on-click "read more"

You have lots of calls to $(".header .text"), which you can replace with calls to box:

var areaBig = box.height();

Similarly, you can simplify calls to selectors within box, such as:

// Better than: readmore = $('.header .text a[title*="meer"]')
var readmore = box.find('a[title*="meer"]');

// Better than: $(".header .text").animate(...
box.animate({ height: areaBig }, 1000, "easeInQuart", function () {
  box.find("p").css({ visibility: "visible" });
});

These changes will not only make the code easier to read but also increase execution speed.


I don't see anything wrong with your code as it is: formatting is consistent and tidy, functions do what they need to do and no more, no apparent bugs.

One nit: your header file includes <iostream> but doesn't need it - you should remove that.

Having said that, "polluting" the global namespace with an object named assert isn't a good idea: assert is defined as a macro in <cassert>, you'll get all sorts of problems if your users include that, directly or indirectly. (Having a file called assert.h isn't a great idea either, that's the name of the C standard library assert header.)

Also your ASSERT macro doesn't do what the standard assert macro does (calls std::abort if the condition doesn't check), so you're likely to confuse people.

While the ASSERT macro itself is necessary to pull in the context information (AFAIK there's no other way to do that), the other three are a bit gratuitous and would benefit from being plain functions. Don't use macros when they provide no real benefit.

Here's a sketch about how you could clean that up a bit and avoid these issues (I'm not very good with names, so YMMV):

In a header, declare four plain functions inside a namespace:

bool check(bool, char const*, char const*, int): same as your Assert::operator() function
void report() (or possibly void report(std::ostream&) for a bit more flexibility)
int total_checks() and int failed_checks().

Also in that header define the CHECK function-like macro as you did your ASSERT, but using Testing::check instead.
In an implementation file, inside the namespace:

Define two static ints to store the total and failed counts
Define all the functions you declared.

This avoids the name clash, and "hides" the global state (the state is still global, so you still need to worry about thread-safety and such, it is just not as visible anymore).

Note: I don't think there's anything fundamentally wrong with using a class rather than plain functions in a namespace, and a class approach would be better if you ever intend to have more than one (e.g. one "test counter" per thread). But as it is, just plain old functions and static data seems enough.

Sample incomplete implementation:

testing.h

#pragma once

#define CHECK(x) Testing::check((x), #x, __FILE__, __LINE__)

namespace Testing
{
bool check(bool, char const *, char const *, int);
int total();
int failed();
}

testing.cpp

#include "testing.h"

#include <iostream>

namespace Testing
{
static int total_checks;
static int failed_checks;

bool check(bool ok, char const *what, char const *file, int line)
{
  total_checks++;
  if (!ok) {
    failed_checks++;
    std::cerr << "Failure of " << what << " at " << file << ":" << line
              << std::endl;
  }
  return ok;
}

int total() { return total_checks; }
int failed() { return failed_checks; }
}

Use case:

#include "testing.h"

#include <iostream>

int main()
{
  CHECK(1==1);
  CHECK(1==0);
  std::cout << Testing::failed() << " / " << Testing::total() << std::endl;
}


Combining multiple masses to obtain a desired total mass

First of all, your code doesn't actually work for some cases. The return statement in the for loop causes the loop to only ever run once. This means your function doesn't find a solution for prepareCargoPacket(2, 10, 12) (it tries with 1 7kg soap, fails the if check since 5 isn't a multiple of 2, then returns -1 without ever trying with no 7kg soaps). Removing that return fixes it.
Another thing I want to point out is that your way to cap the number of 7kg soaps is really not very efficient. If you need to make a total weight of 6kg when you have 200000 7kg soaps available, your function will call itself 200000 times. This is not ideal, for multiple reasons. Not only is it a lot of steps (each of which takes some amount of time), but the program will also internally keep track of each function call in the call stack, and that thing can only get so big before your program crashes with a java.lang.StackOverflowError.
A way around that is to notice that if you have more than totalKg / 7 7kg soaps, the total weight is already too high. So if you have too many 7kg soaps at the start, you don't need to keep trying with 1 less each time, because totalKg / 7 just gives you a nice upper bound.
To finish off with some nitpicking, I'm not a huge fan of repeating the weights of the soaps all over the place like that. If the person who wants this software comes up to you and says "Hi, sorry, we switched from 7kg soaps to 5kg soaps, can you update the program for us?" it would be annoying to replace the weight everywhere, and there'd be a risk of missing a place. A nicer approach could be replacing the numbers with constant variables, maybe something like final int HEAVY_WEIGHT = 7; and final int LIGHT_WEIGHT = 2;? That way, if the weights need changing, it only happens in one place. At that point I might also look into renaming the input parameters to something like heavyAvailable and lightAvailable to match those while I'm at it.
A few more thoughts
I looked some more, and came up with a few more comments.
Apart from the issue with there possibly being a lot of function calls, having the function call itself at all feels like it makes the logic a bit harder to follow. I'd like to restructure it so that that isn't necessary, with that initial check being used not to re-enter the function, but to determine where the loop starts.
Another, fairly minor issue is that this function keeps going for longer that it might have to even though it should know it won't find a solution. For example, if called as prepareCargoPacket(5, 0, 36) we get to the loop, notice we don't have enough 2kg soaps to reach the weight of 1kg that's missing. But then we continue to check if we can make 8kg instead. Which we can't since we have too few soaps. So we go on to check 15kg instead. But we can't make that either, so we check if we can make 22kg... Now imagine if instead of starting at 5 and 36 we'd started at something like 142,857,142 and 1,000,000,000.
Well, you don't have to imagine. I tested it, and it was still really fast. Never underestimate a computer's ability to do math quickly. Still, it can matter if the loop contains anything more complicated than a few basic math operators and a few ifs, so I'm bringing it up for future reference anyway. I also feel like switching the loop condition to take that into account also makes the code a bit cleaner, but it also arguably becomes a bit less obvious why it's written the way it is, so it might not actually be an improvement.
The solution variable doesn't seem entirely necessary to be honest. Each time the function returns, it either returns -1, or it changes solution for the first time and then immediately returns. At that point, I might get rid of that variable to save the reader from having to keep track of whether it's been updated. That's a matter of taste, though, there are definitely people who'd disagree with me on that.
Finally, since I've already done some nitpicking about variable names, I might as well complain about the last few. totalKg doesn't feel as descriptive as it could be. It and currentTotalKg are also a bit confusable, because "the total" and "the current total" don't really feel all that distinct to me - while that is sometimes the best way to describe two values, we might want to look for something that makes their purposes even more obvious. Going by what they're doing, totalKg might be more accurately described as the goalWeight or targetWeight, and since currentTotalKg is the amount we're missing to be able to reach that we might call that missingWeight or remainingWeight perhaps?
Taking all that into account, I might write something a bit like
package com.bit32.cargocalculation;

public class CargoCalculation {

    public static final int HEAVY_WEIGHT = 7;
    public static final int LIGHT_WEIGHT = 2;

    /**
    * Calculates how many lightweight soaps we need to use to reach exactly the target weight, if possible
    * If no lightweight soaps are required, or if the target weight can't be reached, returns -1
    *
    * @param heavyAvailable The number of heavy soaps that can be used
    * @param lightAvailable The number of light soaps that can be used
    * @param targetWeight The desired sum of the weights of all the soaps
    * @return
    */
    public int prepareCargoPacket(int heavyAvailable, int lightAvailable, int targetWeight) {
        int maxHeavyUsed;
        if (HEAVY_WEIGHT * heavyAvailable > targetWeight) {
            maxHeavyUsed = targetWeight / HEAVY_WEIGHT;
        } else {
            maxHeavyUsed = heavyAvailable;
        }

        // Loop until we find a solution, or until we know we can't
        for (int remainingWeight = targetWeight - HEAVY_WEIGHT * maxHeavyUsed;
             remainingWeight <= LIGHT_WEIGHT * lightAvailable;
             remainingWeight += HEAVY_WEIGHT) {
            if (remainingWeight == 0) {
                // Special case: We have to return -1 if we don't need light soaps
                return -1;
            } else if (remainingWeight % LIGHT_WEIGHT == 0 &&
                       lightAvailable * LIGHT_WEIGHT >= remainingWeight) {
                return remainingWeight / LIGHT_WEIGHT;
            }
        }

        // No solution
        return -1;
    }
}

Though as I said if you think it's clearer to write the loop as for (int i = maxHeavyUsed; i >= 0; i--) (and then define remainingWeight inside the loop), you can do that instead.


Replacing characters in a Java string using iteration and recursion

First of all, good work!

Now a couple of points:

Whitespace

You abuse the usage of white space in your code. This applies to indentation as well.

\$\mathcal{O}(?)\$

You are right about the running time of both your methods being \$\mathcal{O}(n)\$ (in all cases). However,

str.toCharArray(); //assuming it to be O(1)

runs in linear time as well (apart from counting the time it takes to ask the memory subsystem for a new character array). The issue here is that, the returned array is not the same array somewhere in the str, and that's why: if it were the same array, it would run in constant time, yes, but it would allow a programmer to modify the state of the string through the character array.

API design

You can improve the API of your methods a bit; see below.

Naming

The names c and r are not descriptive. Consider renaming to targetChar(acter) and replacementChar(acter), respectively.

replacechar(...)

Consider renaming to replaceChar(acter), and declare it private since it is an auxiliary method.

Summa summarum

All in all, I had this in mind:

public static String replace(String str,
                             char targetChar,
                             char replaceChar) {
    // O(n): Strings are immutable. For that very reason, toCharArray()
    // returns the copy of the internal character array, so that the user
    // cannot mutate the string. Copying done in linear time.
    char[] c = str.toCharArray();

    for (int i = 0; i < c.length; ++i) {
        if (c[i] == targetChar) {
            c[i]= replaceChar;
        }
    }

    return String.valueOf(c);
}

public static void recursiveApproach(String text,
                                     char targetChar,
                                     char replacementChar) {
    recursiveApproach(text.toCharArray(), targetChar, replacementChar);
}

public static void recursiveApproach(char[] a,
                                     char targetChar,
                                     char replacementChar) {
    recursiveApproach(a, 0, a.length, targetChar, replacementChar);
}

public static void recursiveApproach(String text,
                                     int fromIndex,
                                     int toIndex,
                                     char targetChar,
                                     char replacementChar) {
    recursiveApproach(text.toCharArray(),
                      fromIndex,
                      toIndex,
                      targetChar,
                      replacementChar);
}

public static void recursiveApproach(char[] a,
                                     int fromIndex,
                                     int toIndex,
                                     char targetChar,
                                     char replacementChar) {
    int rangeLength = toIndex - fromIndex;

    if (rangeLength < 1) {
        return;
    }

    if (rangeLength == 1) {
        replaceChar(a, fromIndex, targetChar, replacementChar);
    } else {
        int mid = fromIndex + rangeLength / 2;
        recursiveApproach(a, fromIndex, mid, targetChar, replacementChar);
        recursiveApproach(a, mid, toIndex, targetChar, replacementChar);
    }
}

private static void replaceChar(char[] a,
                                int index,
                                char targetChar,
                                char replacementChar) {
    if (a[index] == targetChar) {
        a[index] = replacementChar;
    }
}

Hope that helps.


Wanted to write my own form slider, Jquery/JS

Here are some suggestions to simplify the syntax:

For pos, use an array literal: var pos = [0, 67, 133, 199, 267, 333]

Similar thing for compare: var compare = [];

You're missing semi-colons after some statements
You can make initializing compare simpler using Array.prototype.map (doesn't work on IE < 9):

var compare = pos.map(function (e) {
    return e - mouseMovement;
});

If you need to support IE < 9, I'd either implement map, or do basically what you're doing, but use Array.prototype.push instead:

for(var c=0;c<=5;c++){//do some math to make sure the slider ends up going to the closest interval postion
    compare.push(Math.abs(pos[c] - mouseMovement));
}

You've got a lot of undefined variables that will default to the global scope:

sliderPos- not used
mouseCoordStart- dangerous because it might not be defined when it's used
oncontextmenu- not used anywhere

333 in your mousemove handler is magic, perhaps it should be pos[pos.length-1]?

I'm not going to comment on jQuery plug-in style (I don't use jQuery) or your implementation of a "form slider" (which I assume is an implementation of an HTML5 input range).

Hopefully this was useful!


Review of HTML and CSS for a newsfeed of posts

this looks really good so far,

I don't see anything that I would change about this.  you are using span tags correctly and efficiently for what you are doing with them,  your div tags are also used to the best of their abilities.

your CSS also looks good, I don't think I would change anything there either.

I guess the only thing that I might change, and this depends on how you intend to use it, is probably the grouping of the discusBy and the discusMetaPostedOn, I might group those together because they look like they are going to be the same formatting aside from the things that you have given specific classes to.

you might want to give each <div class="discusBox"> it's own unique ID especially if you are going to work some Javascript magic or server-side magic on it.

otherwise it looks really good,  you probably won't make any of the changes I mentioned because of the way you want to go forward with the code.


This would be a good place to use a ternary comparison operator:

var otherPlayer;
if(currPlayer == board.X){
  otherPlayer = board.O;
} else {
  otherPlayer = board.X;
}

Then it would become a single line:

var otherPlayer = currPlayer == board.X ? board.O : board.X;

You could do this in a few other places as well.

for(var i=0; i<moveList.length; i++){

You use spaces around your operators for the most part, you should be consistent with this.

var b = new Board();

In the Minimax object code, you use good variables names.  Not so much in the Board object code.

Otherwise, this looks good to me, very clean, neat, and well documented.


First and foremost: testing in Debug - Any CPU mode is bad. Debug configurations have a lot of extra overhead and Any CPU is a non-native instruction configuration*, both will cause you to get poor measurements.

Next, when you do your testing you should consider (I say consider because when doing simple comparisons you don't need to, but when trying to prove something you should definitely do so) using a proper benchmark tool like BenchmarkDotNet. (It's in NuGet so it's simple to install.)

However, if you choose not to (I'm not going to judge you for that) you should not measure the first execution of your code. You should loop it a few times (I usually use 10-128, depending on how fast the code is) and then discard those results, then do it again and keep those results. Take the average as your metric.

Why?

The first time you execute your code, the JITter (Just-In Time optimizer) will optimize your code another time. This adds a substantial amount of overhead to the first execution. Sometimes a lot of it. This can (and will) skew your results substantially.

* This is heavily debated and may or may not have any effect. In some testing in my environment x64 is faster, and in some testing Any CPU is faster.

Now that the lecture is over, let's look over the code quick:

You have a lot of "magic numbers" here, most notably 4 and 3, you should consider giving them a const identifier. (Consider what 4 and 3 mean in each instance, and what they mean if you were to be writing a Base32 converter instead of Base64.)

Your for loop (for (int i = 0; i < div * 3; i += 3)) can use length instead of div * 3 there, just as well you should assign length first, then use it instead of data.Length everywhere. I.e.:

    int div = data.Length / 3;
    int mod = data.Length % 3;

Should instead be:

    int div = length / 3;
    int mod = length % 3;

With as frequently as you use dPointer[length - 1] and dPointer[length - 2], you should consider extracting variables there for extra micro-performance boosts.

Those are the only complaints I have, good work!


Getting information from URL efficiently

To start off, I will say what I say on every question dealing with files: always use with syntax.

By using this syntax you lessen the change for bugs; especially the bug that happens when you forget to call close() on an open file pointer. Your code shows this bug. You open the temp.del file, but never call close on it. Because of this, when you program finishes running, you have an active file pointer that the OS needs to clean up.

To fix this, simply do this:

with open('temp.del', 'r') as file:
    # Do stuff.

Once this block of code finishes, file will automatically get closed.

To answer you question whether or not its necessary to write the temporary file, take a look a the urllib.urlopen documentation. It says:

  Except for the info(), getcode() and geturl() methods, these methods have the same interface as for file objects — see section File Objects in this manual. (It is not a built-in file object, however, so it can’t be used at those few places where a true built-in file object is required.)

This means that you should be able to iterate through this just like you would a file. Which, in your case, means you do not have to save the temporary file. Unfortunately, in Python 2.7, the return object from urllib.urlopen is not a valid context manager (i.e doesn't implement __enter__ and __exit__). So we have to use open and close:

file = urllib.urlopen("https://launchpad.net/elementary/+milestone/isis-beta1")
for line in file:

Now onto improvements:

In each of your if statements, you have the condition and i < 450. You can bring this out into its own statement, and because you don't do anything after line 450, you can simply break if it evaluates to true:

for index, line in enumerate(file):
    if index >= 450:
        break

Getting the bug counts can be done easier using a regex:

import re

# Grabs all the numerical data, converts them to ints, then sums them together.
bugs += sum(map(int, re.findall('\d+', next_line)))

Each if statement holds the same code: you get the next line, split it, and then assign a value to a certain variable. After you finish the bugs, you add them all together. You don't differentiate after you parse them. You can combine these into a single if statement and simply keep a single running total like so:

if any(span in line for span in ['span class="statusINCOMPLETE">',
                                 'span class="statusCONFIRMED">',
                                 'span class="statusINPROGRESS">']):

    bugs += sum(map(int, re.findall('\d+', next_line)))

If you need to differentiate the different kind of bugs, you can use a dict:

bug_types = {'span class="statusINCOMPLETE">': 0,
             'span class="statusCONFIRMED">': 0,
             'span class="statusINPROGRESS">': 0}

for key in bug_types:
    if key in line:
        bug_types[key] += sum(map(int, re.findall('\d+', next_line))))

When formatting string output, convention says to use the str.format() function. The syntax look like this:

print '{} {}!'.format('Hello', 'World')

If you take all of my suggestions into account, here is your new code:

import urllib
import os
import re

bug_types = {'span class="statusINCOMPLETE">': 0,
    'span class="statusCONFIRMED">': 0,
    'span class="statusINPROGRESS">': 0}

# Even though we have to use `open` and `close` and can simply enclose the next
# for loop with the calls, I still would load the file into a temporary array.
# Then iterate over that.
file = urllib.urlopen("https://launchpad.net/elementary/+milestone/isis-beta1")
lines = [str(line) for line in file]
file.close()

# Because of the way `urlopen` streams the data, we cannot use the `next` command.
# Therefore, we need to use a flag to remember what kind of bug we found on the
# previous line.
bug_type = ''
for index, line in enumerate(lines):
    if index >= 450:
        break

    if bug_type:
        bug_types[bug_type] += sum(map(int, re.findall('\d+', line)))
        bug_type = ''
    else:
        for key in bug_types:
            if key in line:
                bug_type = key
                break

print('\n{} bugs left until Isis. Quit moaning.\n'.format(sum(bug_types.values())))


C inner product function without using array subscripting

I have a few comments on style.  (By which I really mean, 100% opinion... :D)

One declaration per line

A lot of people strongly disagree with this, but I find it much easier to read code that has one declaration per line.

const int *p;
const int *q;

Is a lot clearer to me than:

const int *p, *q;

Though really, the only time I've vehemently opposed to it is if both variables are not the same in terms of a pointer or value:

const int *p, q;

Is a harder to read and more prone to errors than:

const int *p;
const int q;

n

I would name the n paramter something more meaningful.  I would consider calling it size or num.

It's fairly apparent that n is meant to be the number of elements, but two or three extra keystrokes seems worth the extra clarity.

Possible implementation

I would probably write the function something like this:

int inner_product(const int *a, const int *b, int num)
{

    const int* end = a + num;

    int sum = 0;

    while (a != end) {
            sum += (*a) * (*b);
            ++a;
            ++b;
    }

    return sum;

}

Since the two pointers are incremented at the same time, there's no reason to check both.

This should be a tiny bit more efficient (well... probably not once the compiler does it's magic optimisations on the original), and I think it's a bit clearer.


String Similarity using fuzzywuzzy on big data

The first algorithmic recommendation is to use itertools.combinations instead of .permutations, since you don't care about order. This assumes fuzz.token_sort_ratio(str_1, str_2) == fuzz.token_sort_ratio(str_2, str_1). There are half as many combinations as there are permutations, so that gives you a free 2x speedup.

This code also lends itself easily to parallelization. On an i7 (8 virtual cores, 4 physical), you could probably expect this to give you ~4-8x speedup, but that depends on a lot of factors. The least intrusive way to do this is to use multiprocessing.Pool.map or .imap_unordered:

import multiprocessing as mp

def ratio(strings):
    s1, s2 = strings
    return s1, s2, fuzz.token_sort_ratio(s1, s2)

with open('D:\\Sim_Score.csv', 'w') as f1:
    writer = csv.writer(f1, delimiter='\t', lineterminator='\n', )
    writer.writerow(['tag4'])

    with mp.Pool() as pool:
        for s1, s2, r in pool.imap_unordered(ratio, itertools.combinations(Dishes, 2)):
            if r > threshold_ratio:
                writer.writerow([(s1, s2, r)])

All told, I'd expect these changes to give you 5-10x speedup, depending heavily on the number of cores you have available.

For reference, a generator comprehension version of this might look something like:

with mp.Pool() as pool:
    writer.writerows((s1, s2, r)
                     for s1, s2, r in pool.imap_unordered(ratio, itertools.combinations(Dishes, 2))
                     if r > threshold_ratio)

That version has a some, but very little, performance improvement over the non-comprehension version, and IMO is harder to read/maintain.

One other minor thing I noticed in testing my code was that fuzzywuzzy recommends installing python-Levenshtein in order to run faster; when I did so, it ran about 20x slower than when it used the built-in SequenceMatcher. When I uninstalled python-Levenshtein it got fast again. That seems very odd to me, but it's certainly something worth trying.

Finally, if performance is important, you could consider digging into what fuzz.token_sort_ratio does to see if you could remove some repeated work. For example, it's tokenizing and sorting each string again every time you pass it in, so maybe you could pre-tokenize/sort the strings and only run the ratio logic inside the main loop. A quick dig tells me that token_sort_ratio is two main steps:

Preprocess each string using fuzz._process_and_sort
Run fuzz.partial_ratio against the processed strings

I'm not able to get this to run faster at the moment, but I'll edit and update this answer if I can get that approach to work well.


This is very hard to read like that.
The duplication of the same base url is also not great.

With the -O flag, you could specify - to make the output go to stdout.

Lastly, `...` is obsolete syntax, use the modern $(...) instead.

baseurl=https://chromedriver.storage.googleapis.com
filename=chromedriver_linux64.zip

version=$(wget "$baseurl"/LATEST_RELEASE -O-)
wget "$baseurl/$version/$filename" -O "/tmp/$filename"


Note, some of these require a build process

the iife should be added in the build process, it's distracting
The code doesn't expose anything. It's untestable.
var should be let or const
You can use arrow functions to turn some of the functions into one liners
Inconsistent formatting - I recommend getting a linter
setApplicationView - Should probably be replaced with show/hide functions. The current name is not very descriptive to me.
//     hide game board - You can make this a function and get rid of the comment. Several other similar issues.
ifClicked - A function name should generally describe what the functions does, not what happened when it was called. You could also just inline it.
winnerFinder - It would be so much nicer if this was called findWinner, and returned the result instead of storing it globally. Then you could test it as well.
As it stands, it actually returns false when winnerFound is true. Even more confusing.
winnerFinder - You can use player.filter here to get rid of the index variable
playerData.arr - What is arr?
var player = playersData.arr; - How can a player be an array?
document.getElementById - You can run all these calls at the top to shorten the code and get rid of unnecessary dom queries.
innerHTML - It's quite hard to tell how this whole thing works with view logic and game logic all mixed in together.
In general I would recommend separating the view logic from the game logic as much as possible, and even better would be to make the view logic declarative.


Good things

lots of comments are good.
clear keeps things clean when you start
This is an interesting way to learn shell scripting.  My friends would call it "very meta" which is high praise indeed.
I usually tell people they should have run their code through https://www.shellcheck.net/ before worrying about a review.  Amazingly enough you didn't trip any of the checks over there so: try it on your next shell project.  Or read their docs to see what to avoid in the future.

Suggestions

In your lines echo #################### all of the hashes (####################) are completely superfluous.  As you have it or simply writing echo will do the same thing.  Just reading the code it implies that the hashes are getting output, which they're not since the shell views it as one big comment.  You could put the hashes in quotes and then the shell would not "remove" it from the output.
Indenting most of the stuff inside the until is good.  It'd be nice to do the same thing for the case statement.  Your compact layout actually works in this case so I wouldn't mind seeing:

case $selection in
    1 ) echo "#!/bin/bash" > "$text.bash" ; nano "$text.bash"  ;;
    2 ) chmod 755 "$text.bash" ;;
    3 ) gnome-terminal ; echo "./$text.bash" ;;
    4 ) nano "$text.bash" ;;
    5 ) idle ;;
    6 ) gnome-terminal ;;
    7 ) nano ;; # would be something like grep a special crafted document
    8 ) echo "#!/bin/bash" > "$text.bash" ;;
    9 ) cat icodehelp ;;
    0 ) exit ;;
    * ) echo "Please enter 1, 2, 3, 4, 5, 6, 7, 8, 9, or 0"
esac

but it would look more like most people write shell scripts if you spaced it out like:

case $selection in
    1 )
        echo "#!/bin/bash" > "$text.bash"
        nano "$text.bash"
        ;;
    2 )
        chmod 755 "$text.bash"
        ;;
    3 )
        gnome-terminal
        echo "./$text.bash"
        ;;
    4 )
        nano "$text.bash"
        ;;
    5 )
        idle
        ;;
    6 )
        gnome-terminal
        ;;
    7 )
        nano
        ;; # would be something like grep a special crafted document
    8 )
        echo "#!/bin/bash" > "$text.bash"
        ;;
    9 )
        cat icodehelp
        ;;
    0 )
        exit
        ;;
    * )
        echo "Please enter 1, 2, 3, 4, 5, 6, 7, 8, 9, or 0"
esac

That's obviously take up three times as many lines, but if you decide to add more to any of the sections it will remain readable.
Much of your code is outputting blocks of text.  Rather than doing the echo after echo thing it is easier to scale this to multiple lines of text at once with a "Here Document".  To replace your block of echos after figlet you could do:

cat <<-EXAMPLE
Showing a way to use the command line steps to start a Hello World   program
Where you see test.bash, Please rename test.bash
Follow Steps Below...

echo '#!/bin/bash' > test.bash
'echo Hello World' >> test.bash
chmod 755 test.bash
nano test.bash
Exit Ctrl-c

EXAMPLE

This will do the same thing as what you already had, but it avoids needing to worrying about the quoting on each line.  It does remove the ability to comment within it, but usually that's a smaller issue than keeping straight whether you are in the text to be output or in scripting code.  By including the - in <<- we are saying to ignore initial tabs in the Heredoc content.  The tabs get removed on the fly and not exposed to the end user.  This lets you use it inside the until to indent the whole cat and keep everything looking neat.
You could avoid the need for banner or figlet by the users of your script if you took the output of them and saved it into your script, probably in a Heredoc.  Since you're not passing anything variable into them, their output won't change and so "caching" a static version won't reduce any existing functionality.

cat <<'ICODE'
 ___              _
|_ _|___ ___   __| | ___
 | |/ __/ _ \ / _` |/ _ \
 | | (_| (_) | (_| |  __/
|___\___\___/ \__,_|\___|
ICODE

In this case the Heredoc starts with single quotes (<<'ICODE') so that the contents are passed through without any values being replaced.
Your option 9 for help could be done without an external file.  Typically this would be done by defining a function and then calling it inside your case statement.  Inside the function could simply be a cat with a Heredoc.  But doing that means you don't have to worry about the help file getting lost.

Ideas

If you like figlet try cowsay!  :=)
Try reading the bash man page a few times.  It is long and arduous, but full of lots of useful info if you can make it.
https://kvz.io/blog/2013/11/21/bash-best-practices/ has some easier to digest suggestions.  Looking at your menu section I was really hoping to find a set -x so we could see the commands running too.  This may not fit your UX, but it is worth trying to see how tracing works.


It's safe. A few things to consider:

When the list is empty you might want to return false.
Consider using an abstract data type (instead of string) which stores your data (the string) and move the validation logic to there.
As Jeff Vanzella already suggested, you can return false immediately when you now that a value is not valid. It's faster and easier to read:

bool AreValid(list<string> vals)
{
   foreach(string val in vals)
   {
       if(!condition1)
          ...
          return false;
       if(!condition2)
          ...
          return false;
   }

   return true;

}

Note that you don't need the else keyword anymore.


If you have a collection of Meters and you want to be able to find the ONE based on a property, this is how I would do it:

Create a List of Meters, say l..

List<Meter> l = new List<Meter>();

Then implement Extension methods like so..

public static class MeterExt
{
    public static Meter GetByErm(this List<Meter> l, String sErm)
    {
        Meter r = l.Find(s => s.ertNumber == sErm);

        return r;
    }

    public static Meter Get(this List<Meter> l, String sMeter)
    {
        Meter r = l.Find(s => s.meterNumber == sMeter);

        return r;
    }
}

Then you can find your meter like so..

Meter m = l.Get("fsadfa");


Separating values in string and returning them as comma separated string

Stuff I noticed:

Missing semicolons. Perhaps the code doesn't need them, but you certainly want them. My argument is always that if JS truly didn't need semi-colons, they'd be completely optional (or cause outright syntax errors). But JS's automatic semi-colon insertion is (in my opinion) a crutch meant to fix bad code; ideally it should never come into play at all (unless you're a JS minifier or something).
You've got an implicit global: i is never declared. And i is veery likely to used in loops elsewhere, so you've got a really tricky bug that's just waiting to strike.
You've also got some other declaration-confusion: output is declared in one branch of the code, but is also used in another branch. Since the branches are mutually exclusive, the latter branch is basically using output without it having been declared. Again, JS does it's best to fix your code, but it shouldn't be necessary.
Just declare all your local variables at the top of the function.
Strict comparisons (=== and !==). You might as well use them.
Also be consistent with your use of double- and single-quotes. There's no reason to mix and match. Doens't do any harm, but neither does consistency.
Your first conditional can be written as simply: if(input) { .... You're checking for undefined and an empty string, but both of those are false'y, so it's needlessly complex. If anything, you could consider checking typeof input === 'string', if you want to check types.
But instead of wrapping everything in that if block, just return early, and save yourself a lot of indentation.

var result = '';
if(!input) { return result; }
// ...

In a similar vein: You check if the input contains the ;# delimiter. If it doesn't, result is just set to be the input. So once again, just return early; send the input right back.
Don't glue together a string yourself; use join(', '). Saves you the trouble of going back and chopping off stray commas and whitespace afterward.
This doesn't make sense to me:

if (array[i].match(/^\d+/)) {
  //do nothing
} else {
  var output = array[i].replace(/^\d+/, '')

So, if array[i] begins with some digits, do nothing. If it doesn't begin with digits, then... remove those non-existent digits? What?
Most of all: If you're going for performance, don't use indexOf, match, replace and split over and over to find the same stuff.

I'd say just split the input string right away. There's no reason to branch and check whether there's a reason to split; just split, and process the resulting array. If there's only one item in the array, so be it - no need to treat it any differently than if there were 2, 3, or 789 items in the array.

It also looks to me like you intend to discard all the parts that are just digits (e.g. "69", "44" and "45" in your example), and just keep the text parts. If the pattern is always "number;#text;#number;#text ... etc", you could simply include the numbers in your split-pattern. The code below will split the string at ;#<number>;#, <number>;# or just ;#

input.split(/(?:;#)?\d*;#/); // => [ '', 'Statements', 'Clarifications', 'Suggestions;' ]

though, as you can see, that leaves you with a blank string in the array, because your input begins with a number.

Alternatively, you can replace all the numbers ahead of time:

input.replace(/\d+;#/g, ''); // => "Statements;#Clarifications;#Suggestions;"

so now you can split that string easily.

Your example input does however have a trailing ; which I don't see being handled anywhere. You current function returns a string with that semicolon intact ("Statements, Clarifications, Suggestions;"), which is doubt is the intention.

Assuming you only want the "words", you could flip the whole thing around, and, instead of splitting, use match to just pick out the parts you want, ignoring the numbers and delimiters:

input.match(/[a-z]\w+/ig) // matches a starting letter, and goes until it hits something that's not a letter or number.

which, if that's the appropriate pattern to use for your data, reduces the entire function to this:

function formatLookup(input) {
  return input.match(/[a-z]\w+/ig).join(', ');
}

Done.

Edit: Here's a more liberal regex (see comments)

function formatLookup(input) {
  return input.match(/([^#]*?)[a-z][^;]*/ig).join(', ');
}

This one will match everything between a "#" and a ";" provided there's just a single letter in there (i.e. it won't match all-number parts). It's still not perfect, and will for instance not match anything in an input string like "45;#3. 555-3443;" (don't know if that's relevant, but caveat emptor, etc.).

If that proves problematic, it might well be simpler to just split the string, and discard every 2nd part (if indeed the number-text-number-text... pattern holds true):

function formatLookup(input) {
  return input.split(/;#?/).filter(function (value, i) {
    return value && i % 2;
  }).join(', ');
}

Note that the above will likely be slightly faster (i.e. probably-not-worth-it faster) if you use an old-school for-loop to loop through and push to an array, rather than use filter:

function formatLookup(input) {
  var values = input.split(/;#?/),
      result = [],
      i = 1,
      l = values.length;

  for(; i < l ; i += 2) { // notice the increment
    if(values[i]) { result.push(values[i]); }
  }

  return result.join(', ');
}

Addendum: In an earlier iteration of the question, you were adding the values to a global array as well. If that's still useful, then I'd suggest simplifying the function even further, and just let it return an array:

function parseLookup(input) { // note the different name
  return input.match(/[a-z]\w+/ig);
}

Then, where needed, you can do something like this

var values = parseLookup(input);

someGlobalArray = someGlobalArray.concat(values); // append to global array

var formatted = values.join(", "); // same end-result as before

Even if you don't need the global array, I'd still suggest separating parsing the input, and formatting the output. Your current function does both, but it'd be cleaner and more modular to have one function for one thing, and another function for the other (or just inline the join(...) if it's only used once). Your current function basically takes all the data from one informal string format... and outputs another informal string format. Sure, something happens along the way, but overall it's a bit like two steps forward, one back.


Iterative tree traversal to turn tree into a dictionary and list

Some suggestions:

Empty lists are False, so while len(stack) != 0 is the same as while stack.  None is also False, so you can check for empty lists and None values at the same time.

You can use dict.setdefault to get a value and set it to a default (in your case an empty list). if it isn't already there.

You can convert an append loop to extend with a generator expression, or better yet just a zip.

Your last two elif tests are mutually exclusive, so the last can be an else.

The if node_tuple[1] == layer: test does the same thing in the first line of both cases.  I  moved that out of the if test, but if they are supposed to do something different you should fix that yourself.

pre_layer always has its value subtracted by one, so it is easier to subtract one before defining it.

You always set node_tuple to stack[-1] if stack is non-empty, so you can move that out  of the if test entirely.  And if you put it at the beginning of the loop, you can avoid the if test entirely.  You can simplify this further by only getting it if you need it.

def reconstruct_iteratively(root):
    # A tuple that stores node to be traverse and the layer the node is in
    stack = [(root, 0)]

    layer = 0
    pre_layer = -1
    level = dict()

    # This is a postorder traversal
    while stack:
        node_value, node_layer = stack[-1]
        node_list = node_value.node_list
        # This case catch the event that next node is the parent layer and
        # this node is not a termination node
        if node_layer < pre_layer:
            parent_node = stack.pop()
            parent_node_dict = {'value': parent_node[0].value,
                                'children': level.pop(layer, None)}
            layer -= 1
            pre_layer = layer

            level.setdefault(layer, []).append(parent_node_dict)

        # This case catch the event for traversing down to the child
        elif node_list:
            stack.extend(zip(node_list, [layer+1]*len(node_list)))
            layer += 1

        # This case catch the event that we are at the termination node
        else:
            # Two possible scenario
            # 1. The next node is in the same layer
            # 2. The next node is in the parent layer
            level.setdefault(layer, []).append({'value': node_value.value,
                                                'children': []})
            del stack[-1]
            if stack[-1][1] != layer:
                parent_node_dict = {'value': stack.pop()[0].value,
                                    'children': level.pop(layer, None)}
                layer -= 1
                pre_layer = layer

                level.setdefault(layer, []).append(parent_node_dict)

    return [parent_node_dict]


Environment.NewLine always returns \r\n so it won't help you in parsing different line endings.

If your task is to count the number of lines then it would be much easier just to do smth. like:

    private static int GetLineCount(string fileName)
    {
        return File.ReadLines(fileName).Count();
    }

ReadLines method automatically parses different line endings.


JavaScript class that generates HTML form with validation

I'd just move the render part to the constructor and provide it with the id of the parent element.

class Form {

   constructor( id ) {

      const button = document.createElement('button');
      button.value = "Upload";
      button.disabled = true;

      const input = document.createElement('input');
      input.placeholder = 'Path to data';
      input.oninput = () => this.validate();

      this.input = input;
      this.button = button;

      const form = document.createElement('form');
      form.appendChild(input);
      form.appendChild(button);
      document.getElementById(id).appendChild(form);

   }

   validate () {

      const a = document.createElement('a');
      a.href = this.input.value;
      this.button.disabled = !(a.host && a.host != window.location.host);

   }

}

const form = new Form("app");

It depends what you want to do with the form afterwards.


If you rename these:

    var changedClaim1 = CreateAnyChangedClaim();
    var changedClaim2 = CreateAnyChangedClaim();
    var changedClaim3 = CreateAnyChangedClaim();
    var changedClaim4 = CreateAnyChangedClaim();

Like this:

    var service1changedClaim1 = CreateAnyChangedClaim();
    var service1changedClaim2 = CreateAnyChangedClaim();
    var service2changedClaim1 = CreateAnyChangedClaim();
    var service2changedClaim1 = CreateAnyChangedClaim();

Then it will be more obvious that these will be used in two different services. These names will carry more meaning than just an arbitrary list of IChangedClaim objects.

What is "sut" ? A more meaningful name would be better.

In this assert:

    Assert.That(result, Is.EqualTo(expectedResult), "result");

The comment message is not very useful.
Either make it something more meaningful, or delete it.


fun buildPrimes ps x =
          if length ps >= n then ps

Don't forget that length is expensive. It's definitely worth using an extra accumulator variable to track either the length or the number of primes left to find. I haven't done proper benchmarks, but it seems to give a speedup of a factor of 2 for input 10000.

I understand why you prepend newly found primes to the list and then reverse it at the end: appending the prime to the end of the list is expensive. But the other side of the argument is that the smaller primes are far more valuable for eliminating composite numbers, and in my testing replacing (x::ps) with (ps @ [x]) and ditching the rev makes a significant improvement to speed.

If performance is a high priority then you could take a hybrid approach which gives you the best of both worlds at the cost of complicating the code: have one list which is sorted in increasing order and another list which is sorted in decreasing order. Use additional accumulator variables to track their lengths. Add new primes to the front of the decreasing list, and when the decreasing list is as long as the increasing list replace them with asc @ (rev desc) and [].

My SML isn't at a level where I feel qualified to say what is idiomatic and what isn't, but one of the most advanced things I studied in SML at university was lazy infinite lists, and I think they have a claim to be fairly idiomatic in functional languages in general. It's not too hard to rework this sieve into a lazy infinite style. We define a type for lazy infinite lists of integers:

datatype stream = Cons of int * (unit -> stream);

where unit is the tuple of length 0, (); then a lazy list of all integers can be built with

fun integers n = Cons(n, fn () => integers (n + 1));

Filtering an infinite list is useful enough to define it outside the prime generator:

fun filter f (Cons(x,xs)) =
    if f(x) then Cons(x, fn () => filter f (xs()))
    else filter f (xs());

And then the sieve itself just builds up layers of filters:

val primes =
    let
        fun filter_multiples m = filter (fn i => i mod m <> 0)
        fun prime_extractor (Cons(p,xs)) = Cons(p, fn () => prime_extractor (filter_multiples p (xs())))
    in
        prime_extractor (integers 2)
    end;

For testing purposes, converting the first n elements to a normal list is convenient:

fun take 0 (Cons(x, xs)) = []
  | take n (Cons(x, xs)) = x :: (take (n - 1) (xs()));

For production quality this should probably be wrapped in a module, but that's at the level that I've heard of it but don't know any details.