Check if n-th root of product of numbers is a whole number C++

The basic approach looks sensible, but I do have a few suggestions for improvements.

using namespace std;

Bad idea. It may be a nuisance having to prepend std:: everywhere, but it's a short name in order to reduce the nuisance, and the things which could go wrong are quite bad.

void add_base_and_power(Prime_factorization& prime_factorization, int    base, int power)

What happened to the whitespace in int    base? A single space suffices.

What do the names communicate and fail to communicate? The name prime_factorization communicates nothing: the type already says that. What purpose does this particular prime factorisation serve? The name base doesn't really fit the context IMO: you're not accumulating to a Base_power_pairs. add_prime_power(Prime_factorization accumulator, int prime, int power) would make it crystal clear what the function does.

void check_if_is_factor(Prime_factorization& prime_factorization, int &number, int divisor)

Again, names.

    if (number % divisor == 0) { // If the divisor is a base, we divide until it no longer can

This isn't wrong, but I wonder whether you made a conscious choice between this approach and

    int power { 0 };
    while (number % divisor == 0) {
        number /= divisor;
        ++power;
    }

    if (power > 0)
    {
        // Add base and power to factorization
        add_base_and_power(prime_factorization, divisor, power);
    }

I find the latter more aesthetically pleasing. It doesn't do a test which it knows will succeed.

NB this point is purely a subjective point about style - I'm not trying to microoptimise, and microoptimisations should be done with good benchmarks.

void decompose(Prime_factorization& prime_factorization, int number)

What is being decomposed here? My instinct would be that the first argument is the most relevant to interpreting the function name, but that doesn't make sense in this case.

    for (int div { 3 }; div * div <= number && number > 1; div += 2)

I've seen you use this int name { val } a few times, and (not being a C++ user) I'm not familiar with it. Does it have some advantage over int name = val to counter the disadvantage of requiring more effort to port to a different language?

There's a case to be made for calculating the square root of number outside the loop: firstly on micro-optimisation grounds, but secondly on correctness grounds. div * div could overflow the type.

    // We must print the base-power combinations in sorted order
    sort(prime_factorization.begin(), prime_factorization.end(), [](pair<int, int> p1, pair<int, int> p2) { return p1.first < p2.first; });

    if (okay) {
        cout << 1 << '\n';

        for (auto& i : prime_factorization)
            cout << i.first << ' ' << (i.second / m) << '\n';
    } else
        cout << 0;

Two things here: firstly, since the sorted values are only needed in one branch of the if it makes more sense to push the sort into that branch. Secondly,

if (test) {
    foo;
} else
    bar;

is easily the weirdest bracing style I've ever seen, and weird style is not good for collaboration. Do you use a company or published style guide?

Finally, my one algorithmic observation.

    // Check if we've already got the base we're trying to add
    auto it = find_if(prime_factorization.begin(), prime_factorization.end(), [&](pair <int, int> p) { return p.first == base; } );

    if (it != prime_factorization.end()) // If yes, add the power to the existing base
        it->second += power;
    else
        prime_factorization.push_back(make_pair(base, power)); // Else, create a new base

Linear search is never ideal. If you're using a recent standard, std::unordered_map is asymptotically preferable, and also IMO conveys the purpose better. Or maybe you would be better off with std::map, which would remove the need to sort at the end.


Kotlin extension functions with null checks

OK, I'll give my answer. One problem I had trying this approach is that there are too many combinations: there are cases when you want to use also cases when you want to use let etc.
It looks like having the operators and the extension functions independently defined gives you the advantage of a kind of strategy pattern when you can combine different strategies to have an exponential number of configuration without having to define an exponential number of functions.

So you have

Operators:

 1. `?.`
 2. `?:`

Extension functions

a) `also`
b) `let`
c) `run`
d) etc

then you can combine operator 1. with extension fun b) or operator 2. with extension fun c) etc

If you try to define extension funs with null checks then you need to define one function for each combination: it's even difficult just to find names for the functions

So I will keep the otherwise helper fun but I will not use if ifNotNull


MySQL Query to check at least one field is greater than zero

In addition to the other differences between the two statements

WHERE (number_A + number_B + number_C) > 0

Could cause you problems if any of those three are negative. That may not be relevant in your case, but if one of these is negative the total might fail to exceed zero even if another of the values does exceed zero.


Use of global variable
In your function, you use test from the global scope in the comprehension which can lead to nasty side effects.
Type hints and formatting
Type hints and proper formatting help future readers understand the code easier. Modern code editors and static code analysis tools can also use them.
Docstring
A function docstring also helps future users to understand the code.
Raise ValueError if no match
Printing Error is not a good way to notify users of this function that something went wrong. What is the problem? Also if you dont return anything in this case, the function returns None with no errors, which can lead to other, harder to find errors later.
Use generator in counting sum
You dont need to create a list to count the occurences, you can just use a generator expression inside the sum.
No need for list of lists
Maybe you have a reason for this, but you dont need the list of lists data structure for your example.
Use python builtins
You dont need numpy for this task, using python builtins is enough. This way, you dont have to install numpy if you only want to use this function.

Putting it all together, my reviewed version looks like this.
import math
from typing import List

def inverse_document_frequency(corpora: List[str], term: str) -> float:
   """
   Calculates Inverse Document Frequency.

   Arguments:
       corpora (List[str]): List of strings to check for term 'term'
       term (str): Term to count in 'corpora'

   Returns:
       float: Inverse document frequency, defined as
           1 + log(length of corpora / occurrences of term)
           Rounded to 3 decimal places.
   """

   occurences = sum(1 for string in corpora if term in string)
   if occurences == 0:
       raise ValueError(f"No occurrences of term '{term}' in 'corpora'.")
   else:
       return round(1 + math.log(len(corpora) / occurences), 3)

test = [
   "I like beer",
   "I like craft beers",
   "I like ALE craft beers",
   "If I have to choose a craft beer, I will take the IPA craft beer",
]

beer = inverse_document_frequency(corpora=test, term="beer")
craft_beer = inverse_document_frequency(corpora=test, term="craft")
ipa = inverse_document_frequency(corpora=test, term="IPA")
print(beer)
print(craft_beer)
print(ipa)
```


Calculate sum of all the items in array list?

Naming

s is a bad parameter name. If there's nothing better, use editable.

Avoid abbreviations. itemTot might be better as itemTotalValue.

Use camelCase. newsum should be newSum.

It's confusing that textViewSum doesn't actually hold the sum.

Implementation

Don't declare id as 0 and then reassign it right away. Just declare it as what it should be, and make it final because it won't be reassigned.

Guard clauses are very helpful for keeping code from looking like a big > sign. Not an issue now, but it might be if more code gets added to this method.

Don't declare itemtot until it's actually needed. You might leave the method before using the value.

You don't need an entire double[] to hold your computations. You only need one double variable declared inside the for loop.

It might be nice if there were parens to clarify the cast is before the division. Also, you don't need to cast to double. Dividing by 100.0 makes the result a double even though the dividend is a long.

It's ugly to use string concatenation to turn a double into a String. Java provides a method (Double.toString()) for simple conversions, and a class (NumberFormat) for complex conversions. Or you can use String.format(), which is a bit newfangled for me, but I hear the kids love it.

Result

If you were to apply all these suggestions your code might look something like:

@Override
public void afterTextChanged(final Editable editable) {

    final int id = (int) itemtotal.getTag();
    if ((id < 0) || (id > totals.size())) {
        return;
    }

    final String itemTotalValue = itemtotal.getText().toString();
    totals.set(id - 1, itemTotalValue);

    double newSum = 0.0d;
    for (int i = 0; i < totals.size(); ++i) {
        final double value = Double.parseDouble(totals.get(i));
        newSum += Math.round(value * 100) / 100.0;
    }

    final double sum = Math.round((newSum * 0.02 + newSum) * 100.0) / 100.0;
    textViewSum.setText(Double.toString(sum));

    final double vat = Math.round((newSum * 0.02) * 100.0) / 100.0;
    textViewVat.setText(Double.toString(vat));
}


Overloading Java function (insert into binary tree)

Just have one insert method call the other. In your code, that would look like:

public final class BinaryTree {

    public Node head;

    public BinaryTree() {
        this.head = null;
    }

    private class Node {
        private final int data;
        private final Node left;
        private final Node right;
        private int size;

        public Node(final int d) {
            this.data = d;
            this.left = null;
            this.right = null;
            this.size = 1;
        }
    }

    public Node insert(final int d) {
        if (this.head == null) {
            this.head = new Node(d);
            return this.head;
        }

        return this.insert(this.head, d);
    }

    private Node insert(final Node n, final int d) {
        if (n == null) {
            return new Node(d);
        }

        n.size++;
        if (n.left == null) {
            return this.insert(n.left, d);
        }
        if (n.right == null) {
            return this.insert(n.right, d);
        }
        if (n.left.size <= n.right.size) {
            return this.insert(n.left, d);
        }
        if (n.left.size > n.right.size) {
            return this.insert(n.right, d);
        }
        return null;
    }
}


This looks good to me,

As you mentioned, as_view stands out a bit, but I see where you are coming from
I am not sure why you do not declare GET and POST, then you do not need to use toLowerCase(), are you worried the caller will now uppercase the verbs?
You should think about error handling, you should have some framework for it

All in all, I would still suggest that learning and using Express.js might be worth it.


Non-persistent storage for key-value pairs

You didn't say if you were able to use ES6 or not, but here's how I would do it if you can.  Note this solution ensures that you won't return or overwrite values that are on the Object prototype of the storage. It's also somewhat more terse, if you get rid of my comments.

const storingFn = (function(){
  const store = {};

  return (key, value) => {
    // you only want to return things that are on 'store' not on its ancestral prototype.
    if(store.hasOwnProperty(key)) {
      return store[key];
    }

    // If we get here, we know it's a set operation, so I'm assuming we need to quietly avoid setting null keys. Throw an error if you prefer.
    if (value === 'undefined') {
      return null;
    }
    // I didn't test with < ES6, as written it doesn't allow overwrite of 'toString' for example.
    store[key] = value;
    return value;
  }
})();

EDIT:

I also decided to actually return the value in the key, regardless of whether we are setting or getting, as your question didn't specify which was appropriate and I thought this gave a more consistent interface.

If you need to return false if the key is already set (right now it'll return the unchanged value) then that's a simple change to the first conditional block.


You want a data structure that supports efficiently manipulating head and tail. Usually we call that a deque, a double-ended queue, sometimes implemented with linked lists.

As I look at your diagram, the containers on top and bottom in some sense hold the same R,B,Y sequence of items, just in cyclic permutation. So why don't you consider using a simple array of size N, with head and tail indices that you increment mod N ? Then you only incur expensive memory copies when an effect finally completes.


Factory method to create two kinds of cars based on an enum

Do not name things with data type prefixes

clsAutoFactory.  No.  Instead: AutoFactory

Names should be what they are in the problem domain - autos in this case. How a thing is implemented - is it an array? a class? an integer? etc. is not what's important, we can read code and the IDE is real smart. Writing code that is descriptive is the thing.

Unnecessary interfaces

There is no reason for any interfaces at this point. Just inherit from Auto class. Half the code goes away! Perhaps make it an abstract class and override methods as needed. I bet there is common code and/or default behavior.

In general interfaces are for giving unrelated classes similar behavior. A Parrot might implement the Idogable so it can bark like a dog even though a Parrot is not a Dog. But a BMW is an Auto.

  I am implementing the factory method

You wrote a factory class not a factory method.

A factory method would be a method in some other class that does the factory thing. The code simple enough at this point that you could create a factory method - say a method in the Auto class; but I am not saying you should.

There are 3 "levels" of factory design which facilitates increasing construction complexity. i.e. factory method, factory (a simple class), and abstract factory for very complex things. The abstract factory may be appropriate if you were creating multiple auto makes with multiple models with multiple individual options; and perhaps different kinds like SUV, sports car, truck.

Ditto to what @JAD said

switch default

this is a perfect place for catching errors. If the default case is hit then obviously that model has not been implemented in your code. So capture that fact and let the user know.

Be more specific with auto instance names. model is too generic.

Not this:

IAuto model = factory.createModel(ModelType.Audi);
model.start();
model.stop();

but this:

IAuto myAudi = factory.createModel(ModelType.Audi);
myAudi.start();
myAudi.stop();


For testing your code following assumption are made

Sub Entry_Point was disabling screen updating, events and display alerts.
Sub Exit_Point was enabling screen updating, events and display alerts.
It is being used for importing data from multiple files and to be finally placed in SheetShMN one below another

according to the above assumption following modification was done

1 Sheet ShMN is being cleared with in loop For FileCnt = 1 To UBound(FiletoOpen) with line ShMN.Rows("2:" & ShMN.Rows.Count).ClearContents. I pulled out the line out of the For loop for testing purpose.

2.The line  ShMN.Cells(2, c).PasteSpecial modifed to ShMN.Cells(lastRow, c).PasteSpecial for placing data from each file one below another (This to avoid 1st files data to be overwritten by subsequent files data).

Finally as the cause of slow performance, it is found the Case Changing codes are placed inside header finding loop.So it is executing Number of files X Number of columns times. I pulled it out of even file loop and placed just after completion of Data import.
Myrange was defined "B2:B" & Rows Count. I change it to Set MyRange = ShMN.Range("B2:B" & ShMN.Cells(Rows.Count, 2).End(xlUp).Row)

For Testing purpose, I used 5 files consisting same Data of 500 rows X 52 Columns with header. I have not used Calculation mode manual, Screen update disable etc (as I generally don't prefer these). You may use the techniques as per your requirement. It takes around 50 seconds to import all 5 files data and only another 3 odd seconds to change the case of B column (in my old laptop)

My test code:

Option Explicit
Sub test()
Dim Tm As Long
Dim FiletoOpen As Variant, ShDataN As Worksheet, ShMN As Worksheet
Dim FileCnt As Long, SelectedBook As Workbook, MyRange As Range, cell As Range
Tm = Timer
Set ShDataN = ThisWorkbook.Sheets(1)
Set ShMN = ThisWorkbook.Sheets(2)

    Dim lastRow As Long, LastTemp As Long 'lasttemp is "last row for table template
    Const StartRowTemp As Byte = 1
    Dim c As Byte 'number of columns
    Dim GetHeader As Range   'find

    'Call Entry_Point 'to prevent screen updating and display alert, the value is False
    'Application.ScreenUpdating = False
    'Application.EnableEvents = False
    Application.DisplayAlerts = False
'    On Error GoTo Handle

    'pick files to import - allow multiselect
    FiletoOpen = Application.GetOpenFilename _
    (FileFilter:="Excel Files (*.xlsx), *.xlsx", Title:="Select Workbook to Import", MultiSelect:=True)

    If IsArray(FiletoOpen) Then
    'delete the content from Analysis table
    ShMN.Rows("2:" & ShMN.Rows.Count).ClearContents   ' moved out of For foleCnt loop

        For FileCnt = 1 To UBound(FiletoOpen)
        Set SelectedBook = Workbooks.Open(Filename:=FiletoOpen(FileCnt))
        ShDataN.Cells.Clear
        SelectedBook.Worksheets("Client").Cells.Copy
        ShDataN.Range("A1").PasteSpecial xlPasteValuesAndNumberFormats
        SelectedBook.Close False

        'locate last empty row in Monthly Table
        lastRow = ShMN.Cells(Rows.Count, 1).End(xlUp).Row + 1

        'locate last row in the new data
        LastTemp = ShDataN.Cells(Rows.Count, 1).End(xlUp).Row

        'do while to find matching headers before copy paste
        c = 1
        Do While ShMN.Cells(1, c) <> ""

        Set GetHeader = ShDataN.Rows(StartRowTemp).Find _
        (What:=ShMN.Cells(1, c).Value, LookIn:=xlValues, MatchCase:=False, lookat:=xlWhole)
        If Not GetHeader Is Nothing Then
            ShDataN.Range(ShDataN.Cells(StartRowTemp + 1, GetHeader.Column), ShDataN.Cells(LastTemp, GetHeader.Column)).Copy
            ShMN.Cells(lastRow, c).PasteSpecial               ' row 2 modified to lastRow
            ShMN.Rows("2:" & ShMN.Rows.Count).ClearFormats
'            Call Range_Case
             'to change the case on column Client's name after copying

        End If 'get Header
        c = c + 1
       Loop

        Next FileCnt

Debug.Print Timer - Tm
Dim MyArr As Variant, FinalArr() As Variant, i As Long
                Set MyRange = ShMN.Range("B2:B" & ShMN.Cells(Rows.Count, 2).End(xlUp).Row)

                'For Each cell In MyRange
                'cell.Value = UCase(cell)
                'Next cell

                MyArr = MyRange.Value
                ReDim FinalArr(LBound(MyArr, 1) To UBound(MyArr, 1))
                For i = LBound(MyArr, 1) To UBound(MyArr, 1)
                FinalArr(i) = UCase(MyArr(i, 1))
                Next

                MyRange.Value = FinalArr

        'MsgBox "Data imported sucessfully", vbInformation, "General Information"

    End If 'isArray
    ShDataN.Cells.Clear

    'With ShNote
    '    .Select
    '    .Range("A1").Select
    'End With

    Application.ScreenUpdating = True
    Application.EnableEvents = True
    Application.DisplayAlerts = True

Debug.Print Timer - Tm
End Sub

Finally I tried the case changing with arrays to minimize excel cell operations as my ethic. You may use your process (commented out). it hardly affect performance in this case.


You are using async/await absolutely correctly, that's how they were supposed to be used.

Please note that from this code it's hard to tell whether the method will return the Task immediately, since it will be waiting synchronously for rasterize method to return the Task, and thus the answer depends on the implementation of rasterize.

As a side note - you are using implicit dependency here (first method prepares files in folder, and second method enumerates all pdf files there). I would prefer explicit dependency: rasterize to return a collection of FileInfo objects consumed by the concatenatePdfs method.


Overall

Ohhhhh.

  Is it well-formed?

It compiles, so yes.

  i.e. does it follow common C++ standard and patterns (for example, should private members be declared before public ones?

Personally I think so.

* Private Variables
* Public
    * Constuctor / Destructor
    * Copy Semantics
    * Move Semantics
    * Swap
    * Other Public Interface
    * Friends
* Private
    * Methods as appropriate

When reading the code I want to know the members so I can verify that the constructors initialize them all, as a result I usually put them first. But other people prefer to put all private stuff at the bottom.

  Am I missing something regarding functionality?

Yes. Quite a lot.

  Is there maybe a bug in my code that I'm not seeing?

Yes. It potentially leaks on assignment.

Code Review

Constructing from object!

    unique_ptr(T& t) {
       _ptr = &t;
    }

That's exceedingly dangerous:

{
    int x;
    unique_ptr<int>  data(x);
}
// Here the unique ptr calls delete on an automatic variable.

Use member initializing list.

You should always attempt to use the member initializer list for initializing members. Any non-trivial object will have its constructor called before the initializer code is called and thus it is inefficient to then re-initialize it in the code.

    unique_ptr(unique_ptr<T>&& uptr)
        : _ptr(std::move(uptr.ptr))
    {
       uptr._ptr = nullptr;
    }

Member variable Names

Prefer not to use _ as the first character in an identifier name.

T* _ptr;  // Technically OK.

Even if you know all the rules of when to use them most people don't so they are best avoided. If you must have a prefix to identify members use m_ - but if you name your member variables well then there is no need for any prefix (in my opinion prefixes makes the code worse not better, because you are relying on unwritten rules. If you have good well-defined names (see self-documenting code) then members should be obvious).

NoExcept

The move operators should be marked as noexcept.

When used with standard containers this will enable certain optimizations. This is because if the move is noexcept then certain operations can be guaranteed to work and thus provide the strong exception guarantee.

    unique_ptr(unique_ptr<T>&& uptr) noexcept
                              //     ^^^^^^^^

    unique_ptr<T>& operator=(unique_ptr<T>&& uptr) noexcept
                                            //     ^^^^^^^^

Leak in assignment

Note: Your current assignment potentially leaks. If this currently has a pointer assigned then you overwrite it without freeing.

    unique_ptr<T>& operator=(unique_ptr<T>&& uptr) {
       if (this == uptr) return *this;

       // Here you overwrite _ptr
       // But if it has a value then you have just leaked it.
       _ptr = std::move(uptr._ptr);

       uptr._ptr = nullptr;
       return *this;
    }

Checking for this pessimization

    unique_ptr<T>& operator=(unique_ptr<T>&& uptr) {
       if (this == uptr) return *this;
       _ptr = std::move(uptr._ptr);
       uptr._ptr = nullptr;
       return *this;
    }

Yes you do need to make it work when there is self assignment. But in real code the self assignment happens so infrequently that this test becomes a pessimization on the normal case (same applies for copy operation). There have been studies on this (please somebody post a link; I have lost mine and would like to add it back to my notes).

The standard way of implementing move is via swap. Just like Copy is normally implemented by Copy and Swap.

    unique_ptr(unique_ptr<T>&& uptr) noexcept
        : _ptr(nullptr)
    {
        this->swap(uptr);
    }
    unique_ptr<T>& operator=(unique_ptr<T>&& uptr) noexcept
    {
        this->swap(uptr);
        return *this;
    }
    void swap(unique_ptr<T>& other) noexcept
    {
        using std::swap;
        swap(_ptr, other._ptr);
    }

Using the swap technique also delays the calling of the destructor on the pointer for the current object. Which means that it can potentially be re-used. But if it is going out of scope the unique_ptr destructor will correctly destroy it.

Summary

Good first try but still lots of issues.

Please read the article I wrote on unique_ptr and shared_ptr for lots more things you should implement.

Smart-Pointer - Unique Pointer
Smart-Pointer - Shared Pointer
Smart-Pointer - Constructors

Some things you missed:

Constructor with nullptr
Constructor from derived type
Casting to bool
Checking for empty
Guaranteeing delete on construction failure.
Implicit construction issues
Dereferencing

When you have read all three articles then the bare bones unique_ptr looks like this:

namespace ThorsAnvil
{
    template<typename T>
    class UP
    {
        T*   data;
        public:
            UP()
                : data(nullptr)
            {}
            // Explicit constructor
            explicit UP(T* data)
                : data(data)
            {}
            ~UP()
            {
                delete data;
            }

            // Constructor/Assignment that binds to nullptr
            // This makes usage with nullptr cleaner
            UP(std::nullptr_t)
                : data(nullptr)
            {}
            UP& operator=(std::nullptr_t)
            {
                reset();
                return *this;
            }

            // Constructor/Assignment that allows move semantics
            UP(UP&& moving) noexcept
            {
                moving.swap(*this);
            }
            UP& operator=(UP&& moving) noexcept
            {
                moving.swap(*this);
                return *this;
            }

            // Constructor/Assignment for use with types derived from T
            template<typename U>
            UP(UP<U>&& moving)
            {
                UP<T>   tmp(moving.release());
                tmp.swap(*this);
            }
            template<typename U>
            UP& operator=(UP<U>&& moving)
            {
                UP<T>    tmp(moving.release());
                tmp.swap(*this);
                return *this;
            }

            // Remove compiler generated copy semantics.
            UP(UP const&)            = delete;
            UP& operator=(UP const&) = delete;

            // Const correct access owned object
            T* operator->() const {return data;}
            T& operator*()  const {return *data;}

            // Access to smart pointer state
            T* get()                 const {return data;}
            explicit operator bool() const {return data;}

            // Modify object state
            T* release() noexcept
            {
                T* result = nullptr;
                std::swap(result, data);
                return result;
            }
            void swap(UP& src) noexcept
            {
                std::swap(data, src.data);
            }
            void reset()
            {
                T* tmp = release();
                delete tmp;
            }
    };
    template<typename T>
    void swap(UP<T>& lhs, UP<T>& rhs)
    {
        lhs.swap(rhs);
    }
}

Test to make sure it compiles:

struct X {};
struct Y: public X {};

int main()
{
    ThorsAnvil::UP<X>   x(new X);
    ThorsAnvil::UP<Y>   y(new Y);

    x   = std::move(y);                  // This should be valid
    ThorsAnvil::UP<X>   z(std::move(y)); // This should be valid

    // In both these cases x represents an X* which is a base pointer
    // that should be able to point at objects of type Y* as these
    // are derived from X
}


List 130. Surrounded Regions leetcode solution using bfs

Review

There are a few things that could be improved upon.

1 .Your get_neighbours could use some love

map_direction = {"left":(0, -1), "right":(0, 1), "up":(-1, 0), "down":(1, 0)}

I might understand using a dictionary so you can see which value corresponds to which direction, but this may be simplified to just using a tuple of directions.

_i and __i are variables badly named I believe, maybe new_i or something would be better. _i and __i implies that these variables are private/protected, and in your case they are not.

Secondly I think with this:

increment_col, decrement_row, decrement_col, increment_row = (False, False, False, True)

You reinvent your get_neighbours

2. Use enumerate

I think this was said in your last question you posted on CR too, and it is still valid. You should defenitly use enumerate when possible, see the corresponding PEP article

3. Doing this in one loop

You have:

A while True: loop
Another while loop

This could be done in one loop, by tracking if any of the current visited vertex in the dfs, are in either the last or first (row or collumn)

Alternative code

def get_neighbours(board, position):
    directions = ((0, -1), (0, 1), (-1, 0), (1, 0))
    for direction in directions:
        new_x, new_y = (p+d for d, p in zip(direction, position))
        if new_x in range(0, len(board) - 1) and new_y in range(0, len(board[0]) - 1):
            yield new_x, new_y

def dfs(board, start):
    visited, stack = set(), [start]
    change = True

    while stack:
        vertex = stack.pop()
        if vertex not in visited:
            if change and (vertex[0] in (0, len(board) - 1) or vertex[1] in (0, len(board[0]) - 1)):
                change = False
            visited.add(vertex)
            for x, y in get_neighbours(board, vertex):
                if (x, y) not in visited  and board[x][y] == "O":
                    stack.append((x, y))
    return visited, change

def solve(board):
    visited = set()

    # Group the O's
    for x, row in enumerate(board):
        for y, col in enumerate(row):
            if col == 'O' and (x, y) not in visited:
                group, change = dfs(board, (x, y))
                visited |= group
                if change:
                    for o in group:
                        board[o[0]][o[1]] = "X"

    return board

if __name__ == '__main__':
    board = [["X", "X", "X", "X"],
             ["X", "O", "O", "X"],
             ["X", "X", "O", "X"],
             ["X", "O", "X", "X"]]
    print(solve(board))


Perhaps if this method:

this.userDao.getUser(entity);

Accepted just a String as input (the username?) and possibly a password, you could then call it without having to mess around creating the UserEntity beans.

So this:

UserEntity entity = new UserEntity();
BeanUtils.copyProperties(bean, entity);

// Gets user from DB based on UserBean's username and password.
// Returns null if not found.
entity = this.userDao.getUser(entity);

Would become

UserEntity entity = this.userDao.getUser(bean.getUserName());

Maybe rename the entity/bean variable too to some thing that makes it a bit clearer what they are.

Also in the second half of the method, there seems to be no need to copy the properties to a UserBean and then back again. Just update the time since last login on the UserEntity directly.


A code currently in main should be wrapped in its own method (game perhaps).
Business logic shall be performed as high in the call tree as possible. Regarding your code this principle means that neither firstRoll nor moreRolls should call declareResults. The same (questionably) applies to the while loop in moreRolls.

Consider a game skeleton along the lines of

result = firstRoll();
while (result == UNDEFINED)
    result = moreRoll();
declareResults();

moreRolls creates a Scanner and never uses it.
causeOfWin and causeOfLose are mutually dependent. You don't need two distinct variables: cause would be enough.


Python AES-CBC implementation using AES-ECB

Try to follow PEP8. Just a few little things like when assigning defaults to arguments don't put spaces around the =; two spaces between functions and imports; [i : i + 16] -> [i: i + 16]. Very minor stuff but adds up over a larger piece of code.
Avoid assigning variables to small bits of logic if they're only going to be used once. e.g.:

ret = val + chr(remaining).encode() * remaining
return ret

Could become:

return val + chr(remaining).encode() * remaining

Your names could be improved for clarity; avoid using vague names like key, var, data, etc.
I like ternary operators so I'd change encrypt_aes_cbc() to:

padded = pkcs7(data) if pad else data

You can do something similar in decrypt_aes_cbc() with your returns.
In fact, I'd extract the second part of the function to a generator and call it in encrpyt_aes_cbc(). By which I mean:

def gen_encrypted(key, iv):
    """Maybe give this function a better name!"""

    for i in range(0, len(padded), 16):
        ...
    yield encrypted

Then change the second half of encrypt_aes_cbc() to call that generator. This nicely compartmentalises your code, removes the need for the encrypted list and should be faster. I can explain this more thoroughly if you're confused about yield.
Your argument block_size=16 in unpkcs7 is not used.
Your indentation is off in pkcs7.
Try to be specific when raising exceptions. What error exactly are you catching? Exceptions also takes a string argument so you can explain the problem. e.g.:

raise IndexError('This is not a valid position in some_list')


Html Templating for a WIP static site generator, written in Javascript

Here's a few pointers to help out:

I see you're using both let and var in there - be consistent and just choose one.
You're escaping a lot of regular expression characters that don't need to be escaped - it makes the regex less readable. i.e. /\<\!\-\- template:(?<label>(?:(?!\<\!\-\-).)+) \-\-\>/g could be written as /<!-- template:(?<label>(?:(?!<!--).)+) -->/g
Often it's good to name functions as verbs. i.e. just rename dataInject to injectData and fileInject to injectFile, it reads better.
Right now, if there was an error reading the template file, you'll always get the same message logged: error injecting file '<file name>'. It doesn't matter if node didn't have permission to access it, or if the file did not exist, you won't get any more information besides that log message. What's worse, you don't rethrow any error, so the program will continue trying to run even though the template has issues. I would just take out the try-catch completely, the original error usually has the most useful information to help debug problems.
I assume this injection logic is meant to be used by a server. With that use case in mind, you don't want to use the sync versions of the file-system functions - it means the server is unable to handle any other request while it's doing a file operation. Instead of fs.readFileSync(), use fs.readFile(), or even better, fs.promises.readFile().
The if (!matches.includes(match)) line isn't doing anything. matches is an array of arrays while match is a match object, match will never be inside matches.
Any reason why data is a list of lists and not an object (or a Map)? Why not just have data equal { one: 'apple', three: 'orange', ... }. If some function needs it in the list-of-list format, it can just call Object.entries() on it.
Finally, I just want to warn against re-inventing the wheel. There's plenty of great templating systems already out there (i.e. handlebars.js) that come with plenty of great features and built-in XSS protection. If your codebase only needs templates in one or two places, then I can understand preferring to throw together something simple instead of adding a new dependency, but if you're going to be using these templates a lot, it might be better to use a pre-built solution instead of maintaining your own.


Counting the number of increasing sub-sequences

\$\newcommand{\sub}[1]{\text{sub}_{#1}}\$
This is more of an alternative algorithm than a review on your code (at least for now), but it seems like both could be helpful.

A good algorithm results from solving a slightly more informative version of the problem, which is simpler to decompose:

  \$\sub{s}^n\$ is the number of subsequences of \$s\$ that are ordered and end with the digit \$n\$.

\$\sub{s}\$ can be stored in a 10-long array, the sum of which solves your original problem:

$$
\left[\ \sub{s}^0;\ \text{sub}_s^1;\ \text{sub}_s^2;\ \ldots;\ \text{sub}_s^9\ \right]
$$

Clearly, for the empty string \$\varnothing\$, we have

$$
\text{sub}_\varnothing = \left[\ 0;\ 0;\ 0;\ \ldots;\ 0\ \right]
$$

The interesting trick is that extending a string \$s\$ with digit \$d\$ is a simple update

$$
\sub{sd}^n =
\begin{cases}
\sub{s}^n & \text{if}\;n \ne d\\
1 + \sum_{i=0}^{n} \sub{s}^i & \text{if}\;n = d
\end{cases}
$$

as the paths for subsequences that don't end in \$d\$ are unchanged and the subsequences that do end in \$d\$ are \$d\$ itself, \$d\$ added to the end of any prior subsequence that ends in a digit less than \$d\$, or any of the prior subsequences that did end with the digit already.


R function to generate predictions from ratings

Without exact your data I could think of some improvements.
Trying to avoid redundant operations.

# order data.frame by users and movies
probe_test <- probe_test[with(probe_test, order(user, move)), ]
# initialize resulting column
probe_test$res <- rep(as.numeric(NA), nrow(probe_test))

knn_txt_red <- knn_txt[, 1:100] # reduce outside of the loop
for (user in unique(probe_test$user)) { # for each unique user
  u_row <- which(U_lookup == user)[1] # get your id
  knn_match <- knn_txt_red[u_row, ]
  knn_match1 <- as.numeric(unlist(knn_match))
  userI <- probe_test$user == user
  movies <- probe_test$movie[userI] #get all user movies
  m_row <- which(M_lookup %in% movies) # get indexes
  dfm_mov <- dfm[knn_match1, m_row] #select all cols of those movies for user
  x <- colMeans(dfm_mov) # calculate mean for each row
  probe_test[userI, 'res'] <- x # add the results to data.frame
}

As I do not have your data, there are probably/maybe some errors in code.

There are probably better ways to do this, but as I mentioned, it is hard to think of any without any example data.


Never omit "optional" braces, as you did for your first if statement.  That's a bad habit that will eventually lead to a coding accident.  If you feel compelled to omit braces, then at least put the whole statement on the same line.

You should avoid unnecessary mutation, as you did with arr++.  This is  especially important with an exercise in recursion: it is one of the principles of functional-programming.

The curr_max parameter is annoying and unnecessary.  It also leads to a bug with negative array members, when a poorly selected initial value is chosen.  (You should use INT_MIN from <limits.h> instead of 0.)  Furthermore, your base case is questionable: is the maximum of a zero-length array well defined?

Suggested solution

#include <assert.h>

int max_val(int arr[], size_t length)
{
    assert(length > 0);
    if (length == 1) return arr[0];
    int max_tail = max_val(arr + 1, length - 1);
    return arr[0] > max_tail ? arr[0] : max_tail;
}


Search Function With Wildcard in Haskell

Update

Yes, that's better.

Here is a version of your code that uses pattern matching more and guards less. I think it is clearer.

ssearch _ [] = 0
ssearch [] _ = 0
ssearch ('*' : _) _ = error "no '*' allowed in hay" --no confusion with wildcard things
ssearch haystack ('*' : needles) = ssearch haystack needles --removes '*', and then searches through hay for the char after the '*'
ssearch (hay:haystack) (needle:needles)
  | needle == hay = search2 haystack needles + ssearch haystack (needle:needles)
    where
    search2 _ [] = 1
    search2 [] _ = 0
    search2 ('*' : _) _ = error "no '*' allowed in hay" -- I need to declare this twice because search2 often jumps ahead of ssearch.
    search2 _ ['*'] = 1
    search2 haystack ('*' : needles) = ssearch haystack needles
    search2 (hay:haystack) (needle:needles)
      | needle == hay = search2 haystack needles
    search2 _ _ = 0
ssearch (_:haystack) needles = ssearch haystack needles

There may still be bugs, but I can't see any :-)

Original

It appears to be buggy.

I expect search "hello" "he*lo" to result in 1, but it gives me 0.
I expect search "chanchance" "chance" to result in 1, but it gives me 0.

Also

search "bobobob" "bob" results in 2, but perhaps it should result in 3. Whether or not you want your function to count overlapping matches, you should document that it does/doesn't.

You need to rethink your algorithm. (Edit: as you are learning Haskell, I presume you'd rather get your function working yourself, rather than have us spoon-feed you a working version.)
x and y are not very descriptive names. They are suitable when you are writing generic code, but this code is more specific. I would call them haystack and needle instead (from the common English phrase).
This line:

  | (y == '*') && ((head ys) == '*') = error "You can not include two '**' in a row, that messes up the wildcard operator"

ys may be [], so head ys may be an error. You should be using pattern matching instead of head (and often instead of comparing to [] as well).
Why should a second * be an error anyway? The second * should successfully match a run of 0 characters, surely?


Improving readability of non-recursive depth first search function in Lisp

This usage of LOOP is not supported by ANSI Common Lisp. You can't have an UNTIL clause (only in a main clause in LOOP syntax) before a FOR clause (a variable clause).

See: Macro LOOP.


Prime pair set finder (Project Euler problem 60)

This is not so much of a code review question as it is an algorithm review question.

You are calling dig_sum() way too much.  You want pairs of primes, which summed together are not a multiple of 3: p1 + p2 != 3n.   If p1 % 3 == 1 and p2 % 3 == 2, then these primes must not be paired together.  This implies you can partition Primes into two sets: P1 and P2.

P1 = [ p for p in Primes if p % 3 != 2]
P2 = [ p for p in Primes if p % 3 != 1]

Note that 3 is actually part of both sets.

You can then solve the problem using primes from one set, then the other, and choose the lowest sum.

This gives 2 speed ups:

Half of the pairs are never considered, being from opposite sets.
dig_sum() need never be called, since the pairs will never equal 3.

Your prime(N) function can be sped up.   You are testing for prime by testing for divisibility by all values from 2 to sqrt(N).  You only need to test for divisibility by prime numbers in that range ... and you have a list of Primes.  Of course building the list of prime numbers using the prime(N) function, while using that list of prime numbers in that function is a bit of an conundrum... but not impossible.  Watch out for special cases.

You could also test if the number is prime by asking if N in Primes:.  Making Primes as set() would speed that up, but may also have a disadvantage; consider the pros and cons.

Glad to see you are making progress!

Your next improvement will come from further reducing the set of primes you are trying to pair with.  for i in P1 is better than for i in Primes because half the primes weren’t even tested.  We will further reduce the primes into smaller sets:

If you collect primes from P1 which pair with 3, and then you search the entire P1 space again looking for another prime which pairs with both numbers, you are retesting primes you’ve already rejected.

Instead: collect all primes from P1 which pair with 3.  Call that set P1{3}.  Then, for each number i in that set, you could look for other numbers j in this smaller set which form a conforming pair.

Better: compute all sets P1{i}.  Then you can do set intersections: P1{3} & P1{i}.  All numbers j in that intersection form conforming triples (3,i,j).

All numbers k in the intersect P1{3} & P1{i} & P1{j} will form conforming quadruples (3,i,j,k).

And so on.


Using RxJava-Math you can achieve the same result by this way:

List<Transaction> transactions = createRandomTransactions(10);

final Observable<Float> amountStream = Observable.from(transactions)
        .map(transaction -> transaction.amount);

MathObservable.averageFloat(amountStream)
        .map(mean -> String.format(Locale.US, "The mean is %.2f", mean))
        .subscribe(System.out::println);

Hope that helps!


Readability of array_* vs foreach in PHP for filtering and extracting

If your functional code is a filter and then a map it's likely a good candidate for array_reduce.

One of the main advantages of a function first approach here is that you can name the inner operation (the filtering operation), but using a closure (or a foreach) robs of you of a name (which could have been used to signal intent) and often robs of us of reuse so wrap the Closure in a named, reusable context (another named function).

A named function will also allow us to pre-inject the variable $selectedPeople into the Closure before array_ functions interact with the Closure inside.

See: http://www.phptherightway.com/pages/Functional-Programming.html for more information on this.

Now we can type hint all the inputs.

function selected_attendee_names(array $selectedPeople) : Closure {
  return function (array $attendeeNames, array $attendee) use ($selectedPeople) : array {
    $isSelectedAttendee = in_array($attendee['id'], $selectedPeople);
    $isSelectedAttendee ? $attendeeNames[] = $attendee['name'] : NULL;
    return $attendeeNames;
  };
}

$attendeeNames = array_reduce($allPeope, selected_attendee_names($selectedPeople), []);

Another approach that could have increased reuse is to array_filter and then use array_column.

function is_selected_attendee(array $selectedPeople) : Closure {
  return function (array $attendee) use ($selectedPeople) : bool {
      $isSelectedAttendee = in_array($attendee['id'], $selectedPeople);
      return $isSelectedAttendee;
  };
}

$selected_attendees = array_filter($allPeople, is_selected_attendee($selectedPeople));
$selected_attendees_names = array_column($selected_attendees, 'name');

Generally speaking I'd prefer the bottom approach because you'll usually find you want to do something else with the selected attendees later in your program.


My last AI course was too long time ago so just some generic notes and some modifications for easier testing.

Fields should be private. (Item 13 of Effective Java 2nd Edition: Minimize the accessibility of classes and members)
IGame could be Game.

  I don’t want my users knowing that I’m handing them an interface.
  I just want them to know that it’s a ShapeFactory.

Source: Clean Code by Robert C. Martin, Interfaces and Implementations, p24
Class names should be nouns, instead of verbs, like Search:

  Class and Interface Type Names

  Names of class types should be descriptive nouns or noun phrases, not overly long, in mixed
  case with the first letter of each word capitalized.

Source: The Java Language Specification, Java SE 7 Edition, 6.1 Declarations
What is ply? I guess maxDepth would be a more descriptive name.
Short variable names (like g) are not too readable. I suppose you have autocomplete, so using longer names does not mean more typing but it would help readers and maintainers a lot since they don't have to remember the purpose of each variable - the name would express the programmers intent. (Clean Code by Robert C. Martin, Avoid Mental Mapping, p25)

Make it testable

  Good design is testable, and design that isn't testable is bad.

(Source Michael C. Feathers: Working Effectively with Legacy Code)

I made some changes in the API (Game and Move classes to make it easier to test).

I've added a Move parameter to the generateMoves() method to make it stateless. It results easier mocking since the output only depends only on the input parameter.
I'm using move.isLeaf() instead of g.isGameFinished() (for the same reason). It could be game.isFinishingMove(Move move) too but the former was simpler.
I've created a new method for the Move class:

public String getName() { ... }

It will helper when we'll verificate the test results.
I've also changed the loop to a foreach. It also eliminated the duplicated gameMove[i] access.

So, the AlphaBetaSearcher class is the following now:

private Move bestMove;

public Move findBestMove(int maxDepth, Game game, Move root) {
    bestMove = null;
    alpha_beta(maxDepth, game, root,
        Integer.MIN_VALUE, Integer.MAX_VALUE);
    return bestMove;
}

private int alpha_beta(final int depth, final Game game,
        final Move move, int alpha, final int beta) {
    if (depth == 0 || move.isLeaf()) {
        return game.getScore();
    }

    final Move[] moves = game.generateMoves(move);
    for (final Move currentMove: moves) {
        game.execute(currentMove);
        final int score =
            -alpha_beta(depth - 1, game, currentMove, -beta, -alpha);
        game.undo(currentMove);

        if (alpha < score) {
            alpha = score;
            bestMove = currentMove;
        }
        if (beta <= alpha) {
            return alpha;
        }
    }
    return alpha;
}

Test data

For the test below I've used the leftmost part of the sample tree from Wikipedia.

Test framework

I'm using Mockito and JUnit here. A mocking framework makes possible to test the Alpha-beta implementation without the actual Game and Move classes. In isolation you can make sure that the pruning works well before you integrate it into the game. If it isn't completely bug-free it's easier to debug and modify in isolation.

JUnit tests are self-checking, you don't have to check the output and decide if it's OK or not. The assert* assertion methods throws an exception when the tested class does not return the excepted value.

Test code

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class AlphaBetaSearcherOrigTest {

    private final AlphaBetaSearcherOrig searcher =
        new AlphaBetaSearcherOrig();

    // Mockito creates a dummy, programmable Game instance for us
    @Mock
    private Game game;

    @Test
    public void testSubTree() {
        // we are creating the move tree with names and scores
        final Move root = createMockedMove("root");
        final Move moveA = createMockedMove("A");
        final Move moveB = createMockedMove("B");
        final Move moveAA = createLeafMove("AA", 5);
        final Move moveAB = createLeafMove("AB", 6);
        final Move moveBA = createLeafMove("BA", 7);
        final Move moveBB = createLeafMove("BB", 4);
        final Move moveBC = createLeafMove("BC", 5);

        // programming the dummy Game instance
        // calling generateMoves() with the root node will
        // return moveA and moveB
        when(game.generateMoves(root)).
            thenReturn(newMoveArray(moveA, moveB));
        when(game.generateMoves(moveA)).
            thenReturn(newMoveArray(moveAA, moveAB));
        when(game.generateMoves(moveB)).
            thenReturn(newMoveArray(moveBA, moveBB, moveBC));

        final Move bestMove = searcher.findBestMove(5, game, root);
        // checking the name of the best move
        assertEquals("BA", bestMove.getName());
    }

    private Move createMockedMove(String name) {
        // creating a dummy/programmable Move instance
        // whose getName() method will return name
        final Move mock = mock(Move.class);
        when(mock.getName()).thenReturn(name);
        return mock;
    }

    private Move createLeafMove(String name, int score) {
        final Move move = createMockedMove(name);
        when(move.isLeaf()).thenReturn(true);
        when(move.getScore()).thenReturn(score);
        return move;
    }

    private Move[] newMoveArray(Move... moves) {
        return moves;
    }
}

The algorithm currently return with BA. If I'm right it should be A but I'm really not sure.


Change the navigation ul li based on the clicked country

From a once over:

Using each seems overkill, this works:

$.fn.myWidget = function () {
    this.click( function (e) {
        if (e) {
            e.preventDefault ();
        }
        combine_all(this);
    });
};

This code assigns the same function to all elements in this, the function has this as the clicked element, so that is why you provide to combine_all
JavaScript uses lowerCamelCase so combine_all -> combineAll, also combineAll is not enlightening as function names go
Your code is repetitive to determine the links, for starters you could do something like this:

var country_links = {
  uk     : [ 'UK stuff', 'UK phones' ]
  europe : [ 'EU stuff', 'EU phones' ]
  italy  : [ 'Italy stuff', 'Italy phones' ]
  germany: [ 'Germany stuff', 'Germany phones' ]
};

 this.updateNavigation = function(my_region){
      var oldNavigation = $('#navigation').find('ul'),
          menuItems = country_links[ my_region.split('_')[0] ];
          newNavigation = '
';
       for( var i = 0 ; i < menuItems.length ; i ++ ){
           newNavigation += '
' + menuItems[i] + '
';
       }
       newNavigation += '
'

      $(old_navigation).hide().html(new_navigation).fadeIn(800);
 };

This is not the only approach, but you split data from style, country_links has all the data. updateNavigation knows how to build a list from that. I did not test this code but you should catch my drift.
To finish on the first point, I would just call all three functions on top instead of combineAll


Reduce repetition in Pandas DataFrame column assignments

Try to get a good book or tutorial about pandas. The things you want to do is relatively easy with groupby.agg

for segment, segment_data in df.groupby("day_segment"):
    aggregated_data = segment_data.resample("D").agg(
        ["sum", "mean", "std", "min", "max"]
    )
    aggregated_data_renamed = aggregated_data.copy()
    aggregated_data_renamed.columns = aggregated_data.columns.droplevel(0).map(
        lambda x: f"step_{segment}_{x}allsteps"
    )

    filename = f"data{segment}.csv"
    aggregated_data_renamed.to_csv(filename, index=True)

This uses mean instead of avg. If this is a problem, you can add another rename function call somewhere


Putting a matrix from a text file into a list

Not sure if it's possible to make this faster. But it can be better:

with open(path_to_file, 'rt') as fh:
    return [[int(value) for value in line.split()] for line in fh]

First of all, you should always use a with ... context manager when working with files. That way you cannot forget to close the file handle after you are done reading from it.

Other improvements:

More natural variable names
Simpler and more compact writing style using a list comprehension

Also keep in mind PEP8, the Python style guide.


Simple program to print from a buffer until a newline is found

I haven't used nasm, but superficially, it looks like you are calling out to the kernel for each character in the string.  This is likely to be a relatively expensive operation.
Looking at this, it would appear that edx can be used to specify the number of characters to output.  With this in mind, it would probably be more efficient to find the string length first and then output the entire string in a single system call.
It's also worth considering breaking up your logic into functions.  This doesn't make a lot of difference with such a small program, however it'll be important as you start trying to do more complex logic.  I'm not sure what the standard calling conventions are, however you could end up with something 'like' this...
global _start

section .data
    input: db `1234567890\n`

section .text
    _exit:
        mov eax, 1
        mov ebx, 0
        int 0x80

    ; Input esi points to string
    ; Output edx contains length
    ; Modifies eax
    _linelen:
        mov eax, esi
        .loop:
            inc eax

            cmp BYTE [eax], 10
            jne .loop
        mov edx, eax
        sub edx, esi
        ret

    ; Input esi points to string
    ;       edx contains string length
    ; Modifies eax, ebx
    _print:
        mov eax, 4
        mov ebx, 1
        int 0x80
        ret

    _start:
        mov esi, input  ; Current head of string

        call _linelen

        mov ecx, esi
        call _print

        call _exit


As always, before tackling the Project Euler problems, do your math homework. Few hints:

Do not brute force. \$\sigma_2(n)\$ is multiplicative. That allows it to be computed in a much more efficient way.
Do not throw away your work. \$\sigma_2(n)\$ does not depend on \$k\$. Tabulate it once toward the maximal possible \$N\$, or extend it as \$N\$ grows.

Besides that, the constraints say \$1 < N < 6\cdot 10^6, 0 < K < 10^6\$. uint_16 is surely insufficient.


Fight the urge to squeeze multiple "things" into one line.  Your script will be easier to read and maintain with all declarations and constructs occupying their own rightful place.  Spend the extra lines, you'll be happy you did a year from now.
Use curly braces to encapsulate language constructs (e.g. if-else and foreach, etc.), this combined with appropriate tabbing will make your script easier to read and help to prevent mishaps when expressing conditional outcomes.  Start but don't stop reading about coding standards here: https://blog.sideci.com/5-php-coding-standards-you-will-love-and-how-to-use-them-adf6a4855696
Instead of murdering your script with die() calls, return a consistent data type no matter the outcome.  In the future, you may change how you want to display/deliver the results. Finally, convert your returned array to json and echo.
When writing variables into a query, you should be using a prepared statement  with placeholders and bound variables.
Avoid single-use and unnecessary variable declarations.  If you have $_SESSION['avatar'] then you don't need to declare $name.
Starting your session is not a conditional thing.  Do it early and do it every time.
You might like to ask yourself why you've elected to write static methods.  This is a topic worth investing some research time into.  Start, but don't stop here: When should I use static methods?

There is more to tell you, but I have run out of time.


Building an index of items from an iterable-of-tuples

Don't use make variables scoped to a function 'private'.
They're 'protected' so please, just remove the _ from them.

If we look at your next block.
You use iter_tup.__next__().
Don't.
Use next!
If you see __{name}__ then you should always check if there is a better way.
And so I'd use:

first = next(iterator, None)
if first is None:
    return {}

The next block to get the length and to rebuild the iterator is fine.

The reduce is fine, I dislike how static it is.
And so if I were to write this function I'd change it.
But it's fine.

I'd change _add_tup_to_idx to just a plain for loop.
Sure it means you mutate something, oh well.
It's much easier to read and understand.
I'd change it to:

dictionary = idx_ctor()
for tup in iter_all:
    reduce(_getitem, tup[:-1], dictionary).append(tup[-1])
return dictionary

Finally I'll go over a few more 'high-level' things. It's much easier to read if you use good variable names.
Take for example:

def build_index(iterator):
    iterator = iter(iterator)
    first = next(iterator)
    if first is None:
        return {}
    depth = len(first) - 1
    iterator = chain([first], iterator)

    ddict = reduce(lambda d, _: partial(defaultdict, d),
                   repeat(None, depth),
                   list)
    dictionary = ddict()
    for item in iterator:
        reduce(getitem, item[:-1], dictionary).append(item[-1])
    return dictionary

Now you seem to put emphasis on it being a hash-tree.
But what do you get if you do:

build_index((('a',), ('b',), ('c',)))

Is it a dictionary, or is it a list?
Now what do you get if you enter these:

build_index((('a', 'b'), ('b', 'c'), ('c', 'd')))
build_index(())

Yes the they return different types.
The above two are dictionary's, and the first is a list.
That is a massive edge case.

I think the design should be based around an infinite default dict.
And for it to always return a dict.
And so you could use the following recursive function:

def ddict():
    return defaultdict(ddict)

Now we just have to change your for loop.
If we slice the string into two at the second to last position,
and remove the item from the list if the second is empty:

dictionary = ddict()
for head, tail in ((i[:-2], i[-2:]) for i in iterable):
    if not tail:
        continue

Now before you say, that's not functional!
Yeah it's half functional, well the comprehension is.
It's easier to read this way, as if Python were a functional based language it'd be more like:

iterable
    .map(i => (i[:-2], i[-2:]))
    .filter(i => i[1])

Now we could do that, but it'd be icky, take:

(i for i in ((i[:-2], i[-2:]) for i in iterable) if i[0])
filter(lambda i: i[0], map(lambda i: (i[:-2], i[-2:]), iterable))

And so they all are the same, so just go for the most readable.

For the last bit, we will do what you were doing before.
But with two changes.
To allow for tail to have a length of one, we need to use extend rather than append.
and to get a list you'll have to use setdefault with a list.

This gives a quite functional function:

def build_index(iterable):
    def ddict():
        return defaultdict(ddict)
    dictionary = ddict()
    for head, tail in ((i[:-2], i[-2:]) for i in iterable):
        if not tail:
            continue
        (reduce(getitem, head, dictionary)
            .setdefault(tail[0], [])
            .extend(tail[1:]))
    return dictionary

You can also change getitem to a function that uses setdefault to remove the need for defaultdict and getitem.


Common Lisp macro: review for code quality & leaky name escaping

This is the sort of thing you want to get as many eyes on as possible. My gut tells me that you'd want to break it up into smaller functions, but I'm not entirely sure where I'd cut. Any chance of getting an example use or test case? Could you explain the reasoning behind using tagbody with a single go rather than a loop?

Preliminary stuff I've noticed

with-gensyms can save you a few lines at the beginning, and you should probably define it in a macro-heavy package.

(defmacro with-gensyms (syms &body body)
  `(let ,(loop for s in syms collect `(,s (gensym)))
     ,@body))

The expression (setf ,result ,@body) might do some odd things if body is composed of multiple expressions. That should probably be (setf ,result (progn ,@body)) instead.


main should be int main()
Why C-style strings? Use std::string
One function - one task. You are mixing 2 things into one function:

Reverse chars in a word
Find words in a sentence separated by spaces

I feel like your problem with too many variables will resolve when you split the tasks you are doing into separate functions.
Use better code formatting (auto-format).
Type mixing - strlen's return value is std::size_t. Do not assign to int. As a follow-up, use a loop index of type std::size_t to match.
This is my preference - not using using namespace std; and system("pause");. I think a lot of posts could be found explaining why.


Applying random luck scores to instances of people

Python has an official style-guide, PEP8. It recommends using PascalCase for classes, so your class should be called Candidate. It also recommends using spaces after a , when passing multiple arguments to a function.
The creation of the candidates is as simple as this:
candidate_list = [Candidate() for _ in range(20000)]

Note that the starting index of range is 0 by default and that I used the customary variable name _ for the unused loop variable.
This also removes having to clear the candidates list, since it is being created anew every time you call the select function.
To get the candidate with the largest score, just use:
best_candidate = max(candidate_list, key=lambda c: c.total_score)

This does not allow you to easily remove them from the list of candidates, though. For this you can use enumerate:
index, candidate = max(enumerate(candidate_list), key=lambda t: t[1].total_score)

However, since you are running a not quite small numerical simulation, you might want to look into using numpy, which would greatly speed up the calculations. Instead of having a Candidate class, just create arrays. Generating random numbers in bulk is vastly faster than doing it one at a time as well:
import numpy as np

iterations = 100
candidates = 20000
top_ten_luck = []

for _ in range(iterations):
    scores = np.random.randint(0, 99, size=(candidates, 3))
    luck = np.random.randint(0, 100, size=candidates)
    total_score = 0.95 * scores.mean(axis=1) + 0.05 * luck
    top_ten = np.argpartition(-total_score, 10)[:10]
    top_ten_luck.extend(luck[top_ten])

print(np.mean(top_ten))

This runs in less than a second (132ms on my machine, to be exact). The for loop can also be vectorized, but at that point you might run into memory constraints.
Note that I used numpy.argpartition to get the indicies of the top ten candidates, in order to only partially sort the data as much as needed and not further. We need to use -total_score because it only gives you minimal values. This should be both faster than poping the maximum value ten times as well as completely sorting the list.


It doesn't look like too many selfs to me.

class Game:

  _rolls = [0] * 21
  _current_roll = 0

  ...

3 things right off the bat:

What's with the blank line between class Game: and _rolls = [0] * 21?
You are using 2 spaces to indent. Use 4 spaces.
Shouldn't this be in the __init__ function?:

_rolls = [0] * 21
_current_roll = 0

So it would look like:

class Game:
    def __init__(self):
        self._rolls = [0] * 21
        self._current_roll = 0

    def roll(self, pins):
        self._rolls[self._current_roll] = pins
        self._current_roll += 1

    ...


First off, your code does not compile, because (at least my just installed) libtcc does not contain a compile function.

As far as I can see it, your code is that slow because you emit a getch() and a putch() when you run across a . (as a side note: according to MSDN, the correct signature for the latter is int putch(int) and both getch() and putch() are deprecated. For portability, you should use int getchar(void) and int putchar(int) anyway).

You must always check the return value of malloc calls, because an allocation request can fail.

You should use a switch instead of multiple if statements for handling the characters, like in the following:

switch (c) {
case '<':
    /* Do work */
    break;
case '>':
    /* Do work */
    break;
case '[':
    /* Do work */
    break;
case ']':
    /* Do work */
    break;
case '+':
    /* Do work */
    break;
case '-':
    /* Do work */
    break;
case '.':
    /* Do work */
    break;
case ',':
    /* Do work */
    break;
default:
    /* Comment */
    break;
}

The advantages are that the intention is more obvious, the compiler may be able to generate better code and it prints an error if you try to handle a character twice.

The main function should always return a value and that value should allow the user to distinguish between a successful compiler run and an error. So you should add a return 0; to the end of the function and add a return 1; (or whatever nonzero value you like) at the end of every error path.

You should always close files you have opened.

Error messages should be printed to stderr, not stdout.

For protection against buffer overflows, you can use snprintf (which is available since C99) instead of sprintf. It returns either a negative value (if an error occurred) or the number of written bytes (excluding the \0 terminator), but it does not write more than size bytes (including the \0 terminator) to the output. Thus you can use

int ret = snprintf(outbuffer, 1024*1024, format, ...);
if (ret < 0 || ret >= 1024*1024) {
    /* Error or overflow */
    free(outbuffer);
    return 1;
}

Another thing you may want to consider is to reduce the memory size by one byte (thus every allowed pos value uses only 16 bits) and then replace

if (pos == 0) pos = 65536;
else pos--;

by

pos = (pos - 1) & 0xFFFF;

and

if (pos == 65536) pos = 0;
else pos++;

by

pos = (pos + 1) & 0xFFFF;

and thus make those two operations branchless. The effect of those two statements is that the operation is carried out on the pos variable, but only the lower 16 bits of the result are used (that is, 65535+1 becomes zero and 0-1 becomes 65535 (*)).

Putting all this together, you would have (including a compile function that can indicate an error and ):

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <libtcc.h>

static int compile(char const *out, char const *buf) {
    TCCState *tcc = tcc_new();
    if (tcc_set_output_type(tcc, TCC_OUTPUT_EXE) < 0) {
        fprintf(stderr, "Internal compiler error.\n");
        tcc_delete(tcc);
        return 1;
    }
    if (tcc_compile_string(tcc, buf) < 0) {
        fprintf(stderr, "Failed compiling generated code.\n");
        tcc_delete(tcc);
        return 1;
    }
    if (tcc_add_library(tcc, "c") < 0) {
        fprintf(stderr, "Failed linking in C library.\n");
        tcc_delete(tcc);
        return 1;
    }
    if (tcc_output_file(tcc, out) < 0) {
        fprintf(stderr, "Failed writing program to file.\n");
        tcc_delete(tcc);
        return 1;
    }
    tcc_delete(tcc);
    return 0;
}

int minus(FILE* f){
    int c;
    int amount = 0;
    while ((c = getc(f)) == '-')
        amount++;
    ungetc(c, f);
    return amount;
}

int plus(FILE* f){
    int c;
    int amount = 0;
    while ((c = getc(f)) == '+')
        amount++;
    ungetc(c, f);
    return amount;
}

int main(int argc, char** argv){
    static int const buflen = 1024*1024;
    int pos = 0;
    int brackets = 0;
    fprintf(stderr, "Brainfuck Compiler by Joel. All rights reserved.\n");
    if(argc!=3){
        fprintf(stderr, "Usage: %s <input> <output>", argv[0]);
        return 1;
    }
    int amount = 0;
    int ret;
    FILE* f = fopen(argv[1], "r");
    if(f!=NULL){
        char* outbuffer = (char*)malloc(buflen);
        if (outbuffer == NULL) {
            fprintf(stderr, "Internal compiler error.\n");
            fclose(f);
            return 1;
        }
        ret = snprintf(outbuffer, buflen, "int getchar(void);\nint putchar(int);\nint mem[65536] = {0};\nint main(){\n");
        if (ret < 0 || ret >= buflen) {
            fprintf(stderr, "Internal compiler error.\n");
            free(outbuffer);
            fclose(f);
            return 1;
        }
        while(!feof(f)){
            switch (fgetc(f)) {
            case '<':
                pos = (pos - 1) & 0xFFFF;
                break;
            case '>':
                pos = (pos + 1) & 0xFFFF;
                break;
            case '[':
                ++brackets;
                ret = snprintf(outbuffer, buflen, "%swhile(mem[%d]){", outbuffer, pos);
                if (ret < 0 || ret >= buflen) {
                    fprintf(stderr, "Internal compiler error.\n");
                    free(outbuffer);
                    fclose(f);
                    return 1;
                }
                break;
            case ']':
                --brackets;
                ret = snprintf(outbuffer, buflen, "%s}", outbuffer);
                if (ret < 0 || ret >= buflen) {
                    fprintf(stderr, "Internal compiler error.\n");
                    free(outbuffer);
                    fclose(f);
                    return 1;
                }
                break;
            case '+':
                amount = plus(f)+1;
                ret = snprintf(outbuffer, buflen, "%smem[%d]+=%d;", outbuffer, pos, amount);
                if (ret < 0 || ret >= buflen) {
                    fprintf(stderr, "Internal compiler error.\n");
                    free(outbuffer);
                    fclose(f);
                    return 1;
                }
                break;
            case '-':
                amount = minus(f)+1;
                ret = snprintf(outbuffer, buflen, "%smem[%d]-=%d;", outbuffer, pos, amount);
                if (ret < 0 || ret >= buflen) {
                    fprintf(stderr, "Internal compiler error.\n");
                    free(outbuffer);
                    fclose(f);
                    return 1;
                }
                break;
            case '.':
                ret = snprintf(outbuffer, buflen, "%sputchar(mem[%d]);", outbuffer, pos);
                if (ret < 0 || ret >= buflen) {
                    fprintf(stderr, "Internal compiler error.\n");
                    free(outbuffer);
                    fclose(f);
                    return 1;
                }
                break;
            case ',':
                ret = snprintf(outbuffer, buflen, "%smem[%d]=getchar();", outbuffer, pos);
                if (ret < 0 || ret >= buflen) {
                    fprintf(stderr, "Internal compiler error.\n");
                    free(outbuffer);
                    fclose(f);
                    return 1;
                }
                break;
            default:
                break;
            }
        }
        fclose(f);
        if(brackets == 0){
            ret = snprintf(outbuffer, buflen, "%sreturn 0;\n}\n",outbuffer);
            if (ret < 0 || ret >= buflen) {
                fprintf(stderr, "Internal compiler error.\n");
                free(outbuffer);
                fclose(f);
                return 1;
            }
            if (compile(argv[2], outbuffer)) {
                free(outbuffer);
                return 1;
            }
            free(outbuffer);
        }
        else{
            fprintf(stderr, "Compilation fault. Unbalanced brackets.\n");
            free(outbuffer);
            return 1;
        }
    }
    else{
        fprintf(stderr, "Cannot open one of specified files.\n");
        return 1;
    }
    return 0;
}

(*) This is only true for systems representing signed integers using two's complement, where (using signed 16 bit integers) -1 equals 0xFFFF. When using one's complement representation, -1 equals 0xFFFE (with 0xFFFF being -0), but practically every machine commonly available today uses two's complement for representing signed integers.


Getting value from session if available, if not, take from the database

Some recommendations:

1) Give your method a better name. ResponseAsJson is not what it does. Proposal: AppendAllowOriginHeader

2) Your method relies on the affiliateId inputparameter. I would change the parameter to int? affiliateId and then add a short guard:

if(!affiliateId.HasValue) {
   throw new ArgumentNullException(nameof(affiliateId));
}

Also keep in mind, that the id may be invalid in which I would prefere to throw an InvalidArgumentException

3) Let's clean up: Extract the method in two subfunctions:TryAddFromCache(string key) and TryAddFromAllowedOrigins

TryAddFromCache could look like:

if(String.IsNullOrWhiteSpace(key)) {
   return false;
}

...
return true;

And in AppendAllowOriginHeader:

if (TryAddFromCache()) {
    return;
}

4) As a rule: Use const or var wherever possible.

5) Extract a second method:

bool TryAddFromAllowedOrigins(IEnumerable<string> allowedOrigins) { ... }

6) Performance: In this case we have the database access as bottleneck.
The party starts at:

RM.BL.Affiliate.Instance(affiliateId).LUAffiliate.AccessControlAllowOriginJsonResult.Split(';');

.. which has the most impact.

Your array strFromDB will probably not hold references to several thousand strings. So filtering or sorting (which should be the work of the db anyway) has no impact.

 string strLocalhost = strFromDB.Where(x => x.ToLower().StartsWith("http://localhost")).FirstOrDefault();

can be changed to:

strFromDB.FirstOrDefault(x => x.ToLower().StartsWith("..."));

7) Consider using better names: for example strFromDB could be changed to allowedOrigins


Traversing and printing complex Dictionary types (Scripting.Dictionary) - Dictionary inside of a Dictionary

A couple of things, which you've really more or less pointed out already.

You've shown us two different implementations of the same routine that outputs two two different places. I think what you really need is a class that gets initialized with an IOuput member. Then you can have different implementations of the IOuput interface, but TraverseDictionary only has to deal with IOutput and one routine can print out to anywhere.
You're correct that VarType = 9 is unsafe and TypeName = "Dictionary" is safer, but I'm not sure it's entirely safe. What if there's a namespace conflict because I implemented a VBAProject.Dictionary? TypeName of my custom dict would also be "Dictionary" and who knows what would happen then. TypeOf is another option though. I've not tested it, but I believe you can do this.

If TypeOf d(Key) Is Scripting.Dictionary Then

But that means you'll also have to check IsObject(d(key)) prior to checking its actual type as well.

Update:

I finally had time to test this. I created an empty Dictionary class and ran the code below. It works.

Sub test()
    Dim dict As New Scripting.Dictionary
    Dim myDict As New VBAProject.Dictionary

    Debug.Print TypeOf dict Is Scripting.Dictionary
    'true
    Debug.Print TypeOf myDict Is Scripting.Dictionary
    'false
    Debug.Print TypeOf dict Is VBAProject.Dictionary
    'false
    Debug.Print TypeOf myDict Is VBAProject.Dictionary
    'true
End Sub


Steam Community Market Strange Part Scraper

Not exactly a PHP expert but your $weapons array:

$weapons = array(
  0 => "Scattergun",
  1 => "Pistol",
  2 => "Rocket%20Launcher",
  3 => "Direct%20Hit",
  .
  .
  .
  29 => "Knife",
);

You do not need an associative array for this. In fact, I would discourage this. Although there may be no good reason to do this, imagine you want to add a weapon in the middle, then you have to change a lot of numbers.

Similarly, I do not know how PHP internally represents associative arrays, but they may be slower to access than a standard array. C++ implementations often use Red-Black Trees to implement something similar to associative arrays and other languages may use other data structures.

Just use the standard array:

$weapons = array(
  "Scattergun",
  "Pistol",
  "Rocket%20Launcher",
  "Direct%20Hit",
   .
   .
   .
  "Knife",
);

Use a foreach loop:

for($wep_counter = 0; $wep_counter < count($weapons); $wep_counter++) {

  $url = "http://steamcommunity.com/market/listings/440/Strange%20". $weapons[$wep_counter];       # get listing for that weapon type

becomes:

foreach ($weapons as $weapon) { # I don't believe you are mutating a value so I don't believe the "&" prefix is necessary.

  $url = "http://steamcommunity.com/market/listings/440/Strange%20". $weapon;

There could be other issues but I'm not too much of a PHP expert, but these issues pertain to a lot of languages. I would definitely be sure to keep these in mind when using other languages as well.


I understand it is best not to use functions such as SHA1 or MD5.

That is true. But sha256 is not that much better.

Problem: simple sha256

There are basically two problems with your approach:

you don't use a user-based salt, only a site-based salt (also called a pepper).
you only use simple sha256, which is way too fast.

These are serious issues.

The main problem with missing user-based salts is that an attacker only needs to hash each password once and can then compare it to the hashes of all users, instead of needing to hash the password with each salt. This speeds up cracking considerably.

The problem with the second point should be obvious. Hardware has become quite powerful over the years, and simple hashing just doesn't hold up anymore (and hasn't for quite a while). Here for example is a benchmark of 3090.3 Million guesses per second on a pretty standard PC.

If your database is ever leaked - for example because of a Code Execution or SQL Injection vulnerability - it will be quite easy for an attacker to crack a good percentage of your users passwords.

Solution: Bcrypt

What you want to use is bcrpyt. With PHP, this can be done via password_hash (which is also the first result when googling "php hash password").

Example:

// hash
$hash = password_hash("password", PASSWORD_DEFAULT);

echo $hash;

// check
echo "<br>" . password_verify("password", $hash);

User-based salts are managed automatically for you, and it uses multiple rounds of hashing, slowing the process down, and thus increasing the resources an attacker needs to crack your hashes.

You can still use a pepper with bcrypt if you want to.

For more information about password hashing in general see here.

Misc

makeSafe is not a good function name. Make safe how? hash would be more accurate.


You only ask about performance, but I want to point out anyway that there is a small error in the definition of file2RC: you used column instead of row.

Now, let me get to the performance part. The thing making your code slow is that accesses to worksheets are expensive. Accordingly, they should be reduced to a minimum.

Currently, you access each cell individually. A better approach is to load all on the same sheet in one go. You can do this by assigning the Value property, or better the Value2 property (Value causes problems with fields formatted as dates.), of the used range to a Variant variable. After that, the variable contains a two-dimensional array consisting of the values in the range.

By comparing the values in corresponding arrays, you only need to access each sheet once to load the data and then for each time you find an error, in order to change the color.


Determining if three numbers are consecutive

The problem that I have with writing something like the original code is that it is complicated to be sure that it does the right thing in every situation.  You've taken three values and perform whopping fifteen comparisons on them.  What if you'd missed one?  The code would almost work, except it would occasionally (in that one situation) return the wrong result.

A conceptually simple way to handle this is

public static boolean consecutive(int... numbers) {
    Arrays.sort(numbers);

    for (int i = 1; i < numbers.length; i++) {
        if (numbers[i] != numbers[i-1] + 1) {
            return false;
        }
    }

    return true;
}

Sorting saves a lot of logic here.  Since we know the order, we can just check the differences directly.  If any adjacent numbers are not consecutive, we can return false.  If it makes it all the way through, they all must be consecutive.

Note that this also handles other than three numbers.  For example, it always returns true if there's zero or one number passed.  This may or may not be what you want.

Now we do five manual comparisons (including the comparison of i to numbers.length) to determine that three numbers are consecutive.  The sort does more comparisons, but we don't have to worry if we got those correctly.  The chances of there being an error in sort that made it through the Java compiler's testing is extremely low.

I find this version much easier to read and verify correctness than the original code.  For most cases, the difference in runtime is going to be minimal and unimportant.  My ability to write code that looks like this quickly and be sure it works is usually going to be more important.  And if you really need blazing speed, there are always options like @200_success offers.


Computing a Discrete Cosine Transform matrix

It is probably more in the spirit of functional programming to use pattern matches instead of long guard lists where possible. Your first function also has a few overlapping cases that could be eliminated in the interest of brevity:

showFraction _ 0 = error "Division by zero."
showFraction 0 _ = "0"
showFraction n 1 = show n
showFraction n d = show n ++ "/" ++ show d

Another simple change would be to exploit that foldr1 (\acc x -> acc ++ "," ++ x) is simply intercalate ',', which you get from Data.List. In a somewhat similar fashion, you could also replace foldr1 (\acc x -> acc ++ ",\n" ++ x) by concat . intersperse ",\n".

The result would look like follows:

dctRow j n = "{" ++ intercalate ',' [dctElement j x n | x <- [0..n - 1]] ++ "}"
dctMatrix n = "{" ++ concat (intersperse ",\n" [dctRow x n | x <- [0..n - 1]]) ++ "}"

Which in my opinion is more readable than the manual folds.

A more involved change would be to try to get rid of the \$O(n^2)\$ behaviour you will get from overusing (++). The background here is that (++) needs to make a full copy of the first operand in order to append the second one.

A fun functional way of improving this is to replace string concatenation by function composition:

showFraction :: Int -> Int -> String -> String
showFraction _ 0 = error "Division by zero."
showFraction 0 _ = ('0':)
showFraction n 1 = shows n
showFraction n d = shows n . ('/':) . shows d

So instead of a function that constructs a string, this is a function that prepends the string representation to a string passed as parameter. The nice thing about this is that you can simply compose these functions together in order to build bigger strings. As prepending doesn't require copying of the "tail" end in Haskell, this means that every part of the result string will be constructed exactly once!

Here is how to write the folds in this style:

applyInter f = flip (foldr ($)) . intersperse f
dctRow j n = ('{':) . applyInter (',':) [dctElement j x n | x <- [0..n - 1]] . ('}':)

(Realize that flip (foldr ($)) [f,g,h] is simply f . g . h)

Note however that while this indeed has \$O(n)\$ complexity, it is still not very efficient. This is due to GHC probably selecting a bad arity for some of the functions in question, as well as String not being very fast in the first place. For constructing strings fast, it's probably a better idea to use Data.Text and/or a special builder library like blaze-builder.


Create list of objects from an object where the key is properCase using Lodash

The code looks like you're passing the processed data to autocomplete.

Naming

formatToInput: This gives no idea of what the function is doing.
empty: Is it really empty at the end of formatToInput?
obj, list: Confusing.
test, results: Can be named better.

Lodash

Do you really need a library for this functionality? The Same functionality can be done without Lodash or any other library. If Lodash is only used for this functionality, it can be removed.

Missing Semi-colons

Although, a small thing Automatic Semicolon Insertion can lead to unexpected behavior. The usage of the semi-colon is not consistent. I'll recommend using JSLint/JSHint.

Alternative

I'll recommend the use of Array#map and String methods to make the first character uppercase.

const colorValueMap = {
  blue: 10,
  green: 5,
  yellow: 3,
  pink: 1
};
const colors = ['green', 'yellow'];

const result = colors.map(color => ({
  label: color[0].toUpperCase() + color.slice(1),
  value: colorValueMap[color]
}));
console.log(result);

Above solution assumes that the value from the filter array always exists in the object. If this is not the case, you can first filter the array and then use map on it.

colors.filter(color => colorValueMap.hasOwnProperty(color)).map(color => ({
    ...
});


Better way to validate user input in cakephp

I would split up the code into objects, with good object oriented patterns. This should result in objects that have very distinct responsibilities.

The pattern I think you should primarily look into is the "Proxy" pattern (See "Design Patterns" book by "Gang of four".) It can be used to extract the code that ensures security, for example. It makes the security code independent from the domain logic / data access / user interface.

It may mean refactoring a lot of code, but once done, you can then write thorough unit-tests for the security proxy in isolation, giving you a rock solid foundation.

Write tests, then write the testable code, (i.e. isolated) then refactor to the point where it's neat and tidy.


Uint8Array indexOf method that allows to search for byte sequences

First things first. This code is fairly difficult to read. indexOfMulti could mean

You're searching for any one of multiple values.
You're searching for all occurrences of a value (less likely -- might be indicesOf or findAll).
You're searching for the first occurrence of a sequence.

I'd name this something like find, findSequence, findSubstring. I'd also rename searchElements to something like needle, targetSequence.

You have two different efficiency issues here.

First, if this code is running in an implementation without tail-call optimization (I can't tell if any do, much less whether it's common), your memory usage may blow up whenever the first part of needle is common in your haystack but the full needle isn't found, because you'll blow up the stack. Better to implement this non-recursively.

Second, you've chosen the naive string search algorithm (see http://en.wikipedia.org/wiki/String_searching_algorithm). It will work fine when needle and haystack are small, or when prefixes of needle are rare in haystack, but it will be quite slow on the following example:

haystack = "aaaaaaaaaaaaaaaaaaaaab";
needle = "aaaab";
haystack.findSequence(needle);

You'd be better off selecting one of the other algorithms in that wikipedia article; a good choice is Boyer-Moore.


That's a perfectly good and valid way of doing it. Personally, I'd write $counter++ rather than ++$counter, but that's just my personal preference.


Dynamic programming solution

This problem can be solved with a dynamic programming solution by starting at the end cell and working upwards and leftwards to the starting cell.  The basic premise is:

You need to construct a new matrix of values which holds the minimum health required to have before reaching a square.  For example, if m[5][3] is 10, it means that you need 10 health to reach the finish, if you were at (4,3) or (5,2) and were about to move to (5,3).
Start with the end cell, and set its value to max(1, 1 - dungeon[lastcell]).
Then working your way upwards and leftwards, you can set each cell like this:

downHealth  = max(1, m[downNeighbor ] - d[thiscell]);
rightHealth = max(1, m[rightNeighbor] - d[thiscell]);
m[thiscell] = min(downHealth, rightHealth);

Note that some cells do not have both neighbors, so you just set the value to the health computed for the neighbor that exists.


After some research, I've got these answers:

Testing constructor is totally unnecessary if you follow this: Constructor does Real Work. Unit test for units. The constructor only job is to build the object, nothing else, no new objects creation, no initializing, etc...

For constants: I see no reason why do not use constants (for example for a path) to help me to access my classes for tests.


Making a grid for collision detection in a game that wraps

Some style points first.

Always wrap statement and loop blocks in {} eg you wrote for (let j = 0; j < x2; j++) someFunction(j) to avoid maintenance headaches use the curlies for (let j = 0; j < x2; j++) { someFunction(j) }
Don't declare the same variable over and over. There is no advantage to locally scoping variables to code blocks unless you are writing very long functions, and you should avoid writing functions more than a page long.
In this case j is not the best choice of variable name for the loop counter. x would be far better.

Rewriting your function with the above points

var x;
if (x1 < 0) {
    for (x = x1 + gridX; x < gridX; x++) { someFunction(x) }
    for (x = 0; x < x2; x++) { someFunction(x) }
} else if (x2 >= gridX) {
    for (x = x1; x < gridX; x++) { someFunction(x) }
    for (x = 0; x < x2 - gridX; x++) { someFunction(x) }
} else {
    for (x = x1; x <= x2; x++) { someFunction(x) }
}

The remainder operator %

  "I feel like there must be a better way to write it."

You can simplify the solution by using the remainder operator %. First ensure that x1, and x2 are positive by adding the grid width (or height)
Then use remainder as you loop over the items to get the wrapped coordinate.

Example replaces your function

// Assumes x1 is never less than -gridX and that x2 is always > x1
const end = x2 + gridX;
var x = x1 + gridX;
while (x <= end) { someFunction((x++) % gridX) }

More detailed example of wrapped play-field

The example below demonstrates using remainder and has two functions that take a x,y gird coordinated and map it to an array. setGrid(x, y, val) as long as the grid coordinates are greater than gridSteps (same as your gridX) * -gridMin

const AABB = { x: 0, y: 0, w: 90, h: 90 } // values in pixels
const gridSteps = 10;  // same as your gridX
const gridMin = 100; // min number of grids below origin 0,0. Used to translate
                     // coordinates to positive values
const grid = new Uint8Array(gridSteps ** 2); // grid array

function setGrid(x, y, val) {
    x += gridSteps * gridMin; // translate to positive space
    y += gridSteps * gridMin; // translate to positive space
    const idx = (x % gridSteps) + (y % gridSteps) * gridSteps;
    grid[idx] = val;
}

// version 2
const gridMinC = gridSteps * gridMin;
function setGrid(x, y, val) {
    const idx = ((x + gridMinC) % gridSteps) + ((y + gridMinC) % gridSteps) * gridSteps;
    grid[idx] = val;
}

requestAnimationFrame(update);
const scaleMouse = 0.05; // scales mouse to add movement
const inset = 3, inset2 = inset * 2;
var w = 1, h = 1;
const gridImg = createImage(w, h);
const ctx = canvas.getContext("2d");
const mouse  = {x : 0, y : 0};
document.addEventListener("mousemove", mouseEvents);
function fillGrid(AABB, gridSteps, col = "#9998") { // Draw wrapped collision boxes
    var x, y, xs = w / gridSteps, ys = h / gridSteps;
    const yStart = AABB.y / ys | 0, yEnd = (AABB.y + AABB.h) / ys | 0;
    const xStart = AABB.x / xs | 0, xEnd = (AABB.x + AABB.w) / xs | 0;
    ctx.fillStyle = col;
    ctx.beginPath();
    for (y = yStart; y <= yEnd; y += 1) {
        const yy = y % gridSteps;
        for (x = xStart; x <= xEnd; x += 1) {
            const xx = x % gridSteps;
            ctx.rect(xx * xs + inset, yy * ys + inset, xs - inset2, ys - inset2);
        }
    }
    ctx.fill();
}
function drawBox(AABB, col = "#000") {  // draws AABB box wrapped
    ctx.strokeStyle = col;
    ctx.lineWidth = 2;
    const x = AABB.x % w;
    const y = AABB.y % h;
    ctx.strokeRect(x, y, AABB.w, AABB.h);
    var corner = 0;
    if (x + AABB.w > w) {
        ctx.strokeRect(x- w, y, AABB.w, AABB.h);
        corner ++;
    }
    if (y + AABB.h > h) {
        ctx.strokeRect(x, y - h, AABB.w, AABB.h);
        corner ++;
    }
    if (corner === 2) { ctx.strokeRect(x - w, y - h, AABB.w, AABB.h) }
}
function update() {
    if (w !== (innerWidth / 2 | 0) || h !== innerHeight) {
        w = gridImg.width = canvas.width = innerWidth / 2 | 0;
        h = gridImg.height = canvas.height = innerHeight;
        drawGridLines(gridImg.ctx, gridSteps);
    }
    ctx.globalCompositeOperation = "copy";  // copy transparent pixels to destination
    ctx.drawImage(gridImg, 0, 0);
    ctx.globalCompositeOperation = "source-over"; // default comp mode

    //Use mouse dist from center to scale speed of AABB
    AABB.x = (AABB.x + (mouse.x - w / 2) * scaleMouse + w) % w;
    AABB.y = (AABB.y + (mouse.y - h / 2) * scaleMouse + h) % h;
    fillGrid(AABB, gridSteps);
    drawBox(AABB);
    requestAnimationFrame(update);
}
function mouseEvents(e){
    const bounds = canvas.getBoundingClientRect();
    mouse.x = e.pageX - bounds.left - scrollX;
    mouse.y = e.pageY - bounds.top - scrollY;
}
function createImage(width, height) {
    const img = document.createElement("canvas");
    img.width = width, img.height = height;
    img.ctx = img.getContext("2d");
    return img;
}
function drawGridLines(ctx, gridSteps, col = "red") {
    var i, xs = w / gridSteps, ys = h / gridSteps;
    ctx.lineWidth = 2;
    ctx.strokeStyle = col;
    ctx.beginPath();
    for (i = 0; i <= gridSteps; i ++) {
        ctx.moveTo(0, i * ys);
        ctx.lineTo(w, i * ys);
        ctx.moveTo(i * xs, 0);
        ctx.lineTo(i * xs, h);
    }
    ctx.stroke();
}
canvas { position : absolute; top : 0px; left : 0px; cursor: crosshair;}
<canvas id="canvas"></canvas>

Last point

  "especially if I wanted to make my game 3 dimensional in future."

You would never use a 3D grid for collisions as their size can grow very quickly, a 1024 cube would require a minimum or 1Gig of RAM. What you want are Quad Trees or even Octrees and the many variations, as they provide fast data structures for all sorts of spacial related problems 2D, 3D, and more :D

Collision grids are great for lowres 2D and limited 3D uses but you will need to consider alternatives when resolutions grow.


Detecting if an element is found inside a container

Note that for functions the compiler will detect the template types based on the parameters.
So you can simply write:

bool test = is_contained(container.begin(), container.end(), anything);

I don't particularly like the use of decltype in your function. I would simply make it another template parameter.

template <typename Iterator, typename Value>
bool is_contained(Iterator begin, Iterator end, Value const& object);

Because of the compiler deducing the names you can use any type. Also this is more flexable as it allows you to use any type that is comparable to the type inside the container (rather than only allowing values that are the same type (or trivial convertible)).