Using Common Table Expression and Outer queries

I find the query rather difficult to read due to your indentation style.  For your benefit and for the benefit of other reviewers, I've reformatted your query, changing only the whitespace:

WITH CTE (employee_id, RID, instalment, reference, recovered_amount, total_amount) AS (
    SELECT SalaryTrans.employee_id
         , Recovery.RID
         , Recovery.amount / Recovery.duration AS instalment
         , SalaryTrans.reference
         , SUM(Instalment.recovered_amount) AS recovered_amount
         , Recovery.amount AS total_amount
        FROM Recovery
            INNER JOIN SalaryTrans
                ON Recovery.emp_id = SalaryTrans.employee_id
            LEFT OUTER JOIN Instalment
                ON Recovery.RID = Instalment.recovery_id
        GROUP BY SalaryTrans.employee_id
               , SalaryTrans.reference
               , Recovery.RID
               , Recovery.amount / Recovery.duration
               , Recovery.amount
)
SELECT RID, Balance, reference
    FROM (
            SELECT RID
                 , "Balance" = CASE
                      WHEN recovered_amount != NULL THEN total_amount - recovered_amount
                      ELSE total_amount
                   END
                 , reference
                FROM CTE
        ) AS Result
    WHERE Balance > 0

In particular, note:

For anything other than a trivial SELECT, use a separate line for each column being selected.  (My use of leading commas may be controversial.  I find that it helps prevent silly mistakes when editing the query to add and remove columns.)
The indentation matches the clauses of each expression.  For example,

The big-picture structure is WITH (CTEs) SELECT (something).

Within the CTE, SELECT takes a FROM clause and a GROUP BY clause.

The FROM clause consists of two JOINs.

The main SELECT has a FROM clause and a WHERE clause.

Within the CASE, make it more obvious that the THEN is associated with WHEN.

Use a space on each side of binary operators such as !=, -, and >.


static vs instance

Your variable root should probably not be static. Instead, it should be an instance variable so you could have multiple BinarySearchTrees in a single program.

node vs root

In most places, your naming of node vs root is good.
In some places, I found it a bit misleading: In printPreOrderTree(), printInOrderTree() and printPostOrderTree() I'd rather call it node than root. I'd use root only for that type of node for which the system has no parent.

element vs item (vs data?)

I think you can get rid of one of these terms and only use the other. I'd use item and dismiss element. I find element too abstract, the term could also be a supertype of node. I think item describes the payload of a node better than element.
But then again, maybe simply data would be even better?

Simpler Code in addItem()

Since you don't need to remember the variables, you can simplify the code.

Your code:

private TreeNode addItem(TreeNode root, int item) {
    if (root == null) {
        root = new TreeNode(null, item, null);
        return root;
    } else {
        if (item < root.element) {
            if (root.left == null) {
                TreeNode node = addItem(root.left, item);
                root.left = node;
            } else {
                addItem(root.left, item);
            }
        } else if (item > root.element) {
            if (root.right == null) {
                TreeNode node = addItem(root.right, item);
                root.right = node;
            } else {
                addItem(root.right, item);
            }
        } else {
            System.out.println("Duplicate Item");
        }
    }
    return root;
}

Simplified code:

private TreeNode addItem(TreeNode root, int item) {
    if (root == null)
        return new TreeNode(null, item, null);
    else if (item < root.element)
        if (root.left == null)
            root.left = addItem(root.left, item);
        else
            addItem(root.left, item);
    else if (item > root.element)
        if (root.right == null)
            root.right = addItem(root.right, item);
        else
            addItem(root.right, item);
    else
        System.out.println("Duplicate Item");
    return root;
}

And since the recursive addItem() is called anyway and checking root for null anyway, it can be even simpler:

private TreeNode addItem(TreeNode root, int item) {
    if (root == null)
        return new TreeNode(null, item, null);
    else if (item < root.element)
        root.left = addItem(root.left, item);
    else if (item > root.element)
        root.right = addItem(root.right, item);
    else
        System.out.println("Duplicate Item");
    return root;
}

Use stderr instead of stdout for error messages

Your error message

        System.out.println("Duplicate Item");

should not go to stdout but to stderr, I guess.

        System.err.println("Duplicate Item");

Use the Visitor pattern?

In printPreOrderTree, printInOrderTree and printPostOrderTree, you always visit all nodes.

The recursion over the nodes is always the same. What differs is the event placement and the action.

If your code gets more complex and you have more such recursions over the tree, you might want to use the Visitor design pattern to separate the recursion from the action to be performed with the node.


How to speed up a treeview population in Access?

Avoid the multiple DLookUps with eachTreeView.Nodes.Add call for every row of recordset! At the very least store your DLookUp value once and apply it to treeview. This cuts down the repetitive 4 calculations down to 2 for every row.
But since DLookUp essentially is a query anyway, simply integrate a JOIN to Master object in SQL queries of OpenRecordset calls. This cuts down the repetitive 4 calculations to 0 for every row.
sql = "SELECT d.[Tagname], m.[Tagname] AS [MasterTagname] " _
       & "FROM tblData d " _
       & "LEFT JOIN Master m " _
       & "    ON m.ID = d.[Tagname] " _
       & "WHERE NOT d.[Attribute] = " & cbxAttributeFilter01 _
       & "  AND NOT d.[Property] = " & cbxPropertyFilter01

Set oNone = CurrentDb.OpenRecordset(sql, dbOpenSnapshot)

sql = "SELECT d.[Tagname], m.[Tagname] AS [MasterTagname] " _
       & "FROM tblData d " _
       & "LEFT JOIN Master m " _
       & "    ON m.ID = d.[Tagname] " _
       & "WHERE d.[Attribute] = " & cbxAttributeFilter01 _
       & "  AND d.[Property] = " & cbxPropertyFilter01

Set oData = CurrentDb.OpenRecordset(sql, dbOpenSnapshot)

...

TreeView.Nodes.Add sTemp, tvwChild, !MasterTagname, !MasterTagname

...

TreeView.Nodes.Add "MISC", tvwChild, !MasterTagname, !MasterTagname

Also, best practice in VBA is to never use On Error Resume Next but to handle any error that raises which in this case may be a missing or Null DLookUp result. Therefore, enclose If logic.
...

If Not IsNull(!MasterTagName)
   TreeView.Nodes.Add sTemp, tvwChild, !MasterTagname, !MasterTagname
End If

...

If Not IsNull(!MasterTagName)
   TreeView.Nodes.Add "MISC", tvwChild, !MasterTagname, !MasterTagname
End If


You can take advantage of the fact that you're iterating in increasing order, i.e. the trivial fact that if a number is greater than n, then it's also greater than any number below n; thus you can just keep track of the latest threshold you passed and only check if you've reached the next one.

let thresholds = [2, 4, 5, 10, 50, 100, 1000];
let increments = [0.01, 0.02, 0.1, 0.5, 1, 10];
let p = 0;

function createKeysWithTicks(array) {
    let i = 1.0;
    while (i < 1000) {
        array.push(Number(i.toFixed(2)));
        i += increments[p];
        if (i >= thresholds[p]) {
            p++;
        }
    }
 }


Your code includes the optimization of evaluating only odd-valued candidates (by iterating with a step size of 2) because the even-valued candidates are known to contain a factor of 2, and are therefore always composite.

This candidate-skipping optimization can be generalized to include prime factors greater than 2, by varying the step size in a certain way.

I made a version of your code which skips candidates (values of nur) containing factors of 2 and/or 3.  This is done fairly cheaply by alternating step size between 2 and 4.

Extending this optimization to even greater primes gives diminishing returns for two reasons: The step size adjustment calculation becomes more complex (and slower), eventually costing more time than what is saved by skipping candidates; and higher prime factors exist more sparsely than low ones in the candidate population.  Skipping 2 alone catches 1/2 of the composite candidates, and skipping 3 alone would catch 1/3.  But if used together, half of the composites 3 would skip were already skipped by the 2 skip, so skipping 3 just catches an additional 1/6 of the composite candidates.  Including a 5 skip would only eliminate an additional 1/30 of the composite candidates, and a 7 skip 1/210.

I experimented with replacing the floating-point sqrt call with an integer approximation, but it turns out that sqrt is very fast (at least on my machine).  And then I gave up entirely after seeing Vedran Šego's optimization, which is brilliant, especially because as nur gets bigger, the gaps between calls to sqrt become larger, to the point where it doesn't really matter much how slow your sqrt calculation is.  So, I had to add this to my example, thank you Vedran Šego.

One other thing, the nur loop must terminate.  If nur is signed (like int), it will overflow and wrap around to a negative value. This is a completely pathological situation -- calling sqrt with a negative number, plus other things, depedning on optimizations employed.

Even for unsigned nur, duplicate primes will be added to the primes vector until the process crashes when it runs out of memory.

So my example terminates before nur overflows.  I also defined a prime_t type, to make it easy to switch the integer type used for calculating and storing primes.  I use unsigned int in my example, because it gives results a larger maximum value at no extra cost compared to int.  Try unsigned long long if you really want to see the program continue for much longer than you will be willing to wait.

#include <iostream>
#include <vector>
#include <cmath>

typedef unsigned int prime_t;
// max_prime_t is the maximum value which may be held in a variable of type prime_t
// this assumes prime_t is an integer type (signed or unsigned)
// It dupicates information available from std::numeric_limits
const prime_t max_prime_t =
     prime_t(0)-prime_t(1) > prime_t(0) ?
         ~prime_t(0) :
         ~prime_t(0) ^ (prime_t(1) << (sizeof(prime_t)*8-1));

int main() {
    std::vector<prime_t> primes = { 2, 3 };
    prime_t ilimit = 0;
    prime_t ilimit_limit = 0;

    static const prime_t max_nur = max_prime_t - 4;

    // "step" alternates between 2 and 4,
    // to skip values containing factors of 2 and/or 3
    for(prime_t nur=5, step=4; nur<=max_nur; nur += (step ^= 6)) {
        if(nur >= ilimit_limit) {
            // Vedran Sego's optimization
            ilimit = static_cast<prime_t>(std::sqrt(nur));
            ilimit_limit = (ilimit + 1) * (ilimit + 1);
        }
        for(auto one_prime : primes) {
            if(one_prime > ilimit) {
                std::cout << nur << '\n';
                primes.push_back(nur);
                break;
            }
            if(nur % one_prime == 0) {
                break;
            }
        }
    }
}


The goal of a skip list is that you can do a find by doing a loop like:

Node find(T value){
    Node start = root;

    while(start!=null && comp(start.value, value) != 0){

        if(comp(start.next.value, value) < 0){
            start = start.next;
        }else{
            start = start.down;
        }

    }
    return start;
}

Note the comp helper function. I added that so you can easily make it use a custom Comparable<T> passed in during construction.

This can be easily expanded to also keep a list of nodes to update should you want to insert/delete a value:

List<Node> findAllPrevs(T value){
    List<Node> prevs = new ArrayList<>();
    Node start = root;

    while(start!=null){

        if(comp(start.next.value, value) < 0){
            start = start.next;
        }else{
            prevs.add(start);
            start = start.down;
        }

    }
    while(prevs.get(prevs.size()-1).down!=null){
        prevs.add(prevs.get(prevs.size()-1).down);
    }
    return prevs;
}

Then you only need to update the last depth nodes in prevs when you add or remove a value.


I wouldn't assume to go for the First, rather I'd have a Func<T, bool> predicate parameter which you pass to a .FirstOrDefault(predicate) and ?? it with .First()

Also, I'd verify IEnumerable<T> != null before anything.

static void GuaranteeAtLeastOne<T>(IEnumerable<T> list, Func<T,bool> getter, Action<T> setter, Func<T,bool> predicate)
{
    if (list == null || list.Count == 0 || list.Any(getter))
    {
        return;
    }

    setter(list.FirstOrDefault(predicate) ?? list.First());
}


Would this linked list be considered clean if written in an hour-long interview?

I can't speak for others, but I'd personally have some reservations. To be fair, perhaps I'm not being lenient enough for doing this under pressure in an hour, but there are multiple issues that I'd want to address with this code.

Questions and Small Problems

Why is node not an internal class of linked_list? Generally, the user should neither know nor care about exactly how a node is represented. I'd let this slide pretty easily though, because it's a small oversight and can be fairly easily corrected.

You're not passing to your node constructor by const T& which I would have expected. If this is constructing from a type that is expensive to copy construct, this adds quite a bit of overhead.

Usage of NULL vs nullptr. Not a big deal, but it'd make me push you a little bit on knowledge of C++11 constructs.

Pain Points

The interface for your list is (somewhat) setup, but the implementation is very, very incomplete. As it currently stands, it doesn't really represent a list at all, but something that holds the address of a single element that exists outside the list, and is therefore tied to the lifetime of that object (which is a big, big problem).

Your linked_list constructor takes a node<T> as a parameter. This goes back to the first point about node being internal, but here it is more serious in my mind. This shows that you do expect the user to know/care about the node type. It also takes it by reference, and then simply makes the head node point to that address. This is all a bit worrying. It should be taking an element of type T, which it then wraps up in a node, and that is stored as the head element:

linked_list(const T& initial)
  : head(new node(initial))
{ }

You never new or delete anything - a linked_list that uses absolutely no dynamic storage is very strange indeed. It'd certainly make me want to press you on things like object lifetimes, stack and heap allocation, dangling references and the like.

There is no way to modify a list once it is created; something as basic as adding an element isn't possible. Even if these functions weren't finished in time, I'd expect just the declarations to be there, something like:

void push_front(const T& data)
{ }

Because of the lack of dynamic allocation, your copy constructor and assignment operator don't really do anything, and you don't have a destructor. Implementations of these would be something I'd heavily scrutinize. For a start, do they do what they are supposed to do? A copy constructor should be doing a deep copy of the list it is passed - many people get this wrong and end up simply doing a shallow copy, which generally means pointers pointing to deleted memory, and undefined behaviour.

operator= should either be using the copy-swap idiom or at least doing basic checks like (this != &rhs), clearing the current data in the list, and copying the data from what is passed in as the argument to operator=. With your current implementation, none of this can be demonstrated properly.

Why is get_head declared as node<int> *? Why are you returning a node instead of simply returning the data? This should have two overloads, one for const T& and one for T&.

Operators shouldn't be member functions, but that's pretty minor, and I wouldn't really care too much. However, if you do make them member functions, they should definitely be const:

bool operator!=(const linked_list &other) const
                                        //^^^^^

All in all, there is a lot lacking for an implementation, even given the short time span. The lack of any kind of dynamic memory allocation would probably be a deal-breaker for me personally. Without being able to hear your reasoning about this, I'd make the assumption that you didn't understand allocations or object lifetimes, which is of critical importance when programming in C++.

Edit: If given a limited time (such as one hour) to write something like a list, I'd probably approach it in the following way: firstly, sketch out the minimal interface I want to develop from. Given the pretty strict time requirements, I'd keep it as simple as possible:

A private internal node struct with all public members (this cuts down on boilerplate code that needs to be written, and since it's private, it's not user facing, so I'd argue it's fine anyway).
Private members for list, which I'd keep to a node *head and std::size_t size.
Basic constructors, copy assignment, copy constructor, destructor.
Insert, update and delete. Since this is a singly linked list, insert would be limited to adding something to the front (push_front if we're following standard lib naming), something to update a given value, and something to delete a given value. Usually these would use iterators, but that's too complex given the tight time restrictions.
Something to get the size, if the list is empty, and maybe some basic comparison operators.

Sketching out this API, I'd have something like:

template <typename T>
class linked_list
{
private:

    struct node
    {
        T data_;
        node* next_;

        node(const T& data)
          : data_(data),
            next(nullptr)
        { }
    };

    std::size_t size_;
    node* head_;

public:

    linked_list()
      : head_(nullptr),
        size_(0)
    { }

    linked_list(const T& data)
      : head(new node(data)),
        size_(1)
    { }

    ~linked_list() { }
    linked_list(const linked_list& rhs) { }
    linked_list& operator=(linked_list rhs) { } //Use copy-swap idiom

    bool is_empty() const { }
    std::size_t size() const  { }

    void push_front(const T& value) { }
    bool remove(const T& value) { }
    bool update(const T& value) { }

    void swap(linked_list& rhs) { }
};

template <typename T>
void swap(linked_list<T>& lhs, linked_list<T>& rhs) { }

template <typename T>
bool operator<(const linked_list<T>& lhs, const linked_list<T>& rhs) { }

template <typename T>
bool operator>(const linked_list<T>& lhs, const linked_list<T>& rhs) { }

template <typename T>
bool operator==(const linked_list<T>& lhs, const linked_list<T>& rhs) { }

template <typename T>
bool operator!=(const linked_list<T>& lhs, const linked_list<T>& rhs) { }

I'd then start to fill in functions as I went - some of them are one-liners (is_empty and size), some of them take a bit more work. I'd pay the most attention to getting the destructor and copy constructor right, since these are probably the functions that would be scrutinized the most. Even if this API is slightly ambitious, and if some of the functions don't end up being implemented, at least it shows intent.

Finally, after the hour was up, I'd want to be ready to discuss what this implementation is lacking compared to say, the standard library list: from memory, Allocator template parameter, iterator + const_iterator, typedefs such as value_type, reference_type, functions such as remove_if, sort, unique and so on (although this is probably getting to in-depth - unless you've been working with the standard library a lot and know it very well, this is probably too much detail - but it might be worth it to know at least a little bit about std::list).

Given the incredibly limited time, I'd likely eschew unit testing. In fact, unless I had a compiler, I'd be almost positive there would be at least a few errors lurking around - syntax or otherwise. This wouldn't bother me - few people can sit down and bang out even a simplified container class without making a single mistake. To me, it is the high level overview that is important, along with those few key functions (destructor, copy constructor).


Tips to refactor code : very repetitive code

For the code repetition you can use

$(function () { // shorter form of document-ready
    $.each([dr1, dr2, dr3], function (index, data) {
        $('#drawing' + (index + 1)).lazylinepainter({
            svgData: data,
            strokeWidth: 1.2,
            strokeColor: '#65615a',
            onComplete: function () {}
        });
    });
});

For the second part, use boolean values as Josay suggested but place the fired flag inside a function that returns a closure. Each call to createPaintGuard establishes its own fired flag without having to package them all into an array or object.

function createPaintGuard(index) {
    var fired = false;
    return function () {
        if (!fired) {
            $('#drawing' + index).lazylinepainter('paint');
            fired = true;
        }
    };
}

var drawing1 = createPaintGuard(1);
var drawing2 = createPaintGuard(2);
var drawing3 = createPaintGuard(3);

Note that I would probably store the three drawingX variables into an array instead of individually-named variables, but I have no idea how they're being used in the wider context. The code here should be a drop-in replacement for yours.


Mouse input handler which exposes read-only mouse state data

You could represent the mouse state using a struct:

struct MouseSettings
{
    Signal btnLeft_, btnMiddle_, btnRight_, btnX1_, btnX2_;
    int32_t absX_, absY_, relX_, relY_, scrollX_, scrollY_;
}

class MouseInputHandler : public InputHandler
{
public:
    MouseInputHandler(ResourceContext &context)
        : mouseSettings(mouseSettings_)
    {}
    void handleEvent(SDL_Event &mouseEvent);
    void refresh();

    const MouseSettings& mouseSettings;

protected:
    MouseSettings mouseSettings_;
};

Or a property-like get-accessor method like:

const MouseSettings& getMouseSettings() { return mouseSettings_; }


Drawing colored circles using Ruby and Tk

You should define arrays with [] not Array.new

circs should be $circs in case you wrap your loop in some function.

Before drawing can be turned into this :

def before_drawing()
    temp_a = $point_B[0] ** 1 / $rate
    temp_b = $point_B[1] ** 1 / $rate
    $point_A = [temp_a, temp_b]
end

You should turn $i into a local variable for the loop. There is no need for it to be global.

Then replace the loop with upto.

0.upto(10) do |i|
    before_drawing()

    circs[i] = TkcOval.new(canvas, $point_A, $point_B)
    # As suggested using ternary operator
    # circs [i] [:fill] = i % 2 == 0 ? 'blue' : 'red'

    if i % 2 == 0 then
        circs[i][:fill] = 'blue'
    else
        circs[i][:fill] = 'red'
    end

    after_drawing()
end

You seem to use too many global variables. My advice would be to prefer local variables whenever you can (Like i in the loop). All your global variables can also be made local to the loop (or function in case you wrap the loop in some function).


Listing all the chars in a given UnicodeBlock

It is truly unfortunate that Character.UnicodeBlock doesn't have a min() and max().  In fact, the way it is implemented in OpenJDK is as a private static  blockStarts table, which is entirely unhelpful to you.

I don't have a better solution, but rather a complication.  The Java char type only covers the Basic Multilingual Plane.  To be pedantic, you would need to cover even larger codepoints, with Character.UnicodeBlock.of(int)!  (For example, Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B starts at U+20000, which cannot be encoded using a single char, and therefore iterating up to 216 would not find it.)

It appears that existing Unicode blocks have sizes that are multiples of 16, so you could take advantage of that instead of testing every single codepoint.

Code blocks are contiguous.  Therefore, a possible optimization is that once you have found a character that is in the desired block, if you then encounter a character that is not in the block, then you're done.


Swap a word in the DOM from an array of words

There is no way to remove the behavior. This is usually bad design.
Since there is no way to remove behavior, swapWords() as a function is unneeded: you will never call it twice. It would only make sense defining it as a function if it could be called on different elements.
The initial state of the cycle is undefined and/or inconsistent: since the first swap only occurs after 2s, until then the initial content of the span will be displayed (WEBDESIGNER). Then it will be swapped with... WEBDESIGNER. Either leave the span empty and explicitly call a swap round on initialisation, or push the initial contents of the span on top of the stack of words. Otherwise it's not a cycle, it's a "weird start, then a cycle".
if(i == words.length){ - ok, you defined words as const so this is safe. But it's a bad habit to develop to write code like this: if words was variable between rounds, as it got trimmed from, say, 6 items to 4, and i would be 5, the condition would not be triggered anymore, and also not checked before access. So it would just go on to infinity. The responsible way to write code is always update and bound-check any state vars in a synchronous matter, which means BEFORE using them (i.e. before swappingWord.textContent = words[i].toUpperCase();), not at the end of the round for the next async round. Also always use >=words.length not ==words.length, as a coding habit. Always test for valid/invalid condition, not edge condition. In case you decide later to make words list variable, the == condition will automatically introduce a bug. >= won't. The remarks of this point don't qualify as bad code (it works as long as you don't change initial assumptions), it's just bad style. Get rid of it before you get used to it :)


Take an array and return "n" elements, as evenly spaced as possible

Ding!!
I've got it!
So, I have been looking at this code for quite a while now, because I knew there had to be some ingenious way to do this. It seemed all to simple to need something of the opposite scale! And, after playing around, sure enough, I think I got it to it's best.
However! I'd hate to just give away the answer without a bit of some code critiquing beforehand. Shall we begin?...

I sure hope you didn't spend to long typing out those arrays. That'd would have been a bummer! Let's take advantage of a little resource, I like to call it the fill-numeric-array-o-matic. Switch that baby on, and bam, you get this beautiful babe:
$_5elements = range(1, 5);
$_10elements = range(1, 10);
$_14elements = range(1, 14);
$_40elements = range(1, 40);
$_140elements = range(1, 140);

Ain't she a beaut'?
Alright, next step! I see you countin' up the input array a couple times, good thing we know how to handle this! That's right, it needs to DRY out.
$array_length = count($array);

Feel free to replace all those nasty repetitions now!
After we've dried up that spill, let's knock off this arrow nonsense and whip up some clean lookin' code!
Watch ladies and gentlemen as we turn this snippet:

if ($array) {
    $array_length = count($array);
    if ($array_length > $target_array_length) {
        ...
        foreach (...) {
            if (...) {
                $return[] = $value;
            }
        }
        $return = array_reverse($return);
    } else {
        $return = $array;
    }
    return $return;
}
return false;

into this gorgeous girl piece of code!
$array_length = count($array);

if ($array_length == 0) {
    return false;
}

if ($array_length <= $target_array_length) {
    return $array;
}

*insert top secret algorithm here*

return array_reverse($output);

I hope we all got to see this amazing transformation, the original having layers and layers, ifs and elses all over! To now, a clean and concise workflow...
Up next! The end is near, I promise! Before though, let's have a look at these formats and styles. Your code's fashion is really last year... Everyone's shopping at using 2014 standards.
Seriously though, applying and sticking to a style will benefit everyone. I highly recommend something such as PHP-FIG or the Zend Standards.
It's mostly just your naming conventions in this code that are goofy, and I have made some changes in my code below.
Last but not least, the algorithm! No offense, but your loop plus the conditions made everything so hard to follow. Debugging it to figure out what it did what gave me a headache. Good thing I have aspirin.
I found your choice of krsort() unnecessary. Well, I've been able to completely remove this!
Now, here's a list of requirements that must be achieved when we do the work:

The amount of numbers returned MUST be equal to the number specified.
The interval between numbers MUST be as even as possible throughout the list.
The highest integer has priority in the output over the lowest numbers. (Assumed this one based on your output)

I'm going to use a funky lookin' for loop to go through the array. It's going to look confusing at parts, but I'll do my best to make it worse clear things up!
$output = [];
$ratio = round($array_length / $target_array_length);
for ($index = $array_length - 1; count($output) < $target_array_length; $index -= $ratio) {
    $output[] = $array[$index];
}

return array_reverse($output);

How ya like them apples! Alrighty, let's see what I've done here:

Make a new $output array to hold our output.
Find the $ratio at which we should go through the array at. This will cross off the evenly spaced requirement!
We're going to set $index to one less than the original array's length. We do this so we can reference the highest index and not have an out of bounds error.
Throughout the loop, check to make sure we have less in our output array than we want. If we have the right amount, break the loop. Cross off Req. #1!
For each iteration, reduced our index by that ratio we came up with earlier.

Inside the loop, add to our output the value from $array  with the index that has been decreasing in the loop.
Reverse it to get the desired direction, and there ya have it!
Here's the full code that I came up with. Naming and all! I call this one: Make-sorted-and-spread-out-array-inator.
$arrayLength5 = range(1, 5);
$arrayLength10 = range(1, 10);
$arrayLength14 = range(1, 14);
$arrayLength40 = range(1, 40);
$arrayLength140 = range(1, 140);

function spreadOutArray(array $array, $targetOutputLength = 10) {

    $originalArrayLength = count($array);

    if ($originalArrayLength == 0) {
        return false;
    }

    if ($originalArrayLength <= $targetOutputLength) {
        return $array;
    }

    $output = [];
    $interval = round($originalArrayLength / $targetOutputLength);
    for ($index = $originalArrayLength - 1; count($output) < $targetOutputLength; $index -= $interval) {
        $output[] = $array[$index];
    }

    return array_reverse($output);
}

I hope the galaxy is better now that this question has one hell of an answer. Live long and prosper. Writing these types of answers will help in your quest to living long and prospering much.
I'd be happy to clarify anything.


The easiest and most clean way would be to use decimal.TryParse() like so

private decimal ConvertStringToDecimal(string decimalString, decimal defaultReturnValue)
{
    decimal result;
    if (decimal.TryParse(decimalString.Trim(), out result))
    {
        return result;
    }

    return defaultReturnValue;
}

Using exceptions to control the returned value isn't a good way, especially if there are better methods to use.

Your indentation is off but I assume that thats a posting issue.


class Dictionary
    attr_accessor :entries

Indentation in Ruby is two spaces, not four. You have that correct in your specs, but not in the application code.

Also, you create here a pair of methods, entries= which you never use anywhere, and entries, which you overwrite further down, anyway. Either get rid of this line, or (preferred!) actually make use of those methods.

    def initialize
        @hash={}

There should be a space on both sides of the = sign. This applies to operators in general.

[Note: there are some style guides that advocate not using spaces around the = sign for optional parameters with default arguments, but a) this is not universally accepted and b) not the case here anyway.]

    end

    def add(a)

This should probably be called << instead.

[Note: I realize, this is prescribed by the spec. IMO, the spec should be changed.]

        if a.class == Hash

You should never compare the class of an object like this. Ideally, you should use runtime ad-hoc polymorphism. If that isn't possible, at least use Object#is_a?, Object#kind_of?, or Module#===.

            a.each_pair { |k, v|
                @hash[k]=v
            }

There are two different camps when it comes to block styles: one camp says to use {/} for one-liners and do/end for multiple lines. The other camp says to use {/} for "functional" blocks and do/end for side-effecting blocks.

Regardless of which camp you follow: your block has three lines and side-effects, so it should use the keyword form.

        else
           @hash[a]=nil
       end
    end

There should be an empty between the two method definitions.

    def entries
        @hash
    end

    def keywords
        @hash.keys.sort
    end
    def include?(k)
        @hash.key?(k)
    end

    def printable

This should be called to_s. to_s is the standard name for a method that converts an object into a textual representation. It is used automatically by methods such as Array#join or Kernel#puts.

[Note: I realize, this is prescribed by the spec. IMO, the spec should be changed.]

        str=[]
        key=@hash.keys.sort
        key.each do |el|
            @hash.each_pair do |k,v|
                if k==el
                    str << "[#{k}] \"#{v}\""

You could save yourself some hassle here by using something else than " to delimit the string.

This pattern, where you initialize an accumulator to an "empty" value and then iterate over a collection while appending to the accumulator at every iteration, is called a Catamorphism, fold, or reduce. In Ruby, it is known as inject.

However, in this case, it can also be done even simpler, with a map.

                end
            end
        end
        return str.join("\n")

The return is superfluous here, the return value of a method is the value of the last expression which is evaluated inside the method body.

    end

    def find(str)
        if str.class == Hash
            str.each_pair { |k, v|
               return (@hash.select { |k,v| k.include?(k)})
            }

There is nothing in the spec about passing Hashes to find. In fact, you named your parameter str clearly indicating that you expect it to be a String. Then why even bother checking for Hashes?

        elsif str.class == String
            return (@hash.select {|k,v| k.include?(str)})

Here you check whether the key includes the search string. However, from the documentation in the spec, it appears that the search string should be a prefix of the key. Unfortunately, there is actually no test in the spec to test for that distinction.

        end
    end
end

This is what it would look like with those suggestions applied:

class Dictionary
  attr_reader :entries

  def initialize
    self.entries = {}
  end

  def add(a)
    case a
    when Hash then entries.merge!(a)
    else           entries[a] = nil
    end
  end

  def keywords
    entries.keys.sort
  end

  def include?(k)
    entries.key?(k)
  end

  def printable
    entries.
      sort.
      map {|k, v| ["[#{k}]", unless v.nil? then %Q["#{v}"] end] }.
      map(&:compact).
      map {|kvp| kvp.join(' ') }.
      join("\n")
  end

  def find(key)
    entries.select {|k, v| k.start_with?(key) }
  end

  private

  attr_writer :entries
end


Accuracy

Floating-point approximations are not an acceptable substitute for integer arithmetic!  Otherwise, you end up with mistakes, like Homer's bogus counterexample of Fermat's Last Theorem.

How does that apply to your code?  Consider isPower(2147483647).  Your code yields 1, because it thinks that 463412 ≈ 2147483647.  In fact, 463412 = 2147488281, and the correct answer is "false", since 2147483647 is prime.

Filtering a number through a double → String → double round-trip conversion is especially egregious.

Naming

Try to choose variable names that are consistent with the nomenclature in the challenge.  Your variable is really P; your i corresponds to A; your A should be named something else altogether — perhaps n.

Suggested solution

Count the number of times each prime factor of n occurs.  You need to be able to segregate those factors into equal groups, with no lone factors left over.

import java.util.PrimitiveIterator;
import java.util.stream.IntStream;

public class Solution {
    /**
     * Calculates the GCD of two numbers using the Euclidean Algorithm.
     */
    private static int gcd(int a, int b) {
        while (b != 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }

    public boolean isPower(int n) {
        PrimitiveIterator.OfInt factors =
            IntStream.concat(IntStream.of(2), IntStream.iterate(3, i -> i + 2))
                     .iterator();

        // Count the number of times each prime factor occurs
        IntStream.Builder exponents = IntStream.builder();
        int f, e;
        do {
            f = factors.nextInt();
            for (e = 0; n % f == 0; e++) {
                n /= f;
            }
            if (e > 0) {
                exponents.add(e);
            }
        } while (f < n);

        // Try to segregate the factors into equal groups with no loners.
        // If there is no GCD, then n was 1, so a=1, p=2 would work.
        int p = exponents.build().reduce(Solution::gcd).orElse(2);
        return p > 1;
    }
}


K&R Exercise 5-15: sorting with extra options

I'd use a typedef for a pointer to your compare functions:

typedef int (*cmpfnc)(void *,void *);

This simplifies things and eliminates the ugly cast used in main's call to qsort1

I'd remove the & from &strcmp et. al. It is less idiomatic than strcmp. Both say "I want the address of ...". This allows the address of a function and a function pointer of the same type to be used interchangeably syntactically.

That is, you can say:

typedef int (*cmpfnc)(void *,void *);

cmpfnc myptr;

myptr = (cmpfnc) strcmp;

strcmp(x,y);
myptr(x,y);

And, they're all interchangeable. Also, note that (*myptr)(x,y) is simplified.

If you compile with [more] warning (e.g. -Wall), setting compareFunctionPointers needs a cast for strcmp. Using strcmp directly here is a slight blemish (because its signature uses const char * instead of void *, but it works in practice with the cast.

You could wrap strcmp with a wrapper function: int mystrcmp(void *left,void *right) { return strcmp(left,right); } as an alternative to using the cast. This would allow the compiler to do more type checking. But, using strcmp directly would probably run faster.

For most of your functions, you're breaking type safety of the arguments, so you have to be careful when doing that to be sure that things match up when the program runs.

Side note: You use sortDecreasing in main, but rename it in qsort1. Note that the the name in main is much more descriptive of its meaning. Also, you could replace the value with 1 or -1 and simplify qsort1 with a multiply (see my cleaned up code below).

Here is your code annotated with what I think could be cleaned up a bit [Note that it's based on the code in your original post, so I had to guess about some missing functions]:

#include <string.h>

#define MAX_NO_OF_LINES     100

// NOTE/BUG: this should be a typedef
int (*compareFunctionPointers[3]) (void *, void *);

void
swap(void **v,int left,int right)
{
    void *tmp;

    tmp = v[left];
    v[left] = v[right];
    v[right] = tmp;
}

int
numcmp(void *left,void *right)
{
    return *(int *) right - *(int *) left;
}

// NOTE/BUG: this should use a typedef
void
qsort1(void *v[], int left, int right, int (*comp) (void *, void *), int increesingOrDecresing)
{
    int last,
     compare;

    // Base case
    if (left >= right) {
        return;
    }

    swap(v, left, (right + left) / 2);
    last = left;
    for (int i = left + 1; i <= right; i++) {
        compare = (increesingOrDecresing) ? -(*comp) (v[i], v[left])
            : (*comp) (v[i], v[left]);
        if (compare < 0)
            swap(v, ++last, i);
    }
    swap(v, last, left);
    qsort1(v, left, last - 1, comp, increesingOrDecresing);
    qsort1(v, last + 1, right, comp, increesingOrDecresing);
}

enum {
    COMPARE_DEFAULT,
    COMPARE_FOLDED,
    COMPARE_NUMERICLY
};

char *pointersToLines[MAX_NO_OF_LINES];

int
main(int argc, char *argv[])
{

    // Store pointers to the diffrent types of
    // compare functions in a array of
    // function pointers.
    // NOTE/BUG: these require a cast
    // NOTE/BUG: leave off the "&" as it is more idiomatic
    compareFunctionPointers[COMPARE_DEFAULT] = &strcmp;
#if 0
    compareFunctionPointers[COMPARE_FOLDED] = &strcmpFold;
#else
    compareFunctionPointers[COMPARE_FOLDED] = &strcasecmp;
#endif
    compareFunctionPointers[COMPARE_NUMERICLY] = &numcmp;

    int numberOfLines;
    int sortDecreasing = 0;             // 1 if the input is to be sorted in a decreasing order
    int compareFunction = COMPARE_DEFAULT;  // Index for the compare-function

    // Parse the command line arguments
    if (argc > 1) {
        for (int i = 1; *(argv + i); i++) {
            char *c = *(argv + i);

            if (strcmp(c, "-n") == 0)
                compareFunction = COMPARE_NUMERICLY;
            if (strcmp(c, "-r") == 0)
                sortDecreasing = 1;
            if (strcmp(c, "-f"))
                compareFunction = COMPARE_FOLDED;

        }
    }

#if 0
    if ((numberOfLines = readLines(pointersToLines, MAX_NO_OF_LINES)) >= 0) {
#endif

    // NOTE/BUG: too much casting, particularly on compareFunctionPointers
        qsort1((void **) pointersToLines, 0, numberOfLines - 1, (int (*)(void *, void *)) compareFunctionPointers[compareFunction], sortDecreasing);

#if 0
        writeLines(pointersToLines, numberOfLines);
    }
#endif

    return 0;
}

Here is a more cleaned up version incorporating the ideas I've expressed above:

#include <string.h>

#define MAX_NO_OF_LINES     100

typedef int (*cmpfnc)(void *,void *);

cmpfnc compareFunctionPointers[3];

void
swap(void **v,int left,int right)
{
    void *tmp;

    tmp = v[left];
    v[left] = v[right];
    v[right] = tmp;
}

int
numcmp(void *left,void *right)
{
    return *(int *) right - *(int *) left;
}

void
qsort1(void *v[], int left, int right, cmpfnc comp, int sortdir)
{
    int last,
     compare;

    // Base case
    if (left >= right) {
        return;
    }

    swap(v, left, (right + left) / 2);
    last = left;
    for (int i = left + 1; i <= right; i++) {
        compare = sortdir * comp(v[i], v[left]);
        if (compare < 0)
            swap(v, ++last, i);
    }
    swap(v, last, left);
    qsort1(v, left, last - 1, comp, sortdir);
    qsort1(v, last + 1, right, comp, sortdir);
}

enum {
    COMPARE_DEFAULT,
    COMPARE_FOLDED,
    COMPARE_NUMERICLY
};

char *pointersToLines[MAX_NO_OF_LINES];

int
main(int argc, char *argv[])
{

    // Store pointers to the diffrent types of
    // compare functions in a array of
    // function pointers.
    compareFunctionPointers[COMPARE_DEFAULT] = (cmpfnc) strcmp;
    compareFunctionPointers[COMPARE_FOLDED] = (cmpfnc) strcasecmp;
    compareFunctionPointers[COMPARE_NUMERICLY] = numcmp;

    int numberOfLines;
    int sortDecreasing = 1;             // 1=increasing, -1=decreasing
    int compareFunction = COMPARE_DEFAULT;  // Index for the compare-function

    // Parse the command line arguments
    if (argc > 1) {
        for (int i = 1; *(argv + i); i++) {
            char *c = *(argv + i);

            if (strcmp(c, "-n") == 0)
                compareFunction = COMPARE_NUMERICLY;
            if (strcmp(c, "-r") == 0)
                sortDecreasing = -1;
            if (strcmp(c, "-f"))
                compareFunction = COMPARE_FOLDED;

        }
    }

#if 0
    if ((numberOfLines = readLines(pointersToLines, MAX_NO_OF_LINES)) >= 0) {
#endif

    // NOTE/BUG: too much casting, particularly on compareFunctionPointers
        qsort1((void **) pointersToLines, 0, numberOfLines - 1,
        compareFunctionPointers[compareFunction], sortDecreasing);

#if 0
        writeLines(pointersToLines, numberOfLines);
    }
#endif

    return 0;
}


Simple command line tool to query database. Need code optimized

Well, the most important optimization you can make to this code is to improve your SQL query. You are currently pulling down the entire db but only care about one row; you're doing half your query on the client side. Use SQL, not Java, for selecting data from the db! Consider the following version of getDeviceByName:

private static Map<String, Object> getDeviceByName(String name) throws SQLException {
    DriverManager.registerDriver(new com.mysql.jbdc.Driver());
    Connection connection = DriverManager.getConnection(
        "jdbc:mysql://127.0.0.1:3306/test", "test", "test");
    PreparedStatement statement = connection.prepareStatement(
        "SELECT id, mac, name FROM device WHERE name = ? LIMIT 1");
    statement.setString(1, name);
    ResultSet rs = statement.executeQuery();
    try {
        if (!rs.next()) {
            return null;
        }
        return readRowIntoMap(rs);
    } finally {
        rs.close();
    }
}

private Map<String, Object> readRowIntoMap(ResultSet rs) throws SQLException {
    ResultSetMetaData metadata = rs.getMetaData();
    Map<String, Object> row = new LinkedHashMap<>();
    for (int i = 1; i <= metadata.getColumnCount(); i++) {
        row.put(metadata.getColumnName(i), rs.getObject(i));
    }
    return row;
}


Faster searching

Suppose you have an array filled with either 1 and 0, and you are trying to search for a consecutive sequence of twenty 1's in a row.  The way you are doing it is like this:

111111111111111100001111111110111011111111
^               ^
|...............|
start here      end here  length = 15, not long enough, so move on

Next iteration:

111111111111111100001111111110111011111111
 ^              ^
 |..............|
 start here     end here  length = 14, not long enough, so move on

Next iteration:

111111111111111100001111111110111011111111
  ^             ^
  |.............|
  start here    end here  length = 13, not long enough, so move on

As you can imagine, the above algorithm is not very efficient because you are wasting time looking at the same array values over and over again.  The above can take up to \$O(M*N)\$ time, where \$M\$ is the length of the string and \$N\$ is the length of the sequence you are searching for.

Instead of restarting your search from the next index, you should be restarting your search from just past the zero you found:

111111111111111100001111111110111011111111
^               ^
|...............|
start here      end here  length = 15, not long enough, so move on

Next iteration:

111111111111111100001111111110111011111111
                 ^
                 |
                 Restart here, not back there

By doing this, the search now only takes \$O(M)\$ time.  You could do even better by mimicking the Boyer Moore string search algorithm and skipping to the end and searching backwards, like this:

111111111111111101111111111110111011111111
^
|
start here

111111111111111101111111111110111011111111
                   ^
                   |
                   jump 19 spots ahead and search backwards

111111111111111101111111111110111011111111
                ^
                |
                Found a zero here

111111111111111101111111111110111011111111
                 ^
                 |
                 Restart here

This is still an \$O(M)\$ algorithm in the worst case, but it can be as fast as \$O(M/N)\$ in the best case (an array filled with all 0s).

Loop rearrangement

The way you have set up your loops does not lend itself to doing the faster searching methods.  You will need to rearrange your loops in order to be able to restart your searches properly.  I suggest you move your x loop from being the innermost loop to being the outermost loop.  Then you may find that the two other loops collapse into a single search loop.


A correction. I have removed the use of jQuery in the correction. The main issue was that you don't set anywhere a map center and a zoom. I've changed the behaviour by zooming the map to GeoJSON extent (e.g map.fitBounds(jsonLayer.getBounds());)
You could also made the change by setting a map center and a zoom like described in this link to official doc.
function buildCompanyMap() {

  document.getElementById('company_map').innerHTML = "

";

  console.log("script #1: %o", document.getElementById('company_map'));
  console.log("script #2: %o", document.getElementById('map'));

  var map = new L.Map('map', {
      dragging: false,
      tap: false,
      scrollWheelZoom: false
    });

  var osmUrl = 'https://{s}.tile.osm.org/{z}/{x}/{y}.png',
      osmAttribution = 'Map data © OpenStreetMap contributors,' +
                      ' CC-BY-SA',
      osmLayer = new L.TileLayer(osmUrl, {maxZoom: 18, attribution: osmAttribution});

  map.addLayer(osmLayer);

  console.log("script #5: %o", data.responseJSON);

  var geojsonMarkerOptions = {
      radius: 8,
      fillColor: "#ff7800",
      color: "#000",
      weight: 1,
      opacity: 1,
      fillOpacity: 0.8
  };

  fetch('#companies/company.json', {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    })
    .then(response => response.json())
    .then (json => {
      var jsonLayer = L.geoJSON(json, {
        pointToLayer: function (feature, latlng) {
            return L.circleMarker(latlng, geojsonMarkerOptions);
        }
      })
      jsonLayer.addTo(map);
      map.fitBounds(jsonLayer.getBounds());
    })
    .catch(function(error) {
      console.log('Error on fetch operation: ' + error.message);
    });

};

document.addEventListener("turbolinks:load", function() {
  if (document.getElementById('company_map') == null) {
    //console.log('true')
  }
  else {
    buildCompanyMap();
  }
});


More concise way to sum elements of columns in R

Assuming your data are numeric and your columns are ordered by D-#, the following approaches should work:

Using apply:

errorarray$Q1 <- apply(errorarray[, c(3, 6, 7, 14:16)], 1, sum) # using col indices
errorarray$Q1 <- apply(errorarray[c("D-03", "D-06", "D-07", "D-15", "D-16")], 1, sum) # using column names

Using rowSums:

errorarray$Q1 <- rowSums(errorarray[, c(3, 6, 7, 14:16)]) # using indices
errorarray$Q1 <- rowSums(errorarray[c("D-03", "D-06", "D-07", "D-15", "D-16")]) # using column names

Note you can use ":" to denote the start and end of a number of consecutive columns.


Checking whether if start and end has equal number of non-zero integers and contains 3 or more 0 in the center

You can determine the correct answer in a single pass, by working your way from the middle of the array outward, or from the ends of the array inward. Let's get started.

Although the problem description states to return 1 if the array is hollow  and 0 if it is not, such signature would make no sense in Java. It's only natural, and strongly recommended to use proper boolean true and false, respectively.

To work outward from the center, let's track left and right indexes.
If the array has odd number of elements,
left and right can both point to the middle element.
Otherwise the array has two central elements,
let's make left and right point at those.

int mid = nums.length / 2;
int left, right;
if (nums.length % 2 != 0) {
    left = right = mid;
} else {
    left = mid - 1;
    right = mid;
}

Now, let's start moving the left and right indexes outward, as long as both nums[left] and nums[right] are 0, and left > 0.

while (left > 0 && nums[left] == 0 && nums[right] == 0) {
    left--;
    right++;
}

The loop ends either when left reaches the second position of the array,
or when nums[left] or nums[right] (or both) are not zero.
If left and right were not moved enough, that is,
we haven't moved over enough zeros, then the array is not hollow and we can return.

if (right - left < 4) {
    return false;
}

Finally, we need to verify that the rest of the elements are all non-zero.
We can do that by continuing to move outward, and aborting if any of the values is 0.

while (left >= 0) {
    if (nums[left] == 0 || nums[right] == 0) {
        return false;
    }
    left--;
    right++;
}

When the loop completes without aborting, we know the array is hollow.

The complete solution, with some more test cases to verify it:

boolean isHollow(int... nums) {
    int mid = nums.length / 2;
    int left, right;
    if (nums.length % 2 == 0) {
        left = mid - 1;
        right = mid;
    } else {
        left = right = mid;
    }

    while (left > 0 && nums[left] == 0 && nums[right] == 0) {
        left--;
        right++;
    }

    if (right - left < 4) {
        return false;
    }

    while (left >= 0) {
        if (nums[left] == 0 || nums[right] == 0) {
            return false;
        }
        left--;
        right++;
    }

    return true;
}

@Test
public void verify_isHollow() {
    assertThat(isHollow(1, 2, 4, 0, 0, 0, 3, 4, 5)).isTrue();
    assertThat(isHollow(1, 2, 4, 0, 0, 0, 1, 0, 3, 4, 5)).isFalse();
    assertThat(isHollow(1, 2, 0, 0, 0, 3, 4, 5)).isFalse();
    assertThat(isHollow(1, 2, 4, 9, 0, 0, 0, 3, 4, 5)).isFalse();
    assertThat(isHollow(1, 2, 0, 0, 3, 4)).isFalse();
    assertThat(isHollow(1, 2, 0, 0, 0, 0, 3, 4)).isTrue();
    assertThat(isHollow(1, 0, 0, 0, 3)).isTrue();
    assertThat(isHollow(1, 2, 0, 0, 0, 0, 3, 4, 5)).isFalse();
    assertThat(isHollow(1, 2, 1, 0, 0, 0, 0, 3, 4)).isFalse();
    assertThat(isHollow(0, 0, 0)).isFalse();
    assertThat(isHollow(0, 0, 0, 0, 0)).isFalse();
    assertThat(isHollow(0, 0, 0, 0, 0, 1)).isFalse();
    assertThat(isHollow(1, 0, 0, 0, 0, 0)).isFalse();
    assertThat(isHollow(1, 0, 0, 0, 0, 0, 2)).isTrue();
}


I see a lot of little things slowing you down, but I don't know what your chart_centroids and save_image functions do, so I have no idea if they are part of the problem or not.

Let's look at one of your two frequently-called functions:

def choose_points_for_centroids(x, y):
    for i in range(len(list_centroids)):
        list_centroids[i]["points_x"].clear()
        list_centroids[i]["points_y"].clear()

    distances = []
    for j in range(len(x)):
        for i in range(len(list_centroids)):
            dist = distance(x[j], y[j], list_centroids[i]["x"], list_centroids[i]["y"])
            distances.append(dist)

        minim = min(float(s) for s in distances)
        index = distances.index(minim)
        list_centroids[index]["points_x"].append(x[j])
        list_centroids[index]["points_y"].append(y[j])
        distances.clear()

In the first paragraph, you "clear" a bunch of data. But I'm not sure why you have your centroids structured this way. Every time you access something, there's an index, a key lookup, and maybe another index. That's way too much work for getting at something you'll be addressing frequently!

In fact, the whole idea of accessing list_centroids[i]["x"] and list_centroids[i]["y"] is kind of silly. I don't see any value to separating the x and y coordinates, here.

On the other hand, if you were to combine your x and y coordinates into a tuple, you would have a constant object that can be hashed. And hashed items can be stored in a dictionary.

Centroid = { ... }

for c in Centroid:
    Centroid[c] = []    # Reset list of points to empty

In the next section, you iterate over all your points (here you go again, segregating ordinates from abscissas!) computing a distance metric. You store the distances in a list.

After creating the distances list, you then find the min value.

After finding the min value, you then try to map back to the index of that value.

After finding the index, you use that to figure out what centroid was closest to the point, and tie the point to the centroid.

You overlook the min function's key= argument. The key is a function (or lambda-expression) that returns a value. Given the input, the min function determines what to compare by calling the key function. If the key function is not provided, then a simple identity function ( f(x) = x ) is used.

In your case, you can replace all that code by judicious use of a lambda-expression:

# This should be your global Point store, not x[] and y[]
Points = [ (_x, _y) for _x, _y in zip(x,y) ]

for p in Points:
    x,y = p
    nearoid = min(Centroid, key=lambda c: distance(x,c[0],y,c[1]))
    Centroid[nearoid].append(p)

And if you recode your distance function to take tuples, you don't need to do even that much work:

for p in Points:
    nearoid = min(Centroid, key=lambda c: distance(p, c))
    Centroid[nearoid].append(p)

This does three things for you. First, it eliminates a lot of bytecode. And that means it eliminates a lot of things that the computer was doing, which should save you time.

Second, it converts some bytecode into builtins. Using the builtins as much as possible means that your code might be running in C, instead of bytecode. This makes for better performance.

Third, it eliminates extra data structures. Which eliminates allocation, deallocation, garbage collection, data structure maintenance, etc. All that storage translates into performance, either directly (thrashing) or indirectly (code).

Now, speaking of your distance function, I see you are calling int a bunch of times. But the inputs are, if I understand correctly, already integers. So those are a bunch of name lookups, and function calls, that are entirely redundant.

Try something like this, again using the points-as-tuples approach:

def distance(a, b, sqrt=math.sqrt):
    """Return the distance between (x,y) tuples a and b"""
    return sqrt( (a[0] - b[0])**2 + (a[1] - b[1])**2)

(Putting the lookup of math.sqrt into the constants table is a bit of a cheat. But anything for speed, eh?)


Your code works, but its quality leaves some room for improvement. It should be simplified by refactoring.
Here are some suggestions:

Naming

Even if it is only an exercise, utmost care should be applied when choosing names to make sure they are descriptive and clear, but also to comply with coding conventions:

Consider calling your class NonReentrantLock instead of MyLock.
Methods should be camel-case, starting with a lower-case character, so Lock() should be lock() and Unlock() should be unlock().
Only constants should be upper-case, so TAG should be made a constant. But TAG can mean anything. The solution is to refactor your code (as shown below) such that TAG is only used once and is no longer needed as a class variable.

Constants

TAG is not a useful constant because it leads to lots of System.out.println calls which you want to avoid. All your logging should happen in a single place, not be spread out over your class.
However, you are using the magic value of -1 to show that nobody owns the lock at the moment. You should introduce a constant NOBODY and use that to set owner:

private static final long NOBODY = -1;
private long owner = NOBODY;

Redundancy

Tracking the same state twice

Look carefully at your instance variables owner and isLocked. Track their values during runtime with the debugger, and you will see: if owner == -1 then isLocked == false, but if owner != -1 then isLocked == true. In other words, you are using two variable to track the same piece of state.

You should remove isLocked and replace it it with the following method:

private synchronized boolean isLocked() {
    return owner != NOBODY;
}

Doing the same string concatenations multiple times

You have used System.out.println throughout your code, always passing TAG, a message, and a thread id. You can extract this functionality into a new method:

private void log(String message, long threadId) {
    System.out.println(String.format("MyLock: %s %s", message, threadId));
}

That way, System.out.println is only called in a single place and can easily be disabled or replaced with a real logger. For instance, this:

System.out.println(TAG+"Lock Acquired: Owner = " + owner);

can become this:

log("lock acquired, owner =", owner);

Miscellaneous redundancies

If you throw an exception, inside an if-structure, you the else branch is redundant, so code like

if (condition) {
    throw new IllegalStateException(...);
} else {
    doSomethingElse();
}

can become

if (condition) {
    throw new IllegalStateException(...);
}
doSomethingElse();

You have code duplication when checking if the current thread is the owner of the lock. Refactor out this method instead:

private boolean ownerIsCurrentThread() {
    return owner == Thread.currentThread().getId();
}

You should extract argument validation into a separate method:

private void throwIf(boolean condition, String message) throws IllegalStateException {
    if (condition) {
        throw new IllegalStateException(message);
    }
}

which will allow you to replace your argument validation if-statements with code like

throwIf(ownerIsCurrentThread(), "the lock has already been acqired");

Error messages

At the beginning of unlock(), you throw an IllegalStateException with the same message for two completely different reasons. That's not very helpful for debugging. Instead, check them separately:

public synchronized void unlock() throws IllegalStateException {
    throwIf(!isLocked(), "only a locked lock can be unlocked");
    throwIf(!ownerIsCurrentThread(), "only owner can unlock the lock");

End Result

public class NonReentrantLock {
    private static final long NOBODY = -1;
    private long owner = NOBODY;

    public synchronized void lock() throws InterruptedException, IllegalStateException {
        throwIf(ownerIsCurrentThread(), "the lock has already been acqired");
        long threadId = Thread.currentThread().getId();
        while (isLocked()) {
            log("waiting for lock on thread", threadId);
            wait();
        }
        owner = threadId;
        log("lock acquired, owner =", owner);
    }

    public synchronized void unlock() throws IllegalStateException {
        throwIf(!isLocked(), "only a locked lock can be unlocked");
        throwIf(!ownerIsCurrentThread(), "only owner can unlock the lock");
        log("unlocking, owner =", owner);
        owner = NOBODY;
        notify();
    }

    private synchronized boolean isLocked() {
        return owner != NOBODY;
    }

    private boolean ownerIsCurrentThread() {
        return owner == Thread.currentThread().getId();
    }

    private void throwIf(boolean condition, String message) throws IllegalStateException {
        if (condition) {
            throw new IllegalStateException(message);
        }
    }

    private void log(String message, long threadId) {
        System.out.println(String.format("MyLock: %s %s", message, threadId));
    }
}


Print largest/smallest no (even, odd) from user defined list of given size

Your variables are long, without needing to be.
You don't have to define largest_even, amongst others, it'd be simpler to just return the tuple.
If you're targeting 3.4+, and I don't see why you wouldn't, you can use the default keyword. "New in version 3.4: The default keyword-only argument."

Leaving you simply with:

def largest_and_smallest(numbers):
    even = [n for n in numbers if (n % 2) == 0]
    odd  = [n for n in numbers if (n % 2) != 0]
    return (
        max(numbers, default=None),
        min(numbers, default=None),
        max(even, default=None),
        min(even, default=None),
        max(odd, default=None),
        min(odd, default=None)
    )

If you don't like the verbosity of max, you could use functools.partial to set default twice.

from functools import partial

def largest_and_smallest(numbers):
    min_ = partial(min, default=None)
    max_ = partial(max, default=None)
    even = [n for n in numbers if (n % 2) == 0]
    odd  = [n for n in numbers if (n % 2) != 0]
    return (
        max_(numbers),
        min_(numbers),
        max_(even),
        min_(even),
        max_(odd),
        min_(odd)
    )


Two possible sources of errors:

If you forget to use (or don't want to apply) the virtual modifier, it will no longer be a shallow copy (because virtual is typically used for navigation properties).
It relies on unmapping properties by attributes. If at any time in the future you start using the fluent API for that purpose you'll change behavior in an unexpected place.

You evidently want to clone mapped and scalar properties only. Your approach works (if you remember the error sources), but I'd prefer to use a method provided by EF itself:

MobileOrderSettings settings = context.MobileOrderSettings.FirstOrDefault();
var shallowCopy = (MobileOrderSettings)context.Entry(settings)
                                              .CurrentValues.ToObject()

As you see, the CurrentValues property of an entry in EF's change tracker is used to build a clone, which is always a shallow clone of mapped properties.

Of course, you can't apply this method inside an entity class, because it requires a context to which the entity object is attached. But is that bad? I'd say no, because this clone method has a very specific purpose which is tied to an EF environment. To me it would break the persistence ignorance principle if a class would require knowledge of the data layer implementation for which it clones itself.


Refactoring class methods to helper class?

public abstract class MWRequest
{
    public static string WebServiceURL = "url";
    protected XmlDocument xmlDoc = new XmlDocument();

    protected MWRequest()
    {
        xmlDoc.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?><request/>");
    }

Class name

I get the Request part of the class name, but MW could be just about anything, and itsn't descriptive. I suggest you rename the class, and drop this abbreviation.

Static field

Anything public static in an abstract class, smells. You're not showing how it's used, but being static, the value stops being an instance-level value and becomes a type-level value, which means all instances of that class will have the same WebServiceURL (which should be named WebServiceUrl - PascalCase FTW!), which just doesn't sound right, especially in a base/abstract class.

Public fields

Don't do that, you're breaking encapsulation. Derived classes can do anything they want with xmlDoc, and bypass everything you've coded as protected methods.

Encapsulation enables abstraction. Your base class could encapsulate an XmlDocument and provide an abstraction layer that hides this implementation detail to its clients and derived types. If you need to expose the XML, then override ToString and return the encapsulated XML instead of exposing the whole xmlDoc, or expose a Xml property that does that.

public XmlDocument XmlDocument
{
    get { return xmlDoc; }
}

If a derived type wants to set the XmlDocument reference, the parameterless constructor will still run and call LoadXml with the hard-coded string there. I think you should have a protected constructor that just takes an XmlDocument from the derived type, and chain the constructor calls:

protected MWRequest()
    : this(new XmlDocument())
{
    _xmlDoc.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?><request/>");
}

protected MWRequest(XmlDocument xmlDoc)
{
    _xmlDoc = xmlDoc;
}

private readonly XmlDocument _xmlDoc;
public XmlDocument xmlDocument { get { return _xmlDoc; } }

This way a derived type has only 1 way of setting the XmlDocument reference, through the constructor.

A word about LoadElement and LoadExtraElement: they're both badly named, protected and useless - a derived type can access the XmlDocument from the XmlDocument property, and do everything it needs to do with it, including destroying/replacing the entire DOM.

Either make them protected virtual and drop the XmlDocument property (and add any members to expose whatever other types need out of it), or keep the XmlDocument property and drop the helper methods - at the end of the day, it's a design decision you need to make.

If you decide to keep them, I'd suggest to change the signatures a bit:

protected virtual XmlElement CreateElement(string name, string innerText)
{
    // ...
}

protected virtual XmlElement CreateExtraElement(string name, string value)
{
    // ...
}

By making CreateElement a function that returns the XmlElement it's creating (instead of adding it itself to xmlDoc), you can delete some of the code from CreateExtraElement and call CreateElement from within CreateExtraElement

var element = CreateElement("extra", value);
var attribute = _xmlDoc.CreateAttribute("name"); // "attrName" is a bad name
attribute.Value = name;
element.Attributes.Append(attribute);
return element;

The client code is a derived class, so it can do this:

var element = CreateExtraElement("foo", "bar");
XmlDocument.DocumentElement.AppendChild(element);

And if the base class implementation for CreateExtraElement doesn't suit that class' needs, it can always override it, because it's virtual.

LINQ to XML

I'd suggest you use the System.Xml.Linq namespace and its XDocument and XNode, XElement, and XAttribute classes, instead of the older XmlDocument & friends classes from System.Xml.


Add following header for *nix users

#!/usr/bin/env python
# ~*~ codding: utf-8 ~*~

Not required variable definition

test_dir = None

Because of loop

for test_dir in dirs:

Use native generator insted

def get_dirs(dirs):
    """Get all immidiate directories in the current directory"""
    if not len(dirs) > MAX_DIRS:
        return []

    for test_dir in dirs:
        try:
            yield datetime.strptime(test_dir, TIME_FORMAT)
        except ValueError:
            print("Directory %s does not match date format, ignoring..."
                  % test_dir)

If you will use it like module, add

if __name__ == '__main__':
    copy_directory()
    remove_dirs()

IMHO: don't use direct input with input(), try parse command line instead using sys.argv or with help of some more powerful libraries.


Depth First Search Implementation (iterative)

Advice 1 (Space around binary operators)

Matrix=matrix

PEP-8 requires one space before a binary operator and after it:

Matrix = matrix

Advice 2 (Variable names should start from a lowercase letter)

Once again, you have a variable called Matrix. This applies to the function name DFS as well; I suggest you rename it to depth_first_search.

Advice 3

You print intermediate progress in your algorithm. Never do this. Think about what happens when your friend reuses your implementation: he or she will get overwhelmed with all that output that has no value. Also, it might slow down the execution of your algorithm, since printing goes down the chain to the very kernel. If you need to print anything, modify your algorithm to return a data structure which can do that, but let it do its work silently.

Advice 4

Your implementation seems to run in \$\Theta(V^2)\$ time. I suggest you convert the adjacency matrix to an adjacency list and input that list to your depth first search; this will bring down complexity to \$\Theta(E + V)\$, which is more efficient on sparse graphs (where \$E = o(V^2)\$).

Alternative implementation

Putting all together, I had this in mind:

from collections import deque

def adjacency_matrix_to_adjacency_list(adjacency_matrix):
    map = dict()
    j = 0

    for i in range(len(adjacency_matrix)):
        map[i] = []

    for adjacency_matrix_row in adjacency_matrix:
        for i in range(len(adjacency_matrix_row)):
            current_entry = adjacency_matrix_row[i]

            if current_entry == 1:
                map[j].append(i)

        j += 1

    return map

def depth_first_search(adjacency_matrix, source_node):
    open = deque([source_node])
    parents = {source_node: None}

    while open:
        current_node = open.pop()

        for child_node in adjacency_matrix[current_node]:
            if child_node not in parents.keys():
                parents[child_node] = current_node
                open.append(child_node)

    return parents


A Python Tkinter GUI which you can flick between images

Specific suggestions

Usually when you find yourself numbering variables it's time to put all of them in an iterable of some sort. In your case I would simply inline my_img1 etc. into image_list.
Usually names like images would be used instead of image_list. Python is a duck typed language, so it doesn't really matter which type of iterable you use for the code which does the iterating.
Rather than running the main code like root.mainloop() the Pythonic way to do it is this:

if __name__ == "__main__":
    main()

This ensures that the code doesn't run when importing from your file, making it possible to import into a bigger program.
Importing everything from a module is considered an antipattern - it makes it easier to end up with name collisions and it makes it harder to see at a glance where something was imported from.
Refer to existing data structures whenever possible. One example is if image_number == 5, which would be better as if image_number == len(image_list).
Avoid doing unnecessary work. For example, you create an object and assign it to button_forward, then you check whether you have to create a different object to assign to the same variable, in which case the original work was wasted (or in the worst case, had detrimental side effects). I would instead use an if/else to assign button_forward only once.
globals are considered a big code smell these days. A preferable pattern is to pass around exactly the values which each function/method needs. That way the code is much easier to debug. In fact, this is pretty much the perfect example of something which should be encapsulated in one or more classes. That way you have a natural place to keep track of state like image_number, and won't have to pass it around between methods.
It doesn't seem like a stretch that the images would be the user input to this application. If so it would be better to provide them using argparse.

Tool support suggestions

black can automatically format your code to be more idiomatic. It'll do things like adjusting the vertical and horizontal spacing, while keeping the functionality of the code unchanged.
flake8 can give you hints to write idiomatic Python. I would start with this configuration:

[flake8]
max-complexity = 4
ignore = W503,E203


Designing DAOs that handle composite objects

I would go for the first one, because it exposes a much simpler API to the caller.

The day you need to add anything to your design, if it's encapsulated this way, the caller doesn't need to change a thing and it's still going to work, because the Game knows how to build itself and doesn't put that burden onto the caller.


Is this an optimal implementation of merge sort?

Suspect that segmentation fault on large arrays occurs because the list1[] and list2[] ran out of space.  With the recursive calls, code is heavily using the stack space.  Use malloc() and free() for large arrays instead of VLA[]
Memory allocation could be reduced.  Via recursion, this takes > 2n (maybe 4n) memory space.  At worst it should be 2n.
Use size_t rather than int for a integer type that can handle all array indexes.

// void mergesort (int* list, int len)
void mergesort (int* list, size_t len)

Cope with 0 length.

// if(len == 1) return;
if(len <= 1) return;


Implementation of iterator pattern for any array of elements

I have two points for improvement:

Right now next() method increments the index. What happens if someone calls next() without calling hasNext() method?

Take care of ArrayIndexOutOfBoundsException or increment the index carefully.

You could implement remove() method (Optional)


You are assigning c = i in both cases, which means you could pull this out and do this once unconditionally. This also will give you an idea of cs purpose and might give you ideas for how to name your variables in a better way. So trying to stay as close to your code as possible but with the suggested changes, your code could look something along the lines:

inputString = 'azcbobobegghakl'

prevChar = ""
currentString = ""
longestString = ""

for char in inputString:
    if prevChar <= char:
        currentString += char
        if len(currentString) > len(longestString):
            longestString = currentString
    else:
        currentString = char
    prevChar = char
print('Longest substring in alphabetical order is: ' + longestString )

Also I suggest you think about edgecases and treat these cases or at very least you make it clear (at least in a comment) what happens in those cases. As an idea of what I mean: what happens if there are several longest-strings of the same length? Which one should be printed? All? The first? The last? Just any one? What happens if the inputString is empty - your message will look a bit funny. You could output a different message in such a case.

You might think I‘m a bit pedantic, but I seriously recommend to think about your code in this way.

Other than that, I must admit I don‘t know python well enough to give you „the pythonic“ answer - I‘m not even sure if they use camelCase for python - still I hope you get the idea of the type of improvements I‘m recommending. Other than that your code looks ok to me.


I have a number of suggestions:

Don't use self.dict

def __init__(self, **kwargs):
    self.__dict__.update(kwargs)

It is pretty unclear which attributes the class will have after calling the constructor, as it is basically up to the caller to decide this. This is not optimal, as you want to be in control of what data is set in an item. I'd suggest to use named arguments instead:

def __init__(self, id, type, title):
    self.type = type
    self.title = title
    self.id = id
    # Add other attributes that I don't know of?

While this may seem like blowing up the code, it makes it a lot easier to understand for an uninformed reader, and therefor should be preferred IMHO.

Append instead of format

Since you are basically just appending something to self.base_url, you might as well append using + instead of using format. I find it a lot easier to read, but that depends a lot on what you prefer. Consequently:

self.base_url = 'https://hacker-news.firebaseio.com/v0/'

Then

uri = self.base_url.format(**{'api': 'item/{}.json'.format(item_id)})

would look like this if using append:

uri = self.base_url + "item/{}.json".format(item_id)

HackerNews.get()

The get() method's name does not explain what the method does. I'd suggest something offering a bit more documentation, for example: download_item() or download_entry().

On a little side note: You can remove the else: statement, as the raise Exception(..) command will only be executed if the if statement evaluates to False. This depends a bit on personal taste though. I'd also change the ordering like this:

if response.status_code != requests.codes.ok:
    raise Exception('HTTP Error {}'.format(response.status_code))
return json.loads(response.text)

I'd prefer this ordering as it has the return statement at the end, which is where I'd look first when searching for it.

SimpleFIFO

Maybe you can use Python's Queue class? See here for documentation: https://docs.python.org/2/library/queue.html

It also provides a max size, the only thing missing is the check for adding only strings.

HNStream.init()

You can use the super keyword (see also: https://stackoverflow.com/questions/576169/understanding-python-super-and-init-methods) instead of explicitly calling the constructor like this:

def __init__(self):
    super(HNSTream, self).__init__()

Or in Python 3:

def __init__(self):
    super().__init__()

HNStream.stream()

Just a few naming suggestions:

r -> result
iid -> item_id

That was it, hope it helps!


Check if dictionary keys are declared, if not leave them as true

TryGetValue returns True or False if it was found in the dictionary. I would suggest something like below. As it's still a single lookup in the dictionary to get the value but you can also set a default value other than default if it's not found in the dictionary.

bool moreDetails;
if !(dictionary.TryGetValue("MoreDetails", out moreDetails))
{
    moreDetails = true;
}

Update to show extension method:

public static class DictionaryExtensions
{
    public static TValue TryGetWithDefaultValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue)
    {
        TValue value;
        if (!dictionary.TryGetValue(key, out value))
        {
            value = defaultValue;
        }
        return value;
    }
}

Then you could call it like:

var moreDetails = dictionary.TryGetWithDefaultValue("MoreDetails", true);


This is a nice start, but there's some stylistic stuff that could be improved.
Generally it's a good idea to name variables for what their purpose is. Names like l1 are difficult to understand. This varies depending on the language, but in Java people tend to be explicit with their variable naming, preferring descriptive names over concise ones.
When declaring a data structure, convention in Java is to declare the type as the interface.
public boolean areDuplicates(ArrayList<Integer> first, ArrayList<Integer> second)

is more commonly written as
public boolean areDuplicates(List<Integer> first, List<Integer> second)

This is because List defines a set of behaviours that you want to have, and ArrayList defines how they are implemented. If someone has made a data structure with the exact same behaviour as an ArrayList, then you want your methods to support that data structure as well.
The format of the code in quite unusual for Java. I'd run your code through an autoformatter, which deals with all that stuff for you. Personally I use Eclipse's default one, but there's loads of choice out there.
This isn't a complete review, and it's mainly my opinion, so feel free to include or discard this advice.


Marking class with no abstract methods as an abstract

It depends on your design entirely. If classes (2) and (3) can not operate on their own, should not be instanciated and are there to serve as base classes only, then you are justified to make them abstract, and i think you should.

Also, you should probably reflect your intent in class names by adding Base suffix to (2) and (3) (or prefix, but i think it is less common).

Edit Objects with protected constructor can still be instanciated. For example, you can create them from some method in derived class. It is not a realistic use-case in most cases, but you should not leave such holes nonetheless. If you want to forbid instanciation completely, the only way to do it is to mark the class abstract.


Implementing C++ relational operators generator

The problem I see is that it requires that the class be derived from relational, which is not a very durable design.  Instead, why not use the fact that "substitution failure is not an error" (which has the regrettable but commonly used abbreviation SFINAE). the use of real functions is preferred over the instantiation of templates.  That is, if an operator<= actually exists, the templated form will be ignored.  That might look like this:

template<typename T>
bool operator> (T const &lhs, T const &rhs) { return !(lhs <= rhs); }
template<typename T>
bool operator< (T const &lhs, T const &rhs) { return !(lhs >= rhs); }
template<typename T>
bool operator==(T const &lhs, T const &rhs) { return lhs <= rhs && lhs >= rhs; }
template<typename T>
bool operator!=(T const &lhs, T const &rhs) { return !(rhs == lhs); }
template<typename T>
bool operator<=(T const &lhs, T const &rhs) { return lhs < rhs || (!(rhs < lhs)); }
template<typename T>
bool operator>=(T const &lhs, T const &rhs) { return lhs > rhs || (!(rhs > lhs)); }

Note that the differences are that I've made each comparison operator its own template and that I've added one for < and defined <= and >= in terms of < and > respectively.

The result is that if any of the comparisons <, <=, > or >= are defined, then all of the other comparisons are also available.

Edit: I should probably have pointed out why this is different from std::rel_ops.  With std::rel_ops, in order to have all six relative operators, you must define operator< and operator==.  With this scheme, however, as long as at least one of the ordering operators is defined, all others will also be available.  This is due to the way these templates are deliberately circularly defined.  That is, > is defined in terms of <= which is defined using < which is defined using >= which is defined using >.  This arguably adds flexibility, but it also means that it's possible that the performance is not as good because a comparison may go through several templated function instantiations.

Further, if none of those operators is defined, that circular definition will mean infinite recursion at runtime until your stack is exhausted, putting this set of templates into the category of "perhaps more dangerous than clever" so Caveat lector.


Securely implementing AES/RSA hybrid crypto with PyCryptodome

While this question is an off-topic programming question on Crypto.SE, I doubt whether it'll get a better answer on StackOverflow or Code Review.

The part worries me is this:

...
    msg_hash = int.from_bytes(sha512(clear_text).digest(), byteorder='big')
    hashfromsignature = pow(signature, publickey.e, publickey.n)
    if msg_hash == hashfromsignature:
        valid = True

    else:
        valid = False
...

You seem to be verifying unpadded textbook RSA signature. You should change this part to using RSA-PSS signature scheme - it's a newer RSA signature scheme in PKCS#1 ver2.


API POST to save a new item in a Database via PHP & MYSQLI

What are these lines all about?

$thread = $con->thread_id;
$con->close();
$con->kill($thread);
$con = null;

it seems a bit, sorry for the pun, overkill. According to the PHP manual this should do just fine:

$con->close();

but even if you leave it out, the connection will be closed automatically when the script terminates. See:

http://php.net/manual/en/mysqli.construct.php

read the examples, and see:

http://php.net/manual/en/mysqli.close.php


Converting xy coordinates to theta without discontinutities

for index in range() is almost always wrong. Consider

prev = coords[0]
for coord in coords[1:]:
    theta = ...
    prev = coord

Instead of computing theta directly, compute delta - this way you may actually take an advantage of small differences:

prev = (1, 0)    # Initial vector is along the X axis
theta = 0.0
for coord in coords[]:
    delta = angle_between(coord, prev)
    theta += delta
    prev = coord

Computing delta is simply an application of a cross-product formula:

def angle_between(curr, prev):
    return asin(cross_product(curr, prev) / (norm(curr) / norm(prev))


The worst issues are cases of the same element being selected multiple times in order to apply various methods. Repeat selection of the same element should be avoided because selection of DOM element(s) is expensive.

There are also are cases where multiple selections have the same method applied. This isn't so bad for performance, but leads to unnecessarily bulky source.

The code can be improved with the following techniques :

using method chaining.
using comma separated selectors.
using $(this) to select the same element as the one to which an event handler is attached.
passing space-separated lists of class names to addClass() and .removeClass().

You might end up with something like this :

$('.info_2').on('click', function() {
    $('#card-wrapper').toggleClass('centre_share');
    $('.E_info').toggleClass('display');
    $('#info-btn').css('opacity', '0');
    $('#nav-wrapper').toggleClass('hidden_nav').delay(300).toggleClass('hidden').removeClass('display_nav').removeClass('display');
});

$('.info_back').on('click', function() {
    $('#nav-wrapper').removeClass('hidden_nav hidden').addClass('display_nav display');
    $('#info-btn').css('opacity', '1');
    $('.E_info').removeClass('display').addClass('hidden');
    $('#card-wrapper').removeClass('centre_share');
});

$('#info-btn').on('click', function(){
    $(this).toggleClass('close_btn');
    $('.o-card_border').toggleClass('info_display card_active');
    $('.start_title').toggleClass('hidden remove_flow');
    $('#svg_full, #svg_top, #svg_bot, #svg_bot_bot, #svg_bot_right').attr('class', 'test');
    $('.rectangle_style_frame3 display, .triangle_style').toggleClass('hidden');
    $('.bg-info, .info_CharactersInvolved, .info_themes, .E_info').toggleClass('display');
});


callback function with no dynamic memory allocation

lambda's don't alloc, std::function only allocates memory if the object it is wrapping is 'too large'.  The VC++ 2019 std::function impl defines 'too large' as being more than 7 * sizeof(void*) bytes in size.  Other impl may use a different limit.  This is big enough to handle many (most ?) cases w/o allocating.

You could make your own function class, based on std::function, and put static_assert's in the constructors and assignment op's to ensure none of your code that uses your function would trigger an alloc; or if it would you could increase the 'too large' size of your function class.  This would give you something as flexible as std::function, and the control over alloc that you want.

[EDIT]

If you don't want to use the VC++ version, the gcc one is at:

https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/bits/std_function.h

To start you can copy the file and put static_assert's before lines 160 and 237 to catch any cases that would require an alloc (likely also have to check dependencies in other gcc .h files).

... it looks like this version doesn't reserve much space i.e. would alloc in many cases.  You'd have to make a couple other tweaks to increase the no_copy size.


I think the main issue is that you took a bit-by-bit approach to a problem that seems to be designed to elicit approaches that take advantage of bitwise operations, which made the solution less elegant(?) than intended. There is a lot of code to extract individual bits and testing them, and an extra loop to go over the startingPosition, and we can do away with that. I don't expect a performance problem with your solution though, 0.2 seconds is a ton of time (running literally a billion instructions in that time is not unreasonable) and barely any memory is allocated.

As you already discovered, the question of "is there an X here" can be answered by ANDing
 together the bits that make up the X and also ANDing that with the complements of the bits at the positions that must be zero. Rather than working with booleans, we could work with entire 32bit masks at once, and get an entire 32bit mask as a result, which will then indicate the positions where an X is found. The Xs that are present can be counted using Integer.bitCount.

Forming that mask is really the same idea as the code you already wrote, but instead of adding offsets to the startingPosition there will be some bit-shifts. For example:

private static int calculateXMask(int top, int middle, int bottom) {
    return (top >>> 1) & ~top & (top << 1) &
        (~middle >>> 1) & middle & (~middle << 1) &
        (bottom >>> 1) & ~bottom & (bottom << 1);
}

Which can then be applied to every "window" of 3 successive integers in num, with the results bitCounted and added up.


Design

Try to put as little code as possible in your Start(), Awake() etc. methods. Have those methods call other methods. The reasoning is very similar to the reason behind avoiding code in the code-behind of WinForms or WPF applications. It seems like you could initialize those variables in the GetFriendRequests method.

In your if statements, it is common to put the most-expected outcome first, and put the edge case in the else. In your case, a success case is more accepted than a failure, so put that first.

So

    if (!String.IsNullOrEmpty(result.Error)) {
        // Failed Case
        lastResponse = "Get Friend Request Callback: Error Response:\n" + result.Error;
    } else if (!String.IsNullOrEmpty(result.Text)) {
        // Success Case
        lastResponse = "Get Friend Request Callback: Success Response:\n" + result.Text;
        JsonData datas = JsonMapper.ToObject(result.Text);
        Debug.Log(datas["data"]);
        for(int i = 0; i < datas["data"].Count; i++) {
            requestData.Add(i, JsonMapper.ToObject((string)datas["data"][i]));
            requestLoadStatus.Add(i, false);
            requestTexture.Add(i, new Texture2D(50, 50));
            StartCoroutine(LoadUserProfilePic(i));
        }
    }

should be:

    if (!String.IsNullOrEmpty(result.Text)) {
        // Success Case
        lastResponse = "Get Friend Request Callback: Success Response:\n" + result.Text;
        JsonData datas = JsonMapper.ToObject(result.Text);
        Debug.Log(datas["data"]);
        for(int i = 0; i < datas["data"].Count; i++) {
            requestData.Add(i, JsonMapper.ToObject((string)datas["data"][i]));
            requestLoadStatus.Add(i, false);
            requestTexture.Add(i, new Texture2D(50, 50));
            StartCoroutine(LoadUserProfilePic(i));
        }
    } else if (String.IsNullOrEmpty(result.Error)) {
        // Failed Case
        lastResponse = "Get Friend Request Callback: Error Response:\n" + result.Error;

    }

Spacing

You're cramping your code together and making it much harder to read. Spread it out a bit and things will look a lot less cluttered and complex.

e.g

protected void GetFriendRequests() {
    if(FB.IsInitialized) {
        FB.API("/me/apprequests", Facebook.HttpMethod.GET, GetFriendRequestsCallback);
    } else {
        InitFacebook();
    }
}

Is easier to read as:

protected void GetFriendRequests()
{
    if(FB.IsInitialized)
    {
        FB.API("/me/apprequests", Facebook.HttpMethod.GET, GetFriendRequestsCallback);
    }
    else
    {
        InitFacebook();
    }
}

I know the condensed form is how MonoDevelop decides to do bracing by default, which AFAIK is the Java style, but I prefer the expanded style for ease of reading, and it is the more common of the C# styles.

Secondly, it often helps to add breathing room around clauses in your code that use curly braces.

e.g.

        // Success Case
        lastResponse = "Get Friend Request Callback: Success Response:\n" + result.Text;
        JsonData datas = JsonMapper.ToObject(result.Text);
        Debug.Log(datas["data"]);
        for(int i = 0; i < datas["data"].Count; i++)
        {
            requestData.Add(i, JsonMapper.ToObject((string)datas["data"][i]));
            requestLoadStatus.Add(i, false);
            requestTexture.Add(i, new Texture2D(50, 50));
            StartCoroutine(LoadUserProfilePic(i));
        }

Looks easier to read as:

        // Success Case
        lastResponse = "Get Friend Request Callback: Success Response:\n" + result.Text;
        JsonData datas = JsonMapper.ToObject(result.Text);
        Debug.Log(datas["data"]);

        for(int i = 0; i < datas["data"].Count; i++)
        {
            requestData.Add(i, JsonMapper.ToObject((string)datas["data"][i]));
            requestLoadStatus.Add(i, false);
            requestTexture.Add(i, new Texture2D(50, 50));
            StartCoroutine(LoadUserProfilePic(i));
        }

Magic Variables

You're using magic variables in your code. Refactor these out as constants or static readonly variables.

e.g.

protected void GetFriendRequests()
{
    if(FB.IsInitialized)
    {
        FB.API("/me/apprequests", Facebook.HttpMethod.GET, GetFriendRequestsCallback);
    }
    else
    {
        InitFacebook();
    }
}

Should be:

private const string FacebookApiURL = "/me/apprequests";

protected void GetFriendRequests()
{
    if(FB.IsInitialized)
    {
        FB.API(FacebookApiURL, Facebook.HttpMethod.GET, GetFriendRequestsCallback);
    }
    else
    {
        InitFacebook();
    }
}

The reason you should do this is that if re-read the code it is more obvious what "/me/apprequests" means, which is invaluable when performing maintenance on year-old code.

Testing

Lastly, I am concerned by the heavy quantity of Debug.Log calls. I hope you're not testing your methods by writing status updates to the log, and are instead doing this so you can remain informed. If you are testing this way, stop right now. It's intensely inefficient, and Unity have released a free set of libraries for unit and integration tests that work very well with the engine.