Design review
Trying to roll your own shared_ptr is actually a really good practice project. This is not true for many other standard library components, but it is true for shared_ptr. You could try to duplicate the behaviour of std::shared_ptr exactly… but you don’t need to, because there are actually many, many different smart pointer designs. The ones in the standard library are just nice general-purpose smart pointers, but it’s very common to see custom smart pointers in libraries built for specific purposes.
Your shared_ptr actually has one important benefit over std::shared_ptr: it’s usually going to be half the size. The reason for that is std::shared_ptr uses a control block to keep track of how many shared pointers share the same pointer (among other things), so in a std::shared_ptr, there’s usually the actual pointer, and then the pointer to the control block… that’s two pointers, so double the size of a single pointer. You use a static map instead, so each of your shared pointers only holds the actual pointer. That could be an important benefit.
However, you also truck around an int as an ID. Is that necessary? Why not just use the pointer value itself as the key?
Something like so:
std::unordered_map<std::uintptr_t, std::size_t> count_map;

template <typename T>
class shared_ptr
{
public:
    constexpr shared_ptr() noexcept = default;

    explicit shared_ptr(T* p) : _ptr{p}
    {
        _increment_count();
    }

    shared_ptr(shared_ptr const& other) : _ptr{other._ptr}
    {
        _increment_count();
    }

    ~shared_ptr()
    {
        if (_ptr)
        {
            // find the iterator to the count
            //
            // this is better than `count_map[n]` because we might need to use
            // the iterator more than once: once to decrement and check the
            // count, and possibly once more to erase
            auto const n = static_cast<std::uintptr_t>(_ptr);
            if (auto const p = count_map.find(n); p != count_map.end())
            {
                // decrease the count, and see if it's zero
                if (--(p->second) == 0)
                {
                    delete _ptr;

                    // remove the map entry tracking the pointer
                    count_map.erase(p);
                }
            }
            else
            {
                // something went really wrong!
                //
                // you should never get here unless there's a bug somewhere
            }
        }
    }

    auto operator=(shared_ptr const& other) -> shared_ptr&
    {
        auto temp = other;

        std::ranges::swap(_ptr, temp->_ptr);

        return *this;
    }

    // other stuff...

private:
    auto _increment_count() -> void
    {
        if (_ptr)
        {
            // convert the pointer to a number
            auto const n = static_cast<std::uintptr_t>(_ptr);

            // add the number as a new key in the count map
            //
            // note that if the key already exists, this will just increment the
            // count, so your shared_ptr will safely work with duplicates...
            // something std::shared_ptr won't do!
            ++(count_map[n]);
        }
    }

    T* _ptr = nullptr;
};

By using the pointer value itself as the key, rather than an int ID, your shared_ptr can now be the size of a single raw pointer.
So your design—using an external map to keep track of the count—has some benefits: notably it is now possible to make your smart pointer the same size as a raw pointer. But, of course, it has some drawbacks:

If you have a lot of shared_ptrs, that map can get huge.
Copying and destroying your shared_ptrs will be slow. std::shared_ptr has the pointer to the control block right on hand, so it just needs to do a single pointer indirection. Especially for making copies (and increasing the count), that’s fast (relatively speaking). Your shared_ptr has to search through a map (which is probably not going to be hot in cache) for each operation. That means that while auto sp1 = sp2; is really fast for std::shared_ptr it will be slow for your shared_ptr (and will get slower the more pointers you have). But that’s a pretty standard engineering size-versus-speed trade-off; your shared_ptr takes up less space, at the cost of speed.

Testing
Rather than simply wondering whether your code works or not, you should test it.
Now, something like shared_ptr is not easy to test… but not impossible. As a start, you could run your shared_ptr through all of its operations, and use a tool like Valgrind to check for bad memory access or leaks. Actually properly unit-testing something like shared_ptr is complex, and way beyond the scope here.
But a really easy trick is to simply insert a bunch of std::cout statements in your class member functions to print all the data about what’s going on. Yes, this isn’t the “sexy” way to test your code, but you’re a beginner; focus more on your code actually being correct than on doing things the “sexy” way.
In your destructor, you should also print the contents of the count map. That will give you a way to spot leaks, or other problems with the counts.
As I said, this isn’t technically the “right” way to do testing, but screw it, it’s quick, it’s easy, and it works. Even I develop code this way sometimes, if I’m experimenting with something difficult or “clever”. It’s cheap and hacky, but in the early stages of figuring something out, it does the job.
Code review
For starters, you should really be putting your own classes and stuff into your own, personal namespace. For example, I always use indi:
namespace indi {

template <typename T>
class shared_ptr
{
    // ... [snip] ...
};

} // namespace indi

auto main() -> int
{
    indi::shared_ptr<int> sp1;
    // ...
}

Putting your stuff in your own namespace is a good habit to get into in any case.
template<typename dataType>

dataType is a bad name for a template parameter. By convention, template parameters are written in “UpperCamelCase”. Also by convention, T is most commonly used. And it’s a hell of a lot shorter than dataType.
    shared_ptr()
    {
        id++;
        internalId = id;
        countMap[id] = 1;
        ptr = new dataType();
    }

Your default constructor actually allocates a new object. That’s… not a great idea. Default construction should be simple, fast, and—ideally—no fail.
Not only that, this behaviour is pretty surprising for a pointer. Consider:
using pointer = int*;

auto p1 = pointer{};                // p1 == nullptr, no-fail and fast
auto p2 = std::unique_ptr<int>{};   // p2 == nullptr, no-fail and fast
auto p3 = std::shared_ptr<int>{};   // p3 == nullptr, no-fail and fast
auto p4 = shared_ptr<int>{};        // p4 != nullptr, very slow, and the allocation might throw

Default construction for every other smart pointer I’ve seen gives you a null pointer. That should be the case for your smart pointer, too.
If you want a constructor that actually allocates the object—which is a good idea—you can use a “tagged constructor”. A good tag is std::in_place:
    constexpr shared_ptr() noexcept = default;

    explicit shared_ptr(std::in_place_t)
    {
        id++;
        internalId = id;
        countMap[id] = 1;
        ptr = new dataType();
    }

And you’d use it like this:
auto sp1 = shared_ptr<int>{std::in_place};

You could get even more advanced with perfect forwarding:
    template <typename... Args>
    explicit shared_ptr(std::in_place_t, Args&&... args)
    {
        id++;
        internalId = id;
        countMap[id] = 1;
        ptr = new dataType{std::forward<Args>(args)...};
    }

So now you could do:
auto sp = shared_ptr<std::string>{std::in_place, '*', 8};
// sp points to a string containing 8 asterisks

But let’s dig into the meat of the constructor:
    shared_ptr()
    {
        id++;
        internalId = id;
        countMap[id] = 1;
        ptr = new dataType();
    }

The first line can’t fail. So no problems yet (or so it seems!).
The second line also can’t fail. This is the only safe line in this entire constructor. (And even then, it’s not perfectly safe; it would be dangerous in concurrent code. But concurrency is a whole other beast.)
This line can fail. When you do countMap[id], the map will try to find a key matching id, and will (presumably) fail. So it will need to allocate a new node. That allocation might fail. This won’t be too serious a problem… all it means is that you’ll skip an ID.
This line can also fail, either in the allocation phase, or the construction of the new object. Either way, this is bad, because now countMap holds a node with an ID and count of 1 that will never be freed. Since no other shared pointer will use the same ID, this is only a minor leak… but it’s still a leak.

If you don’t care about losing IDs, you could fix this constructor by doing something like so:
    shared_ptr()
    {
        id++;
        internalId = id;
        countMap[id] = 1;

        try
        {
            ptr = new dataType();
        }
        catch (...)
        {
            countMap.erase(id);
            throw;
        }
    }

But the moral here is to always consider which expressions can throw, and what that means for the function as a whole.
    shared_ptr(shared_ptr& a)
    {
        this->ptr = a.ptr;
        this->internalId = a.internalId;
        countMap[internalId]++;
    }

The correct form for a copy constructor is to take the argument by const reference.
Failure to do so means this code won’t work:
auto const sp1 = shared_ptr<int>{};
auto const sp2 = sp1; // won't compile

Other than that, this copy constructor is okay. Most C++ programmers would gripe about the this-> stuff, because it’s unnecessary and ugly, but it’s not actually wrong, or harmful. (You could also use a member initializer list, but meh. For these simple types it doesn’t really matter.)
    void operator=(shared_ptr& a)
    {
        this->ptr = a.ptr;
        this->internalId = a.internalId;
        countMap[internalId]++;
    }

@1201ProgramAlarm has already pointed out one of the bugs in this function, but the best way to fix it is to rethink the whole function entirely, and use the “copy-and-swap” technique.
You see, if you follow @1201ProgramAlarm’s advice directly… you’ll have another problem. Let me show you—suppose you did this:
auto operator=(shared_ptr const& a) -> shared_ptr&
{
    // first decrement the count of the current pointer, and delete if necessary
    --countMap[internalId];
    if (countMap[internalId] == 0)
        delete ptr;

    // now set the new data
    ptr = a.ptr;
    internalId = a.internalId;
    ++countMap[internalId];

    return *this;
}

This looks innocuous… but it’s a trap. It won’t explode easily, but it will explode if you do this:
auto sp = shared_ptr<int>{};
sp = sp; // self-assignment

Consider what happens during the self-assignment above. Before the self-assignment, the count for the pointer is 1 (because it’s the only smart pointer that owns it). So the first line of the assignment operator does the decrement… and now the count is zero. So, of course, the object gets freed.
Then the “new” data gets transferred over. But… the new data is the same as the old data. So ptr is set to… itself… the pointer which now points to the deleted object. internalId is also set to itself, but that’s harmless. Then the count gets re-incremented, so it goes from zero to one again.
The net result is that your shared pointer appears to still be working—still keeping the count to some pointer—but the pointer points to deleted memory. If you access it, boom. And of course, when the last shared pointer pointing to it is destroyed, it will try to free it again. Double delete. Boom.
So I recommend the “copy-and-swap” technique:
auto operator=(shared_ptr const& a) -> shared_ptr&
{
    // copy a into a temporary...
    auto temp = a;

    // ... then swap the contents of the temporary with this
    std::ranges::swap(ptr, temp->ptr);                  // cannot fail
    std::ranges::swap(internalId, temp->internalId);    // cannot fail

    return *this;

    // when temp goes out of scope, it will be destroyed
    //
    // since it now holds the *OLD* internalID that this had, it will
    // decrement *THAT* count, and if it's zero, free the *OLD* ptr this held
    //
    // in the case of self-assignment, all the copy will do is increase the
    // count (to 2), and then the destruction will decrease it (back to 1),
    // so no harm, no foul
}

“Copy-and-swap” is technically less efficient… but it avoids very subtle bugs, like the self-assignment bug I described. You should do “copy-and-swap” in copy assignment operators by default.
Also, your copy-assignment operator is malformed. It should take a const reference, and it should return a non-const reference to this… not void.
The destructor is fine, so I’ll skip it.
    static int id;
    int internalId = 0;
    static std::map<int,int> countMap;

Okay, there are a couple of issues here.
First, I don’t know if you realize it, but since shared_ptr is a template, that means that there will be multiple id and countMap objects… one for each template parameter set.
In other words:
auto sp1 = shared_ptr<int>{};
auto sp2 = shared_ptr<long>{};

You probably think that the internalId for sp1 will be 2, and for sp2 it will be 3. Nope. It will be 2 for both. Why? Because sp1 is using shared_ptr<int>::id, and sp2 is using shared_ptr<long>::id. Those are two different ints.
In fact:
auto sp01 = shared_ptr<char>{};
auto sp02 = shared_ptr<signed char>{};
auto sp03 = shared_ptr<unsigned char>{};
auto sp04 = shared_ptr<int>{};
auto sp05 = shared_ptr<unsigned int>{};
auto sp06 = shared_ptr<short>{};
auto sp07 = shared_ptr<unsigned short>{};
auto sp08 = shared_ptr<long>{};
auto sp09 = shared_ptr<unsigned long>{};
auto sp10 = shared_ptr<std::string>{};
auto sp11 = shared_ptr<std::u8string>{};
auto sp12 = shared_ptr<std::vector<int>>{};
auto sp13 = shared_ptr<std::vector<long>>{};

The above code will create thirteen different id ints, and thirteen different countMap std::map<int, int>s. Every unique type you instantiate a shared_ptr with will create a new id and countMap. If you make shared_ptrs using many different types, that will balloon your static memory usage. And the bad thing about static memory usage is that it exists for the whole program. It is created when the program starts even if you never actually use it, and it exists until the program ends, even if you’re long done with it. Indeed, if you only allocate a single shared_ptr<foo> one time in the middle of your program, you’re paying for it for the whole program. You’re even paying for it if you allocate zero shared_ptr<foo> objects… but only mention one as a conditional possibility!
So this is not good. You probably only want a single map and id counter for all types in your program. To do that, you need to pull those static objects out of the template. You have multiple options for how you can do that. You can simply use global objects (probably hidden in a detail namespace). Or you can use a non-template base class and put all the statics in there.
Another issue is the use of int for both the ID and the count. int is only guaranteed to hold 65,536 values, though in practice it will usually hold at least 4,294,967,296. Four billion sounds like a lot, and it probably is, but it is not inconceivable that if a program runs long enough, and does enough allocating and deallocating, it could run out. (Far more likely to have that happen if you only have 65,536 values, of course.)
Whenever you’re keeping a count of something, the standard type to use in C++ is std::size_t. On most 64-bit systems, this will give you at 18,446,744,073,709,551,616 different IDs. That should be enough. You should use this for both the ID and the count.
So, perhaps you might do this:
// these could be hidden in a detail namespace, or a base class
//
// watch out for the static initialization order fiasco!
static auto next_id = std::size_t{0}; // in C++23 "= 0uz;" would work
static auto count_map = std::map<std::size_t, std::size_t>{};

// since the static variables are not in the template, they won't be
// duplicated for every T
template <typename T>
class shared_ptr
{
    // ...
};

Finally, you should consider using std::unordered_map rather than std::map. You don’t need the ordering, and the unordered map may be faster.
All that’s left is main():
shared_ptr<int> sp1;

You should really avoid this kind of declaration. The gold standard in modern C++ is the “always auto” style:
auto sp1 = shared_ptr<int>{};

There are a number of reasons why this form is better, too many to get into here. But as a bonus, once you get in the habit of using auto, numerous other bugs and quirks go away, and many lines of code become simpler. For example, instead of:
shared_ptr<int> sp2(sp1);

You could just do:
auto sp2 = sp1;

Shorter, simpler, clearer, and it avoids all kinds of bugs.


Use std::random_device instead of time()
Stay within C++, and use a real random device to seed the generator, like so:
std::random_device rd;
std::mt19937 generator{rd()};

Consider turning Randomiser into an anonymous namespace
Does this namespace need a name? If only getRandomNumber() uses Randomiser::generator, and it's in the same source file, you can make it an anonynous namespace instead, just omit "Randomiser".
Be consistent with types
Avoid mixing types like int and size_t. It might seem to work fine, but it is easy for errors to happen this way. Before changing types, consider that sometimes you don't really need to specify a type explicitly, and can instead use template<> or auto. For example:
template<typename T>
auto getRandomNumber(T min, T max)
{
    std::uniform_int_distribution<T> rand{ min, max };
    return rand(Randomiser::generator);
}

However, you will now get some compiler errors, because you were actually calling getRandomNumber() with min and max having different types, like in:
int randomNumber{ getRandomNumber(0, m.size()) };

This is actually a good thing, the compiler is telling you something fishy is going on. In fact, m.size() returns a size_t, which can be bigger than what an int can hold on most 64-bit platforms, as well as being unsigned instead of signed. Considering that min is always 0 in your code, I would instead write:
template<typename T>
auto getRandomNumber(T max) {
    std::uniform_int_distribution<T> rand{ 0, max };
    return rand(Randomiser::generator);
}

...

auto randomNumber = getRandomNumber(m.size());

Note that you probably meant getRandomNumber(m.size() - 1) here. This brings me to:
Consider writing a getRandomElement() function
You actually use the random numbers to pick random elements out of containers. So write a function to do exactly that:
template<typename T>
static auto &getRandomElement(const T &container)
{
    std::uniform_int_distribution<size_t> rand{ 0, container.size() - 1 };
    return *std::next(std::begin(container), rand(Randomiser::generator));
}

Simplifying markovIt()
Now that we have the above, we can simplify markovIt() greatly. It can be rewritten as:
void markovIt(const std::map<std::string, std::vector<std::string>>& m)
{
    // Get the initial word
    auto word = getRandomElement(m).first;

    for (int i = 0; i < 255; ++i)
    {
        std::cout << word << " ";

        // Find the entry in m that matches word
        auto entry = m.find(word);
        if (entry == m.end())
            break;

        // Select a random word from the list of possibilities
        word = getRandomElement(entry->second);
    }
}

Move special cases out of loops if possible
While loading story.dat, you use the variable i do determine if you need to push back the first word. You can move that special case outside of the loop. The compiler will probably do this for you even if you don't, but it also cleans up the code if you do so in this case:
wordStream >> fword;
wordStream >> sWord;
gram[fWord].push_back[sWord];

while(wordStream)
{
    wordStream >> fWord;
    gram[sWord].push_back(fWord);
    wordStream >> sWord;
    gram[fWord].push_back(sWord);
}

However, why read two words in each loop iteration? You can rewrite this to:
wordStream >> fWord;

while(wordStream)
{
    wordStream >> sWord;
    gram[fWord].push_back(sWord);
    fWord = sWord;
}

Move more functionality into functions
You are doing too much inside main(). Move more functionality into functions, and keep main() as high-level as possible. For example:
static auto load_gram(const std::string &filename)
{
    std::map<std::string, std::vector<std::string>> gram{};
    std::ifstream wordStream{ filename };

    // load the data into gram here
    ...

    return gram;
}

int main(int argc, char *argv[])
{
    auto gram = load_gram("story.dat");
    markovIt(gram);
}


C++ EventHandler class, invoking & arguments

I don't like that you use operator += to set the function. += suggests that I can append a bunch of functions and they all get called when the event happens, which is not the case. myEvent.setFunction([](int){}); would be better.

It would make sense to take advantage of move semantics. The lambda that gets passed into myEvent is moved into func and then copied into _func, when 2 moves would have been enough:

void operator+=(Function func)
{
    _func = std::move(func);
}

Better yet: Make it a template and perfect forward the argument to have only 1 move:

template<class Fun>
void operator+=(Fun &&func)
{
    _func = std::forward<Fun>(func);
}

You get somewhat worse error messages but most likely better performance.

Same goes for CallFunc, it should take a variadic template argument that gets perfect forwarded into the call for efficiency.

Speaking of efficiency, the flexibility of std::function comes at a price. It is known at compile time what types func can be, so _func should be exactly the same type without type erasure and virtual function calls. You can make that work with a template <class Fun> Event<Fun> make_event(Fun &&fun) style function to get the type of the function and create an Event with the appropriate template parameters, but you lose the ability to specify the function later.

There are extra parenthesis in the call (_func)(ax...);. Maybe it is a style thing, but I would write _func(ax...); instead.

Oh, and printf is not very C++y, but it was just an example.


JavaScript - Does this bookmarklet need some optimization?

The loader could be simplified to the following:

javascript:(function () {document.getElementsByTagName('head')[0].appendChild(document.createElement('script')).src = 'http://bookmarklet.example.com/js/bookmarklet.js?v=1'}());

No more variables. By the way, you forgot to use var. It causes the variable to be declared as a global.
Browsers, by default, parse script tags as JavaScript, thus the type can be omitted.

And in your script body, as far as I can understand, it's a script that gets a selected text or, if none selected, lets the user manually input the text and sends it to a server. Thus we have:

//remember that you are loading this script into the global scope. Protect your
//variables by enclosing it in a closure
(function () {
      //a ternary if is a short 2-way evaluation (as far as reading is concerned)
  var F = (frames.length > 0) ? ' (Frames not supported)' : '',
      //the OR operator (`||`) could also be used to evaluate stuff
      //here, it returns either document.getSelection(),
      //or if non existent, a prompted value
      Q = document.getSelection() || prompt('Enter a text...' + F + '', '');

  //then we execute your command
  window.open('http://www.example.com/add?url=' + encodeURIComponent(window.location) + '&text=' + escape(Q) + '&title=' + encodeURIComponent(document.title))

}());

As an additional tip, I suggest you load the url to a hidden iframe for a cleaner interface. You could add listeners (there are hacks for cross domain iframe messaging), to detect a success and show a confirmation UI afterwards.


Using an IEnumerator without a foreach loop in order to simulate a state machine

You could make life slightly easier for yourself by using the iterator slightly more properly:

public override IEnumerator<bool> ExecuteEffect()
{
    if(delay < 0 || GetRealTime() > executionStart + delay)
    {
        DealDamage();
        yield break;
    }
    if(executionStart == -1m)
    {
        executionStart = GetRealTime();
    }
    yield return false;
}

Then you could actually use MoveNext 'correctly' as it will return false when you get to the end.

To be completely and brutally honest, I'd still rage erase all of this code if I found it in a project I worked on. Why is it an enumerator of booleans? None of it's particularly obvious.

As an aside:

if(temp.Current)
{
    return true;
}
else
{
    return false;
}

is 100% the same as

return temp.Current;


Use functional-programming to convert a tree of parent:children objects to array

getValidParentAndChild can be rewritten as follows:

function getValidParentAndChild(list){
    return list.filter((obj) => obj.isValid)
               .map((obj) => obj.children.filter((kid) => kid.isValid)
                                         .map((kid) => toParentChildModel(obj, kid))
               .reduce((arr1, arr2) => arr1.concat(arr2));
}

The filter takes the element of the list and keeps it if the condition passed in is met. (In this case, both uses keep all the valid elements.)

map applies a function over each element of the list and returns the list of what the function returned for each element. Here it converts the list to a list of the parent-child pairs.

reduce is also called fold. These apply a two-argument over a list such that if your list was [a, b, c, d], with the function f, the reduce would return f( f( f(a, b), c), d). Here it is used to make a 2D list a 1D array.

This problem becomes more interesting if children could have children. In that case I would do the following:

function getPairsForNode(node){
    if(node.children)
       return node.children.map((child) => getPairsForNode(child))
                           .concat(node.children.map((child) => toParentChildModel(node, child))
                           .reduce((arr1, arr2) => arr1.concat(arr2));
    else return [];
}

function getValidParentAndChild(list){
    return list.filter((node) => node.isValid)
               .map(getPairsForNode)
               .reduce((arr1, arr2) => arr1.concat(arr2));
}


"The Story of a Tree" solved using depth-first search

gcd is missing a docstring.
gcd is tail-recursive, but Python doesn't have tail-recursion elimination, and so:

>>> gcd(3**7000, 2**10000)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
[...]
RecursionError: maximum recursion depth exceeded

It is more robust to turn the tail-recursion into a loop:

def gcd(a, b):
    """Return the greatest common divisor of a and b."""
    while b:
        a, b = b, a % b
    return a

and then:

>>> gcd(3**7000, 2**10000)
1

Python has a built-in greater common divisor function, fractions.gcd, so you could use that and avoid writing your own.
The only use for gcd is to print a fraction in lowest terms. The built-in fractions.Fraction class can do that, so you could write:

from fractions import Fraction
print("{0.numerator}/{0.denominator}".format(Fraction(win, n)))

The names dfs1 and dfs2 are not very informative. Sure, they do some kind of depth-first search, but which one is which?
The docstrings for dfs1 and dfs2 don't explain the arguments m, guess, seen, cost, and k. What am I supposed to pass for these arguments?
The seen argument to dfs1 and dfs2 always gets an empty set which is not used again after the function returns. So it would better for these functions to use a local variable and initialize it with an empty set. Then there would be no risk of passing the wrong value for this argument.
Instead of creating an empty list and appending an item to it:

stack = []
stack.append(root)

it's simpler to create a list with one item:

stack = [root]

Instead of testing the length of a list:

while len(stack):

it's simpler to test the list itself:

while stack:

Instead of computing the index of the last element of a list:

root = stack.pop(len(stack)-1)

you can use a negative index:

root = stack.pop(-1)

but by default the pop method pops the last element, so you can write:

root = stack.pop()

Instead of writing this complex condition:

count += (1 if root in guess and i in guess[root] else 0)

you can take advantage of the fact that True equals 1 and False equals 0, and write:

count += root in guess and i in guess[root]

The only use you make of guess is to test if it contains a directed edge. But this is slightly awkward because the test takes two steps. It would be better if you built a data structure that was better adapted to the use you intend to make of it. In this case, you could build a set of directed edges. So instead of:

guess = {}
for a1 in xrange(g):
    u,v = raw_input().strip().split(' ')
    u,v = [int(u),int(v)]
    if u not in guess:
        guess[u] = []
    guess[u].append(v)

write:

guess = set()
for _ in range(g):
    u, v = map(int, raw_input().split())
    guess.add((u, v))

and then in dfs1 you can write:

count += (root, i) in guess

(The construction of guess can be turned into a set comprehension, like this:

guess = {tuple(map(int, raw_input().split())) for _ in range(g)}

but I think the explicit loop is a bit clearer.)
Similarly, in dfs2 you have the complicated expression:

stack.append((i, cost - (1 if root in guess and i in guess[root] else 0) + (1 if i in guess and root in guess[i] else 0)))

Given the set of directed edges, this simplifies to:

stack.append((i, cost - ((root, i) in guess) + ((i, root) in guess)))

The top-level code is hard to test, because you can't call it from a Python program or the interactive interpreter. Better to put it in its own function, conventionally called main.
The top-level code is full of one-letter variables (m, q, g, k, u, v). It is hard to guess what these mean. Although it makes sense to stick with the names from the HackerRank problem description, a comment or two would help remind the reader of what they mean.
When you don't use a loop variable like a1, it's conventional to use the name _.
Some of the repetition in the input code can be avoided by using collections.defaultdict:

# Map from node to list of neighbours.
tree = defaultdict(list)
for _ in range(n - 1):
    u, v = map(int, raw_input().split())
    tree[u].append(v)
    tree[v].append(u)


Extreme use of pointers in adjacency list graph construction?

Am I going too far/extreme trying to place data onto the heap?

Yes. Containers like std::unordered_map and std::forward_list already store contents on the heap. If you declare a std::unordered_map on the stack, only a little bit of administrative data goes on the stack. But the same happens with std::unique_ptr. So in your code, the use of std::unique_ptr is superfluous and only increases indirection, which might be bad for performance. So just write:
template <typename TKey, typename TWeight>
class Graph {
    ...
    struct Vertex {
        ...
        std::forward_list<Adjacent> adjVertexList;
        ...
    };
    ...
    std::unordered_map<TKey, Vertex> vertices;
    ...
};


Code organization

Defining the add() and collect() functions is a good start, but it could be better, as there is still a lot of free-floating code outside those functions.  Part of the problem is that prompting for the inputs to add() requires intimate knowledge of what add() does, so you might as well make add() responsible for reading its own input.

Prompting for the Student ID is common to options 1 and 2, but is not appropriate for any other invalid option.  Therefore, the Student ID prompting code needs to be moved.

parcels.json is hard-coded four times.  The loading code is at the top, far from the saving code at the bottom.  I also find it odd that you feel compelled to write an empty dictionary to parcels.json if the file does not exist.

I'd use the following outline:

import json
import re

DATABASE_FILENAME = 'parcels.json'

def load():
    try:
        with open(DATABASE_FILENAME) as f:
            return json.loads(f.read())
    except IOError as e:
        return {}

def save(data):
    …

def input_student_id(prompt='Student ID: '):
    while True:
        student_id = input(prompt)
        if re.match(r'^\d[7]$', student_id):
            return student_id
        print('Invalid input! Student ID must be 7 digits')

def input_nonnegative_int(prompt):
    …

def add(data):
    student_id = input_student_id()
    new_letters = input_nonnegative_int('Letters: ')
    new_parcels = input_nonnegative_int('Parcels: ')
    record = data.get(student_id, [0, 0])
    data[student_id] = [record[0] + new_letters, record[1] + new_parcels]

def collect(data):
    student_id = input_student_id()
    record = data.get(student_id, [0, 0])
    print('Letter: {0} Parcel: {1}'.format(*record))
    del data[student_id]

def main():
    data = load()
    while True:
        option = input('1. Add\n2.Collect\nOption: ')
        if option == '1':
            add(data)
            break
        elif option == '2':
            collect(data)
            break
        else:
            print('Invalid option!')
    save(data)

if __name__ == '__main__':
    main()

Besides reorganizing all of the code into functions, I've also changed the input validation.  It's more forgiving — retrying instead of aborting.  Also, using a regular expression to validate the student ID simplifies the code while forbidding "000.000" as input (which your program would have accepted).

Data format

Using a two-element list to store the letter and parcel count is hard to read and a headache for future expansion.  A dictionary with two keys would be a bit better.

I'm concerned about using a JSON file as a database.  It's not a storage mechanism that is designed for concurrent access, so you might end up with dropped add/collect transactions or even a corrupted file.  If you don't want to install a full SQL database server, then consider using SQLite as a storage mechanism — it takes care of the concurrency concerns for you.


Creating a join table entry by looking up name

I'm not a postgres expert by any means, so take this as just an opinion:

DECLARE
  lk_act_id INTEGER := (SELECT act_id
                        FROM actors
                        WHERE LOWER(act_name) = LOWER(p_act_name));

Several issues with this.

I don't think the DECLARE section should be used for querying a table. I think it should only perform literal assignments. (I don't know if there's any accepted guidance around this, but it seems wrong to me.)

LOWER(act_name) will ensure any index on that column isn't used. Granted it's not an issue in your code because you don't have an index, but in the real world you probably would (or you'd suffer the performance impact of a sequential scan on that table every time the function is called, which would become an issue with a large table).

act_name has no guarantee of uniqueness - and it shouldn't, as there can certainly be more than one actor with the same name. So the above would throw an exception if it found more than one result. What then?

The query runs before the validation. If validation subsequently fails, you've done a sequential scan for nothing.

lk_chr_id INTEGER := NULL;
lk_med_id INTEGER := NULL;
md_unv_id INTEGER := NULL;
cr_unv_id INTEGER := NULL;

None of these variables need to be explicitly set to NULL, as all variables not explicitly initialised are NULL by default. (I'm not sure if this holds for all types e.g. enums, but certainly for all "native" and custom types I've used, it holds.)

  IF p_med_title IS NULL OR LENGTH(p_med_title) = 0
  THEN
    RAISE EXCEPTION 'A media title must be given';
  END IF;
  IF p_chr_name IS NULL OR LENGTH(p_chr_name) = 0
  THEN
    RAISE EXCEPTION 'A character name must be given';
  END IF;

What if it's whitespace? I'd do something like this instead:

IF NULLIF(TRIM(p_med_title), '') IS NULL THEN...

Although, I might cache the trimmed inputs so I don't have to trim them again when using them in the subsequent queries.

Also you could use ELSIF rather than having two separate IF statements.

You should probably also validate p_act_name here before looking it up in the table, or if it's valid for this parameter to be null or empty, then check it's not null/empty before querying the table for the id.

As to the rest, I can't quite understand what exactly it's trying to do and what all the conditions are. I would prefer seeing the desired outcome and constraints written in plain English rather than working it out from the code.


For SIMD optimization, I tried doing it with SSE2, as the compilation flags imply SSSE3 is disabled, and SSE3 is not useful here.

It's mostly a transliteration of the scalar code, but there are a few points of interest:

Except the squaring of gx and gy which is done in 32bit, and taking the square root which is done in floating point, most arithmetic is done in 16bit. That shouldn't change the results as everything fits well within the margins.
16bit is more than 8bit, so basically there is a choice between doing some half-wide loads and stores, or "doubling" the code. Often "doubling" the code is a little faster because it gets more arithmetic done with the same number of loads and stores, but that didn't pan out this time. So I used the less-common _mm_loadl_epi64 and the corresponding store. Note that these notionally take a pointer to __m128i, but they actually just load and store a qword (with no alignment restriction).
_mm_madd_epi16 is used for the gx*gx + gy*gy expression, which requires interleaving gx and gy, but is still more convenient than the alternatives.
There is no good way to conditionally not write a byte somewhere in the middle of a qword store, so for gradients less than 20 I write a zero, which is definitely different than the scalar code (but maybe safer anyway)
SSE2 has no single instruction to take an absolute value, but SSSE3 does. I didn't use it, but I factored it out so it can easily be updated if SSSE3 support can be assumed someday.
I paid no particular attention to alignment. The qword loads and stores don't care that much about alignment inherently, but on Core2 it is nevertheless Quite Bad to cross a cache line that way. If Core2 is a serious target, perhaps that aspect can be improved.
No testing was done other than for performance.

The results on quick-bench are OK but not amazing, about an 4x improvement (the final code there is labeled Gradient2). But maybe that's all we can hope for, given that there are square roots to be done. Of course you can still add threading on top of this which should (mostly) stack multiplicatively.

#include <x86intrin.h>

__m128i abs_epi16(__m128i x)
{
    __m128i m = _mm_srai_epi16(x, 15);
    return _mm_xor_si128(_mm_add_epi16(x, m), m);
}

void Gradient(unsigned char *smoothImg, short *gradImg, unsigned char* dirImg, size_t rows, size_t cols) {
    for (size_t i = 1; i + 1 < rows; i++) {
        size_t j = 1;
        // do blocks of 8 pixels at the time until near the edge
        for (; j + 8 < cols; j += 8) {
            __m128i zero = _mm_setzero_si128();
            // com1
            __m128i img1 = _mm_loadl_epi64((__m128i*)&smoothImg[(i + 1)*cols + j + 1]);
            __m128i img2 = _mm_loadl_epi64((__m128i*)&smoothImg[(i - 1)*cols + j - 1]);
            __m128i img1A = _mm_unpacklo_epi8(img1, zero);
            __m128i img2A = _mm_unpacklo_epi8(img2, zero);
            __m128i com1 = _mm_sub_epi16(img1A, img2A);
            // com2
            __m128i img3 = _mm_loadl_epi64((__m128i*)&smoothImg[(i - 1)*cols + j + 1]);
            __m128i img4 = _mm_loadl_epi64((__m128i*)&smoothImg[(i + 1)*cols + j - 1]);
            __m128i img3A = _mm_unpacklo_epi8(img3, zero);
            __m128i img4A = _mm_unpacklo_epi8(img4, zero);
            __m128i com2 = _mm_sub_epi16(img3A, img4A);
            // gx
            __m128i img5 = _mm_loadl_epi64((__m128i*)&smoothImg[i*cols + j + 1]);
            __m128i img6 = _mm_loadl_epi64((__m128i*)&smoothImg[i*cols + j - 1]);
            __m128i img5A = _mm_unpacklo_epi8(img5, zero);
            __m128i img6A = _mm_unpacklo_epi8(img6, zero);
            __m128i gx = _mm_add_epi16(_mm_add_epi16(com1, com2), _mm_sub_epi16(img5A, img6A));
            // gy
            __m128i img7 = _mm_loadl_epi64((__m128i*)&smoothImg[(i + 1)*cols + j]);
            __m128i img8 = _mm_loadl_epi64((__m128i*)&smoothImg[(i - 1)*cols + j]);
            __m128i img7A = _mm_unpacklo_epi8(img7, zero);
            __m128i img8A = _mm_unpacklo_epi8(img8, zero);
            __m128i gy = _mm_add_epi16(_mm_sub_epi16(com1, com2), _mm_sub_epi16(img7A, img8A));
            // sum
            // gx and gy are interleaved, multiplied by themselves and
            // horizontally added in pairs, creating gx*gx+gy*gy as a dword
            // 32bits is required here to avoid overflow, but also convenient for the next step
            __m128i gxgyL = _mm_unpacklo_epi16(gx, gy);
            __m128i gxgyH = _mm_unpackhi_epi16(gx, gy);
            __m128i lensqL = _mm_madd_epi16(gxgyL, gxgyL);
            __m128i lensqH = _mm_madd_epi16(gxgyH, gxgyH);
            __m128i lenL = _mm_cvttps_epi32(_mm_sqrt_ps(_mm_cvtepi32_ps(lensqL)));
            __m128i lenH = _mm_cvttps_epi32(_mm_sqrt_ps(_mm_cvtepi32_ps(lensqH)));
            __m128i sum = _mm_packs_epi32(lenL, lenH);

            // store gradient lengths
            size_t index = i*cols + j;
            _mm_storeu_si128((__m128i*)&gradImg[index], sum);

            // classify H/V/low
            __m128i thresholdLow = _mm_set1_epi16(19);
            __m128i markerV = _mm_set1_epi8(1);
            __m128i isSignificant = _mm_cmpgt_epi16(sum, thresholdLow);
            __m128i isHorizontal = _mm_cmplt_epi16(abs_epi16(gx), abs_epi16(gy));
            // if not horizontal, then 1 - 0 = 1
            // if horizontal,  then 1 - (-1) = 2
            // if not significant, then make it zero
            __m128i classifier = _mm_and_si128(_mm_sub_epi16(markerV, isHorizontal), isSignificant);
            _mm_storel_epi64((__m128i*)&dirImg[index], _mm_packs_epi16(classifier, classifier));
        }
        for (; j + 1 < cols; j++) {
            int com1 = smoothImg[(i + 1)*cols + j + 1] - smoothImg[(i - 1)*cols + j - 1];
            int com2 = smoothImg[(i - 1)*cols + j + 1] - smoothImg[(i + 1)*cols + j - 1];

            int gx=abs(com1+com2+(smoothImg[i*cols + j + 1] - smoothImg[i*cols + j - 1]));
            int gy=abs(com1-com2+(smoothImg[(i + 1)*cols + j] - smoothImg[(i - 1)*cols + j]));

            int sum = (int)sqrt((double)gx*gx + gy*gy);

            size_t index = i*cols + j;

            gradImg[index] = sum;
            if (sum >= 20) {
                if (gx >= gy) dirImg[index] = 1; //1 vertical
                else      dirImg[index] = 2; //2 Horizontal
            }
        }
    }
}


Is there a simpler way to make an English-readable list from strings in a tuple?

Looks pretty good. The only problem I can see is that you're not doing a check to make sure the list is not empty: if it is, then you'll try to access my_list[-1] in the final else clause, which will raise an IndexError.

Hence, I'd simply add a check up front for length == 0 and return '' in that case.


General concept

From your explanation it seems to me that, apart from dimensions and prices, different categories of products may have different additional features (like glasstype, hinges, and coating in your showerdoor example).

But since you showed only one product, I can't be certain. So What follows is based on the hypothesis that:

there is potentially a number of these features and each category of product uses only some of them, but each feature may be shared by several categories.
for a given feature, the way it is processed is the same for all involved categories of products.

That's said, I think you'd better to write all these methods in your abstract class, so they're always already available for each new derived class you create for a kind of product.

More, I think that even if certain features are specific to certain unique categories (what you called "exceptions"), they also should be written in the abstract class.

At the same time, in order to keep the whole process secure (i.e. be sure that a derived class can't accept features that don't regard their category), each derived class could have its own allowed-features list.

Applying the above strategy leads to something like this for the abstract class:

abstract class ConfigurableProduct {

  public $squareMeters;
  // Stores the prices
  protected $_price = array();

  // Initializes object
  public function __construct($data = [], $allowed_features = []) {
    // Set square meters
    $this->squareMeters = $data['square_meters'];

    // Set features when they are both allowed and present
    foreach ($allowed_features as $feature) {
      if (isset($data[$feature])) {
        $method = 'set' . $feature;
        $this->$method($data($feature));
      }
    }
  }

  // Adds price to _price array
  public function addPrice( $value ) {
    $this->_price[] = $value;
  }

  // Sums prices in _price array
  public function getPrice() {
    return array_sum( $this->_price );
  }

  // One example of feature method for "someFeature"
  public function setSomeFeature($id) {
    // Check for part id (so integer)
    if (isset($id) && is_int($id)) {
      // Calculate price
      $value = gtp_wizard_part_price($id) * $this->squareMeters;
      // Add price to price array
      $this->addPrice( $value );
    }
  }

  // Other feature methods here...
}

And something like this for a category of product:

class Showerdoor extends ConfigurableProduct {

  protected $allowed_features = [
    'glasstype',
    'coating',
    'hinges',
  ];

  // Initializes object
  public function __construct($data) {
    // Parent constructor
    parent::__construct($data, $this->allowed_features);
  }
}

At my eyes this way ensures both consistency and simplicity (hence readability): all existing feature methods are gathered at a unique place, once for all; granting a feature to a category is only matter of simple registration.

Some minor aspects

I'm a bit surprised you calculate square meters outside of the object: unless I'm missing something subtle, it could be done (again, once for all) in the abstract class, so the __construct() function becomes:

  public function __construct($data = [], $allowed_features = []) {
    // Set square meters
    $this->squareMeters = $data['width'] * $data['height'] / 1000000;
    // ...

And the object creation is only:

// Parts (ids from database)
$glasstype      = 282236;
$hinges         = 282242;
$coating        = 282296;

// Create object
$showerdoor = new Showerdoor(
   array(
    'width'     => 800,
    'height'    => 2000,
    'glasstype' => $glasstype,
    'hinges'    => $hinges,
    'coating'   => $coating,
  )
);

Also I'd suggest adding the availibility for the app to access data in the object, avoiding to keep global variables outside of it.
This way, the abstract class looks like this:

abstract class ConfigurableProduct {

  public $squareMeters;
  public $data;
  // Stores the prices
  protected $_price = array();

  // Initializes object
  public function __construct($data = [], $allowed_features = []) {
    // Set square meters
    $this->squareMeters = $data['width'] * $data['height'] / 1000000;
    // Keep a copy of data
    $this->data = $data;
    //...

And the object creation is even simpler:

// Create object
$showerdoor = new Showerdoor(
   array(
    'width'     => 800,
    'height'    => 2000,
    'glasstype' => 282236,
    'hinges'    => 282236,
    'coating'   => 282296,
  )
);

Regarding the feature methods you gave in example, note that setGlasstype() and setCoating() are perfectly identical and hence can be factorized.
Obviously it can be achieve by simply invoking a common (protected) method from each of them. But if this situation is frequent you might use another strategy, using aliases, like this:

  // Aliases for feature methods
  protected $feature_aliases = [
    'glasstype'   => 'GlassType_setCoating',
    'setcoating'  => 'GlassType_setCoating',
    'sethinges'   => 'SetHinges',
  ];

So the __construct() function must be adapted:

// Set features when they are both allowed and present
foreach ($allowed_features as $feature) {
  if (isset($data[$feature])) {
    $method = 'set' . $this->feature_aliases[$feature];
    $this->$method($data($feature));
  }
}

This way, again, we get more consistency and readability, since there is a clear and brief registry for all existing feature methods.
Note that this also simply solves an issue I didn't pay attention in the above: the difference between all-lower and camelcase feature names.

Hope this helps!


Interview questions are almost always meant to evaluate you by the clarifying questions you ask.

In this case, what data structures were you allowed to use beyond the arrays? Clearly something was allowed, since the requirement for queue and dequeue methods implicitly allow a class to be used. But was the Queue class allowed to contain auxiliary classes?

If not, the solution calls for the queue to be an Object[5] where the fifth element, when not null, is the next Object[5].

Requirement said arrays, not ArrayLists.
The requirement did not specify the type so a generic type should have been used instead of assuming integers are ok.
Use of primitive types and lack of exceptions means you're limited to positive numbers, as half of the valid value range has been used for errors.
You have copy-pasted the sub-array initialization code twice. That should have been a shared method.
When dequeueing, you leave the empty sub-arrays in the outer list, forcing you to perform an O(N) search to find the first element. Should have just removed the empty sub-arrays and gone for the O(1) operation of getting the first element from the first sub-array.
The check for array.isEmpty() in dequeue is redundant and adds a third exit point for that method.

Edit: I was thrown off by the for-loop in the dequeue method. Fixed my answer.


There are several ways you can go about doing this.

Use pandas.read_excel
Manually convert excel workbook to csv file then use pandas.read_csv
Use Python code to convert excel workbook to csv file then use pandas.read_csv

The third method is your best approach. It's the fastest.

Here is my excel workbook

1

df1 = pandas.read_excel('workbook.xlsx')
print(df1)

Out

  col1    col2     col3        col4
0   I   should       be  completing
1   my  linear  algebra    homework

2

I named the .csv file 'workbook.csv'

df2 = pandas.read_csv('workbook.csv')
print(df2)

Out

  col1    col2     col3        col4
0   I   should       be  completing
1   my  linear  algebra    homework

3

import csv
import xlrd
with xlrd.open_workbook('workbook.xlsx') as wb:
    sh = wb.sheet_by_index(0)
    with open('workbook.csv', 'w', newline="") as csv_file:
        col = csv.writer(csv_file)
        for row in range(sh.nrows):
            col.writerow(sh.row_values(row))
df3 = pandas.read_csv('workbook.csv')
print(df3)

Here is the .csv produced, calle

col1,col2,col3,col4
I,should,be,completing
my,linear,algebra,homework

And then the subsequent dataframe

  col1    col2     col3        col4
0   I   should       be  completing
1   my  linear  algebra    homework

VERDICT

All the outputs for each method is the same but method 3 is the fastest. This means you should import csv and xlrd to convert each of your xlsx files to csv files and then use read_csv. You can use os to get into your specific directories. Add for loops for each file for solution 3.

NOTE

Test method 1 versus 2 for yourself because I am getting somewhat inconsistent results using the timeit module and writing

start = timeit.timeit()
# code
end = timeit.timeit()
print(f"Time {end - start} {df}")

but I am not sure if I am using it correctly. So, at the very least, try the first and last methods for yourself and see which ones go faster.


Printing a string in NASM Win16 Assembly

You have all the elements. The only thing that can be eliminated is jmp .run, as follows:

org 0x100

        mov     si, Prompt
        call    puts
        ret

  puts: mov     ah, 0xe
        mov     bx, 7
 .read: lodsb
        or       al, al
        jnz     .post
        ret
 .post: int     0x10
        jmp     .read

 Prompt: db  'Hello World', 0

As INT 10H does not trash AH or BX, there is no need to reinitialize them each time through the loop.


A better way of always dumping Gedit out of Terminal?

If you just want to make gedit operate silently and in the background, I would create a function (save in ~/.bashrc)

gedit() { command gedit "$@" &>/dev/null & }

Also, Accessing bash command line args $@ vs $*


Well, unless you wanted to add instances to allow for folding and so, or conversions to Data.List I'd say that's perfect as it is.


I am also using MomentJS for formatting dates.

I have experienced performance issues when using MomentJS before. It's not because it's terrible but rather the opposite. It just does a lot of things to get dates right. But you'll have to look out for potential bottlenecks.

  it takes up to 1-2 sec to load a page

Also consider that you're using AJAX. Network latency can become an issue as well. But there's nothing you can do with that since you have no control of the network. Consider other strategies like loading pages, or caching, or data compression.

We can do nothing with a slow network, but we can do something about the slow code.

        data.forEach(function(item) {
            if (item['submission timestamp']) {
                var month = moment(item['submission timestamp'], 'M-D-YY h:m a').format('MMM-YY');
                if (datesarray.indexOf(month) < 0) {
                    datesarray.push(month);
                }
            }
        });

        datesarray.sort(function(a, b) {
            return moment(a, 'MMM-YY') - moment(b, 'MMM-YY');
        });

        datesarray.forEach(function(date) {
            var counter = 0;
            data.forEach(function(item) {
                var month = moment(item['submission timestamp'], 'M-D-YY h:m a').format('MMM-YY');
                if (month === date) {
                    counter += 1;
                }
            });
            returnarray.push({
                label: date,
                issues: counter
            });

        });

The lag you are experiencing is most likely the browser's garbage collector kicking in. Every moment call creates a new MomentJS object. It's terrible thing to do in loops. In your case, you call it on each of the loops you have. You have 1 loop that executes n times, 1 sort whose callback is called an arbitrary amount of times, and 2-level loop which is n^2.

The goal here is to reduce the usage of moment and avoiding the use of nested loops. The following code is my attempt at it. It uses moment only once to grab everything it needs into a regular object. Everything else is just linear object/array operations.

const issuesByDate = data.reduce((data, item) => {
      // Return early when there's no timestamp
      if(!item['submission timestamp']) return data;

      // Group the data by using an object
      // { 'MMM-YY': { label: ..., timestamp: ..., issues: ... }}

      // The only time we use moment
      const itemMoment = moment(item['submission timestamp'])
      const label      = itemMoment.format('MMM-YY');
      const timestamp  = itemMoment.valueOf();

      // Use the label as key to group similar items
      // Append timestamp, a number value. Well need it later for sorting
      data[label] = data[label] || { label, timestamp, issues: 0 };
      data[label].issues += 1;

      return data;
    }, {});

             // Convert object into an array
             // [{ label: ..., timestamp: ..., issues: ... }]
return Object.keys(issuesByDate)
             .map(key => issuesByDate[key])
             // Sort here since object keys don't guarantee order
             .sort((a, b) => a.timestamp - b.timestamp)
             // Strip off the timestamp property that we don't need
             // [{ label: ..., issues: ... }]
             .map(item => ({ label: item.label, issues: item.issues }))

The code above can be further tuned by using regular loops instead of array methods, grouping up loop operations, use pushing to existing arrays instead of returning new arrays after each oepration. In summary, avoid calling out moment too often and avoid nested loops.


You should be able to use a Simple Form Custom Input.

As I don't know Simple Form well enough, I don't know if you can access the routes from a custom input class.

If not, see the answers to these questions:

Accessing Rails RESTful routes in the model

and

Rails, get resource path in model


In my humble opinion, the version below is more elegant, easier to read and to maintain.

It uses a class to keep things more organized.

I would consider the code below as a starting point to start being improved, with things like error checking, etc.

I hope you like, and maybe learn something from it.

<?php

class MyQuery
{
    public $query = '';

    public $search_url = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?';
    public $fetch_url  = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?';

    public $search_parameters = array(
        'db'         => 'pubmed',
        'term'       => '',
        'retmode'    => 'xml',
        'retstart'   => '0',
        'retmax'     => '500',
        'usehistory' => 'y'
    );

    public $fetch_parameters = array(
        'db'        => 'pubmed',
        'retmax'    => '500',
        'query_key' => '',
        'WebEnv'    => ''
    );

    public $search_results;
    public $fetch_results;
    public $matches = array();

    public $match_regex = '/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}/';

    public __constructor( $query )
    {
        $this->query = $query;
    }

    public search()
    {
        $this->search_parameters['term'] = $this->query;
        $url = $this->search_url . http_build_query( $this->search_parameters );
        $this->search_results = simplexml_load_file( $url );
    }

    public fetch()
    {
        $this->fetch_parameters['query_key'] = (string) $this->search_results->QueryKey;
        $this->fetch_parameters['WebEnv']    = (string) $this->search_results->WebEnv
        $url = $this->fetch_url . http_build_query( $this->fetch_parameters );
        $this->fetch_results = file_get_contents( $url );
    }

    public match()
    {
        $matches = array();
        preg_match_all( $this->match_regex, $this->fetch_results, $matches );
        $this->matches = array_values( $matches[0] );
    }

    public get()
    {
        $this->search();
        $this->fetch();
        $this->match();
        return $this->matches;
    }
}

$query  = new MyQuery( 'psoriasis' );
$result = $query->get();
echo implode( '<br />', $result );

?>


Finding the min and max of an array, using a pointer

int b[N], *i, big, small;

printf("Enter %d numbers\t:",N);
for(i=&b[0];i<&b[N];i++)
    scanf("%d",i);

I would normally expect i to be an index variable.  If you want a one letter name for a pointer, I'd suggest p.  However, I would normally go ahead and name such a variable current.

    int b[N], big, small, *current, *end

    printf("Enter %d numbers\t:", N);
    for (current = b, end = &b[N]; current < end; current++)
    {
        scanf("%d", current);
    }

It's unnecessary to say &b[0].  Just b will do the same thing.  The compiler may optimize it out, but I find it more readable to use the variable end rather than calculate &b[N] each time.

It's generally preferred to use the block form for loops, even when the single statement form would work.  This makes it clearer what is in the loop.

It's not terribly important, but I'd consider naming b something more descriptive, even if it's just numbers.

void max_min(int a[], int n, int *max, int *min);

You wouldn't need a prototype here if you put the max_min function before main instead of after.

If you are not using an index variable, it would make more sense to pass a pointer into the function.

void max_min(int *start, int *end, int *max, int *min);

Which you can call

    max_min(b, end, &big, &small);

And then inside the function, you'd replace

int *i;
*max = *min = a[0];
for (i=&a[0]; i<&a[n]; i++)

{
    if(*i>*max)
    *max=*i;
    else if (*i<*min)
    *min=*i;
}

with

    int *current;
    *max = *min = *start;
    for (current = start + 1; current < end; current++)
    {
        if (*current > *max)
        {
            *max = *current;
        }
        else if (*current < *min)
        {
            *min = *current;
        }
    }

Note that this says start + 1 rather than start.  This is because you implicitly do the first iteration of the loop when you set *max and *min to *start.  You don't need to do it a second time.


Count number of bits to convert one integer to another integer

cmn_d = n1 & n2
all_d = n1 | n2
diff = all_d - cmn_d

There is an operator for that:

diff = n1 ^ n2

Having found the bits that differ, you want to count the set bits of diff, also known as the population count or the Hamming weight. The approach you use is simple and valid, but there are higher performing approaches which parallelise it (see here and following sections).

However, the standard approaches for the fastest parallel implementations without direct hardware support are based on fixed-width integers, and they typically go to 32 bits or 64 bits; since your specification says that you want to support 128-bit integers, you'll have to extrapolate, although it's not that hard.


Remove all adjacent duplicates in a string using a Stack

std::array

You could use std::array and get rid of max define. In general, I'd like to suggest avoiding defines which can conflict with any stl names by any cost.

One of Windows header has its own #define max and this is horrible when your code wants std::numeric_limits<int>::max(), std::max({a, b, c}), etc.

Things are even worse if you're writing header only library:

#if defined max
#  undef max
#  define HAD_MAX
#endif

// ... C++ code ...

#if defined HAD_MAX
#  define max(a, b) ... // copy-paste from Windows.h
#endif

Stack::removeAdjacentDuplicate signature

Signature of Stack::removeAdjacentDuplicate(std::string) can be improved:

At least, it doesn't actually removes anything. It perform some kind of initialization from given string, so consider choosing more intuitive name.

Additionally, avoid copying parameter - you can use const std::string&

Stack::modifyString

Stack::modifyString also says nothing about its purpose and it also constructs another string instead of modifying something. Consider better naming.

Use standard library

When copying N characters, consider using standard library functions instead of for loop: strncpy, memcpy, std::copy_n and others works fine, looks clear and may perform some performance optimizations.

Use standard library (alternative)

As alternative, you can construct new string directly from Stack::stk. There is corresponding constructor: std::string(const char* s, size_t n);. In this case you can pass all std::string parameters by const reference.

BTW, I'm assure you're already bored with my variable naming suggestions, so I don't need to add another one here :)

Non-const public members are dangerous

Consider using some naming conventions

It's hard to determine whether some variable is a class member or not. In order to simplify your work, make member variables somehow. You can use m_member, member_, etc.


In the pop and the print function, the new node seems unnecessary, since the next line modifies the pointer to point to the top. It could be simply

node *n = top;

The delete n; also looks superfluous in the print since n will always be NULL there.
If I'm right making top as static or global would result that you can't have more than one stack in an application. Linked lists usually have two classes: one is a Node which stores a reference to the next node and the data, and the second is a LinkedList class which stores the head and the implementation of the push, pop, etc. methods. You can see an example in this answer.
Take care of the boundary cases. Calling pop on an empty stack gives a segmentation fault error. I suppose that's not the best error handling method :)


Script for concatenating delimited text files

There is some repetition between your header-reading routine and the rest of the code.  You could incorporate it into the main loop to remove that duplication and avoid opening the first file twice.  You already use next(reader) nicely to read the header; use the same technique to skip the header row.

To determine the seed from a file path, you look for a - in the file path.  Your glob should have a - to ensure that that succeeds.

import csv
from glob import glob

paths = glob('*-*/unknown/*.dat')

with open('output.dat', 'a') as csv_output:
    writer = csv.writer(csv_output, delimiter='\t')
    header_written = False

    for path in paths:
        param_dir = path.split('/')[0]
        seed = param_dir.split('-')[0]

        with open(path, 'r') as csv_input:
            reader = csv.reader(csv_input, delimiter='\t')

            header = next(reader)
            if not header_written:
                writer.writerow(['seed'] + header)
                header_written = True

            for row in reader:
                writer.writerow([seed] + row)


Better way to structure and optimise try except statements

Given that there isn't much here to analyse purely based on performance since we don't know what those other function calls do, here are some minor changes:
def data_handler(message, topic):
    try:
        logging.debug(f'Invoked on topic {topic} with message {message}')
        client.publish(topic=topic + '/pass', payload=json.dumps({'state': 'pass'}))
    except Exception as e:
        logging.error(e)
        client.publish(topic=topic + '/fail', payload=json.dumps({'state': 'fail'}))

Both try/catch blocks in your code look identical, and you should have only one endpoint that needs to be communicated with. If you really need both, then there should be a separate function to have this code.
It also seems pretty redundant that you're publishing to a pass and fail endpoint and have a payload that says whether or not it passed or failed. You should know that status based on the endpoint that receives the message.
You can have the payload be more descriptive as well to remove multiple endpoints. Something like {'formatted': true, 'error': ''} is far more informative.
Lastly, you can just pass your one-off variables into this function, like so: data_handler(event, context.topic). If your event really is just a post message and not a posting event object, then that should be clarified somewhere in the code base.


Looks mostly pretty good.

When exiting with error, it's a good practice to specify a non-zero exit code, for example exit 1.

This looks odd:

if env | grep -q ^S3_BUCKET=
then
    echo "Checking if $S3_BUCKET exists"
    if aws s3 ls "s3://$S3_BUCKET" 2>&1 | grep -q 'AllAccessDisabled'

It's odd to check environment variables using env | grep.
And in this example, it looks error-prone too,
because S3_BUCKET might be defined empty, with no values.

I don't know aws, but I have a strong feeling that in case of S3_BUCKET= (empty) you would rather raise an error than run execute aws s3 ls "s3://".

I suggest to replace with a simple variable check:

if test "$S3_BUCKET"; then

In this code:

tar -zcvf $datestamp.tar.gz $datestamp
file=$datestamp.tar.gz

It would be better to set file first, and then use it in the tar

I like to avoid nested if statements when possible. For example here:

if env | grep -q ^S3_BUCKET=
then
    echo "Checking if $S3_BUCKET exists"
    if aws s3 ls "s3://$S3_BUCKET" 2>&1 | grep -q 'AllAccessDisabled'
    then
        echo "bucket $S3_BUCKET doesn't exist please check again."
        exit
    fi
else
    echo 'S3_BUCKET is not set please set it'
    exit
fi

I would flatten by inverting the outer if:

if test ! "$S3_BUCKET"
then
    echo 'S3_BUCKET is not set please set it'
    exit 1
fi

echo "Checking if $S3_BUCKET exists"
if aws s3 ls "s3://$S3_BUCKET" 2>&1 | grep -q 'AllAccessDisabled'
then
    echo "bucket $S3_BUCKET doesn't exist please check again."
    exit 1
fi


JavaScript: Find the number in an array which is closest to an given number

Your main questions

  Can I expect my implementation to solve the task in a correct way?

You should know that the answer is "yes" before posting a question on Code Review.

  Was it a good idea to initialize the 'closest'-variable with the value of the 'compareNumber'-parameter?

No, it's a mistake. The function incorrectly returns 0 for input [10, 9], 3.
When looking for the minimum distance,
you must choose as the default the largest possible number.
For example if you target ES6, then Number.MAX_SAFE_INTEGER.

  Was it a good idea to check for 'currentDistance < closest'? Or should I have used 'currentDistance <= closest'?

That depends entirely on the specification.
If you're looking for the first closest index, then use <.
If the last, then use >.

If the specification was not clear,
then ask to clarify.

Naming

The names are overly verbose.
When short names are sufficient, they are better than long names.

For example,
in a function to find the closest index to a number,
the array parameter is obviously for searching,
so instead of arrayToSearch, it could be simply nums,
and compareNumber could be target.

I would have written like this:

function indexOfClosest(nums, target) {
  let closest = Number.MAX_SAFE_INTEGER;
  let index = 0;

  nums.forEach((num, i) => {
    let dist = Math.abs(target - num);

    if (dist < closest) {
      index = i;
      closest = dist;
    }
  });

  return index;
}


Print max occurring character in a String

Primitives over wrapper classes

public static Character findMaxOChar(String text) { ... }

It's usually recommended to prefer the primitive type over its wrapper class, unless you have a clear intention to return null values for indicating the absence of a value.

Interfaces over implementations

HashMap<Character, Integer> map = new HashMap<Character, Integer>();

Using the Map interface over the HashMap implementation is often recommended, as subsequent usage of the object only needs to know it's a Map. Since Java 7, you can rely on type inference for generic object creation to eliminate the redundant type specification on the right, i.e.:

Map<Character, Integer> map = new HashMap<>();

Java 8 stream-based processing

Assuming you are on Java 8 and eager to learn about its new stream-based processing, this is a good candidate for adopting this approach. :) For starters, you need to understand:

String.chars() can give you an IntStream of the string's characters, as long as we're talking about Western-based encoding.
A Collector that lets you apply some processing on a Stream to return some form of results, e.g. a Map in your case. Converting an IntStream to Stream<Integer> by calling IntStream.boxed().

Building the Map can be just:

Map<Character, Long> map = text.chars()
                                .boxed()
                                .collect(Collectors.groupingBy(
                                            i -> Character.valueOf((char) i.intValue()),
                                            Collectors.counting()));

Here, we are groupingBy mapping the Integer values into Characters, and counting the number of occurrences.

Following the same idea,  you can call Map.entrySet().stream(), i.e. to stream on map's entries, to:

Group by the entries' values now, into a TreeMap, by mapping the entries' keys into a List,
Get the TreeMap's last entry, and from that entry's value, find any value to return as the result.


Lindenmayer System String Generator in F#

To simplify you should just split at the F's and replace each section of +, -, X and Y characters with a string of +, a string of - or the empty string depending what the final balance of +/- characters are. Then you will only be making one pass over the string.

Consider what happens with your approach if the string to be simplified is ++---. If I understand your code correctly you end up with +++ which you would like to represent as -. In order to do this, however, you have to make another pass over the string.

Using my phone right now. When I get to a real computer I'll update with some code.

Update: You can see a Haskell implementation of simplify here: (link). It should readily translate to F#.


Object-oriented web scraping with Python

Use top-level functions

Reading URLs from a file and checking each of them for vacancies is done at the top-level of the file. You should enclose this code into functions and put the remaining top-level code under if __name__ == '__main__' to:

separate the intents;
reuse the code more easily;
not have random code execution when importing the module.

Use filter

You are only interested in knowing which URL have vacancies. The easiest way to perform that is to:

interesting_urls = filter(has_vacancies, url)

with the proper definition of has_vacancies.

You also only print 'Has vacancies' when a given URL has so, letting the user try to figure out which one actually has. You might want to print the URL instead to make your script more usable:

print 'Following URLs have vacancies'
for url in filter(has_vacancies, urls):
    print url

Use generators

There is no need to store all the URLs you’ll be checking up-front. Yield them from a generator since only one is processed at a time:

def read_urls(filename):
    with open(filename, 'rb') as spreadsheet:
        reader = csv.reader(spreadsheet)
        for row in reader:
            yield row[0].strip()

It also allows you to parametrize with the name of the file to read, in case you have several of them.

Do not force OOP when not required

You are not interested in storing a state about each URL. You just want a simple question answered: "does this URL points to a page that provide vacancies?" Thus a simple function will do, for each URL:

def has_vacancies(url):
    source = urllib2.urlopen(url).read()
    return not(any(text for text in NO_VACANCIES if text in source.lower()))

See what I did there? This is the exact function we need for the filter I introduced earlier.

Remove extraneous computation

Calling lower() on a string has its cost. Calling it once for every piece of text your are looking for in said string is even more costly. You should call it only once after fetching the source of the URL.

Of a lower interest, any is converting pieces of text to their truthy value after a test text in source already returned True. You also store source, self.url, self.source (and, to a lesser extend, page) without really needing it. But I’ve shown ways to avoid it.

Proposed improvements

import csv
import urllib2

NO_VACANCIES = ['no vacancies', 'not hiring']

def has_vacancies(url):
    source = urllib2.urlopen(url).read().lower()
    return not any(text in source for text in NO_VACANCIES)

def read_urls(filename):
    with open(filename, 'rb') as spreadsheet:
        reader = csv.reader(spreadsheet)
        for row in reader:
            yield row[0].strip()

def check_vacancies(filename):
    print 'Following URLs have vacancies'
    for url in filter(has_vacancies, read_urls(filename)):
        print url

if __name__ == '__main__':
    check_vacancies('25.csv')

Going further

You might be interested in trying the re module to perform text matches, there may be a performance improvement.

Alternatively, the multiprocessing module provide a map_async performed in parallel by a pool of workers. You might want to change has_vacancies a bit and use that instead of filter to increase overall performances.

You may be interested into handling exceptions from urllib2 so a sudden networking failure or an invalid URL won't crash everything. Something simple can do:

def has_vacancies(url):
    try:
        source = urllib2.urlopen(url).read()
    except urllib2.URLError:
        print 'Error processing', url
        return False
    else:
        source = source.lower()
    return not any(text in source for text in NO_VACANCIES)


I'm not really sure if your code matches the intention of the task, albeit you possibly might get the expected results.

At first, you are producing a new array, whereas the task is 'all elements raise their values', which I read that you should modify the array in place.

Then I'd rather assume that you should implement a single operation in a function which then gets called M times, example:

void applyOperation(int array[], size_t length, size_t begin, size_t end, int operator);

int array[] = { 1, 1, 1, 4, 5, 6 };
applyOperation (array, sizeof(array)/sizeof(*array), 1, 5, 2);
applyOperation (array, sizeof(array)/sizeof(*array), 2, 3, 10);
// print result

M is 2, function is called twice (I renamed N to length...).

Whether you now implement the function to execute one operation at a time or all at once, you shouldn't iterate over the entire array and then check if the index is in the range, instead you'd iterate over the range directly:

void applyOperation(int array[], size_t length, size_t begin, size_t end, int operator)
{
    --begin; --end; // they want one-based indices? bad idea for C++,
                    // but OK, then let's adjust them to zero-based...

    for(;; begin != end; ++begin)
    {
         array[begin] += operator;
    }
}

Looks much easier, doesn't it? What's actually lacking yet is checking the range of begin and end, assuming you manage this yourself...

Now if you want to have all operations in one single go, then it is much more comprehensive if you iterate over the operations in first place:

void applyOperations(int input[], int operations[], int N, int M)
{
    for(int i = 0; i < M; ++i, operations += 3)
    // this assumes: each operation occupies three subsequent values
    {
         // now using operations[0] as begin, operations[1] as end
         // and operations[2] as operator just like above

         // it might be unacceptable to modify the operations array, then you'd
         // need a separate loop variable compared to above; but IF it is,
         // then you should keep the operations const anyway:
         //int const operations[]
    }
}

Finally: You tagged the question C++ – your code could as well be good old C, though. In C++, you'd rather use std::array or std::vector than raw arrays. Whichever you use, you don't have to provide size/length separately, both come with their own member function size() giving the number of elements (not size in bytes as sizeof operator does, so you'd avoid the ugly sizeof(x)/sizeof(*x) at the same time – even more important: you could provide a bad value for length, this cannot happen with the C++ containers as these manage their length/size on their own).

void applyOperation(std::vector<int> values, size_t begin, size_t end, int operator)
{
    --begin; --end;
    for(;; begin != end; ++begin)
    {
         values[begin] += operator;
    }
}

The loop still looks similar, but range checking would now use values.size() instead of a length parameter.

One final note: Did you notice that I changed the parameter types to size_t? Two reasons for this:

size_t is an unsigned type. Negative indices are meaningless in the given task, so why allow them at all?
size_t mapped to the native type large enough to hold an object of maximum size on given system (which means at the same time that it will always be large enough to index any member in an array). This is obviously not relevant in given case, as your arrays' sizes most likely won't ever exceed the range of ordinary int - but you simply cannot fail this way, so if you get used to it, you'll be well prepared for the future...


Implementing checksum add without carry in C

It appears code is simply exclusive or-ing the arguments.  Sounds like a "add without carry".

"Is my logic for the implementation correct?"
Appears correct except the range of acceptable values is not clearly stated.
Gotcha 1.  What is UINT?  If UINT is narrower than int/unsigned, the arguments will be widened and va_arg(valist,UINT); is problematic.  Recommend unsigned instead.
Gotcha 2. arg1 = va_arg(valist,UINT); arg2 = va_arg(valist,UINT); Only makes sense if n it at least 1 or 2.  Should test for that first.
if (num > 2) {
    for (i = 2; i < num; i++) { looks dodgy.
Simplify

va_list valist;
va_start(valist, num);
unsigned result = 0;
while (num-- > 0) {
  result ^= va_arg(valist, unsigned);
}
va_end(valist);
return result;


Showing object's data on GUI and HTML without accessors and mutable objects

Your outset is wrong. The articles you've linked to present a nice story, but what you're running into here is the issue with that ideology:

When your data structures AND your views are rigid, you can't change the system to do anything else.

You're now stuck!

Say I had to show a listing of Employees. I can't! There is no way to use the data stored in Employee to make a screen that contains a listing of employees. I also cannot make a REST API with this Employee object without some serious magic - I'd have to make a "View" which takes multiple Employees and ignores calls to "show" unless they're from an authorized source.

You say "Class Employee is not responsible for showing itself".

public final class Employee {

  //...
  public void showOn(View view) {
    view.addData("Name", name.toString())
        .addData("Salary", salary.toString())
        .show();
  }
}

What's the show() doing here? Why does the Employee decide when the view is ready? Maybe I have a page consisting of a Project and the Employees that work on it. I'd have to make custom subviews.

You're right in that the Employee does not decide HOW it is shown, but it does decide WHAT is shown and WHEN it is shown. Which is not a desired property.

That, or I'd have to alter Employee to add View logic to support multiple or partial employee views. Which is bad, because standards constantly change, and you don't want to alter all your model classes to be able to give a view that can be used for that standard (e.g. something that you can convert to JSON).

Additionally, by limiting yourself to those constraints, you can no longer leverage certain libraries! It's fun and all to harp on the gigantic projects and code cruft that comes with using big libraries like Hibernate and Spring and such, but if you need to build a REST API and a phone app, being able to have libraries handle your object conversion to json and back (and in case of android, maybe even SHARE the model objects as a library!)... you can't do it in your setup! There are no getters, objects are immutable, libraries don't support this.

Employee.View is oddly specific class; it doesn't make any mention of Employee:

  public interface View {
    View addData(String name, String value);
    void show();
  }

Let's say we had projects later - will there also be Project.View? What methods will it contain? The same? Mostly the same?

This leads to code duplication, which is really bad!

In your HTML page you use a table, and for that, String name, String value will do. But for non table situations, like a stackexchange profile, you have graphs for reputation, lists of answers and questions, it's partially sortable, some are numbers, others are text, some of the numbers are rounded (reputation is shown as ##.#k, rather than a 5 digit amount)...

All of that is either HARD or NOT POSSIBLE just because you're following the dogma of "You should never have Getters/Setters near your code.".

Such an idea is DANGEROUS in this case!

But you link to more than just 1 article of this guy, so maybe you really like what he says and I won't get through to you by just pointing at your code. Let's point at his:

Dog dog = new Dog();
dog.setBall(new Ball());

You could say this can be improved; Dog can have 0 to many objects to play with. Maybe it's carrying up to one object at a time. You could either use setCarriedObject (but that's secretly setBall), or, perhaps better, take(PlayObject). I call it PlayObject but basically anything that you could give to the dog to carry around would work. We're not using a very strict object hierarchy here.

Then, of course, if we're gonna play fetch, we'd have to retrieve the ball.

Dog dog = new Dog();
Ball ball = dog.getBall();

Because we've rephrased setBall to take (the dog takes the ball... because you've ordered him to), getBall is obviously going to become give.

But they're still getters and setters, we just call them differently now. They do the same.

The author comes to the same conclusion:

Dog dog = new Dog();
dog.take(new Ball());
Ball ball = dog.give();

So far, I get the point; getters and setters show that you might not have thought about the usecases and are treating your objects as dumb things, and maybe you want to emphasize that there's actual work being done.

But then the author says this:

  Now, we're treating the dog as a real animal, who can take a ball from us and can give it back, when we ask. Worth mentioning is that the dog can't give NULL back. Dogs simply don't know what NULL is :) Object thinking immediately eliminates NULL references from your code.

How?!

If I do this:

Ball ballInMyHand = new Ball();
Dog dog = new Dog();
Ball otherBall = dog.give();
dog.take(ballInMyHand);

What's otherBall gonna be? The author says it's not going to be null. In that case, the options we've got left are these:

Null-representative value; the dog gives you "air" or a NonExistantBall
A new ball; the dog steals one from the neighborhood
The ball that was previously in my hand; the dog knows where all the balls are and can use reflection to obtain any ball
NoBallException; the dog goes mad and dies, possibly killing you (The program)
Infinite loop; the dog searches for a ball forever, and we're relying on the inherent multi-threaded way that the world works for a person to tell the dog to stop searching (but this doesn't happen, so you're stuck forever)
Program exits with fault code; the universe stops existing

And, save for the "air" option, they're all really bad choices! Exceptions for regular cases, infinite loops, program exits... what's so bad about null?

Back to Employees for a moment; say I want to generate a report that tells me all the costs I spend on Employees per month. That's salary, compensations, bonuses and all that. I sure hope there's an alternative data source out there, because the only way I'm gonna get to that data is by pretending I'm going to display it. I guess adding up all the salaries is gonna be done by casting String to int again.

It's also weird that I have to delete the old employee if I want to give them a raise.

You also have the issue that your views are stringly typed: if you wanted to prominently display Job title at the top, you'd have to filter via if(name.equals("Job title")). And if we ever change it to Job Title or Title or Role or Occupation then guess what, we're going to have to go back and change everything again! IDE's may or may not support this refactoring, so chances are you'd have to do all this by hand.

To summarize - what you've done presents multiple problems:

Views and Model are tightly coupled
New views require model alteration (violation of open-closed and SRP)
Less library support means more manual work
View class is likely to be duplicated
Model giving data rather than providing data means views are limited in what they can do

and I see no real benefits.

But lets say your boss says "I've read this article, and this stuff is amazing! You programmers should work to build our apps like this. Now, I've already discussed this with the managers and we're going with this, so if you don't like it, there's the door." There's no way you're going to convince your boss, he has decided that this way is the way. And you need your job, whilst quitting does sound nice, you need the money, and if you don't work you don't get paid.

What do you do?

In that case, take immutability up another level.

Instead of treating your objects like forms to be filled in and stored, like HtmlPage, create printers of a sort.

Employee goes in, EmployeeReport comes out. If you want a different report, either feed the Employee into a different ReportMaker, give the ReportMaker different settings, or pass more Employees into ReportMaker.

Pure functional programming like that exists, and whilst Java isn't the best language for it, Java 8 made things a lot better. You don't have to carry state around all the time. Once you have the report you need, you can drop all instances of objects and just request them new later.


Limit an integer to certain number of digits and suffix '+'

Use less powerful language constructs

You use if and else

if (in >= max) {
    return String.valueOf(max - 1) + "+";
} else  {
    return String.valueOf(in);
}

Using if and else duplicates return String.valueOf

Here the ternary operator comes to the rescue. It looks hard but really is very easy to use.

condition ? a : b

If condition is true, than a, else b. As easy as that.

You can now write return String.valueOf just one time:

return String.valueOf(in >= max ? (max - 1) + "+" : in)


Google Foobar Challenge: Spy Snippets in Python

Class attribute

Having input_array = [] defined at class level does not add anything except confusion.

Counter

I think that this:

no_of_search_terms = 0
count = dict()
for searchTerm in searchTerms:
    if searchTerm in count:
        count[searchTerm] += 1
    else:
        no_of_search_terms += 1
        count.update({searchTerm: 1})

could be done in a clearer and more efficient way using: collections.Counter.


Set a font for a UITextView if the font is nil or not equal to desired font

There's a much easier way of doing this.

if self.view.font?.fontName != mongolFontName {
    view.font = UIFont(name: mongolFontName, size: defaultFontSize)
}

We should always prefer optional binding and optional unwrapping (?) to forced (!).

When the value we're optionally unwrapping is nil, we just get nil back.  And of course, nil and mongolFontName aren't going to be the same (unless you've set up mongolFontName as nil), so we enter the if's body.

Consider this example from the playground:


How to improve my JS code? Avoid repeated element

This code is perfectly fine (aside from the fact that it's weird to clean up className and then add one item to classList—might as well set className directly).

DRY is about repetition of logic (which is dangerous because you may forget to change it in one place when you change it in the other place). Repetition of variable name is totally fine.

In fact, sometimes some verbosity is preferred to excessive succinctness.

// Bad

sb.className = "";
sb.classList.add(test);
sb.dataset.kind = 'web';
sb.addEventListener('click', function() {
}, true);

// Good

searchWebButton.className = "";
searchWebButton.classList.add('search');
searchWebButton.dataset.kind = 'web';
searchWebButton.addEventListener('click', function() {
}, true);

You're not repeating yourself—these are several distinct actions, and they are obvious.
There is nothing to simplify here.

As noted by Greg, if you did this sequence of calls for several elements, you could have extracted them into a function:

// Hm-kay

searchWebButton.className = "";
searchWebButton.dataset.kind = 'web';
searchWebButton.classList.add('search');
searchWebButton.addEventListener('click', function() {
}, true);

searchHistoryButton.className = "";
searchHistoryButton.dataset.kind = 'history';
searchHistoryButton.classList.add('search');
searchHistoryButton.addEventListener('click', function() {
}, true);

// Good

function setupSearchButton(btn, kind) {
  btn.className = "";
  btn.classList.add('search');
  btn.dataset.kind = kind;
  btn.addEventListener('click', function() {
  }, true);
}

setupSearchButton(searchWebButton, 'web');
setupSearchButton(searchHistoryButton, 'history');

Note that btn by itself is short but not descriptive, and it would make a bad name in outer scope, but as a parameter to setupSearchButton it's obvious so we can keep it short.

It also might be a good idea to extract initialisation code if the initialization is long and you have several other elements to initialize (and maybe something else) in one function:

// Hm-kay

function initialize() {
  searchField.className = "";
  searchField.classList.add('search');
  searchField.addEventListener('change', function() {
    search();
  }, true);
  searchField.addEventListener('focus blur', function() {
    refreshSearchPlaceholder();
  }, true);

  searchWebButton.className = "";
  searchWebButton.dataset.kind = 'web';
  searchWebButton.classList.add('search');
  searchWebButton.addEventListener('click', function() {
  }, true);

  doSomethingElseForInitialization();
}

// Good

function initialize() {
  initializeSearchField(searchField);
  initializeSearchButton(searchWebButton);
  doSomethingElseForInitialization();
}

function initializeSearchField(field) {
  field.className = "";
  field.classList.add('search');
  field.addEventListener('change', function() {
    search();
  }, true);
  field.addEventListener('focus blur', function() {
    refreshSearchPlaceholder();
  }, true);
}

function initializeSearchButton(btn) {
  btn.className = "";
  btn.classList.add('button');
  btn.dataset.kind = 'web';
  btn.addEventListener('click', function (e) {
    e.preventDefault();
    search();
  }, true);
}

For some ideas about easy-to-maintain JS code, read Airbnb Javascript Guide (or any other popular guide, for that matter).


Redirect incoming traffic based on referrer or random number

null coalesce does exist in php according to the google (per: https://stackoverflow.com/questions/1013493/coalesce-function-for-php )

$s = $_SERVER["HTTPS"] ?: "";
$protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;

I'm not super familiar with php, but I think this should work from what I understand you're doing here.


1. Is the intent clear?

Not completely for me. As you're saying

  for the real thread code, leaving any other locks, mutexes, etc. in place, allows me to gain some insight as to how the various threads might run.

the closest intent I can grasp is, you want to eliminate certain threads by replacing them with worksim threads, to isolate other threads that might be the source of race conditions, dead locks or other multiple threading related problems in the to be tested code.

I'm not a 100% sure if these simplified threads may be really useful for diagnosis of the above mentioned problems. Especially as they won't affect other threads, other than with a random delay and don't touch those synchronization mechanisms left in place. To some degree may be.

2. Is the use of a static number generator OK here?

The instantiation of static local variables will be thread safe. Execution of operations like dist(gen)) will not guarantee thread safety.

The reference documentation about std::binomial_distribution::operator() doesn't tell anything about thread safety, and because gen is a shared resource between threads I would doubt about appropriate results.

3. is there a better way to handle the logging?

The standard I/O output can be fairly slow, and as I mentioned in my comment "The use of a shared logger with the mutex locking may severely influence your threads' runtime behavior".

A generally better approach might be to use the shortest possible lock to pass the log message to the logger (e.g. using a protected queue of std::unique_ptr's), and let the Logger class output these from another background thread (that's what we're using in our production systems).