The function takes around \$41\mu s\$ on average per run on my machine. About three quarters of it (around \$ 32\mu s\$) are spent for downsampling_indices = np.linspace(...). Add another \$1.5\mu s\$ for round().astype(int), about \$1\mu s\$ for the actual sampling, plus some calling overhead, and you're there.

So if you would need to use the function several times, it would be best to precompute or cache/memoize sampling indices. If I understood your implementation correctly, the downsampling index computation is basically data independent and only depends on the length of the two sequences, so that might be actually viable.

For example you could have

import functools

...

@functools.lru_cache()
def compute_downsampling_indices_cached(n_samples, data_sequence_len):
    """Compute n_samples downsampling indices for data sequences of a given length"""
    return np.linspace(0, data_sequence_len-1, n_samples).round().astype(int)

and then do

def resample_cache(n_samples, data_sequence):
    downsampling_indices = compute_downsampling_indices_cached(n_samples, len(data_sequence))
    return [data_sequence[ind] for ind in downsampling_indices]

Note that I replaced desired_time_sequence by n_samples which would then have to be set to len(desired_time_sequence) since you don't care about the actual values in desired_time_sequence.

It might also be possible to benefit from NumPy's indexing and use return np.array(data_sequence)[downsampling_indices] for larger inputs. You will have to check that yourself.

On my machine resample_cache(...) takes \$1.7\mu s\$, which is about a decent 20x speed up.


Calculating the terminal width and height

What is the functionality of this class?
Get width and height from process.stdout,
an external resource,
or else fall back to default values.

You can make this testable by making it possible to inject process.stdout, the external resource.
Then in the test you can inject an object that you control,
and verify that Terminal uses that object correctly or else falls back to the defaults correctly.

To make process.stdout injectable, you have at least two options:

Add an optional constructor argument. By default use process.stdout, only the test method will inject a custom object.
Add a _stdout function, that will be used by width and height, and in the test override it appropriately.


At first glance I can see a few points where you can start to optimize your polynom generation.
First thing I would refactor is the "heavy" use of conditional cases. There are only two well defined situation in which M==0 or M==L. Therefore you could extract both cases and implement them within the outer loop. If you don't care for code duplication copy/paste the functionality but if you care you have to write another function to call, which might be slow again. After you extracted the two special cases you cann ommit the remaining condition when you let L begin at 1 and run till L-1. Another point of optimization is to precompute values like 2*L-1 in the outer loop to have them "cached" for further access. As I'm not sure if sparse matrices are computationally faster than full matrices I'm not sure if I should recommend to use them from the beginning and not to convert the results into sparse matrices. Now I would try to vectorize as many operations as possible and let highly optimized code do the job for you.
And at last step @Elpezmuerto is fully right try to turn it into a mex function. This will precompile the function and speed up the execution time even further.


Your HTML seems to be correct, except you do not have a doctype in there, which goes at the top of the document:

Doctype for HTML5:

<!doctype html>

Your CSS has one error:

li {
    float: center;
}

center is not a possible value for float - only left and right are.

Otherwise, your code has no errors according to the official W3C validators:

  HTML Validator
  CSS Validator

Your HTML markup is, however, very difficult to read due to your wild indentation.  For example, you have this:

Your ending </style> tag should have the same level of indentation as the beginning tag, and I was taught to use 4 spaces as the indentation level.  Part of the problem is you are mixing tabs and spaces as your indentation level - only use one.

You also have this:

About Roamfree

        Roamfree is a small company that wants to be recognised by the internet and we
        decided to make a website to hold ALL our future products, apps and games!
        This is a Prototype website (not even alpha) so I need support from
        the online community so my coding skills will progress further and this company
        will (eventually) grow!

Relyr

Well Relyr is the measuring app that I am currently developing
    and it is optimised for iOS 8 and is targeted at the Iphone 5s (sorry Ipad users)
    and you press Start then you walk with your Iphone with you and afterwards you press
    Stop then using GPS it approximately calculates how far you walked, this is mainly for
    architects and builders but perfectionists can also use it as well :)

Again, the indentation is wild.

Your indentation on the CSS is very good.  However, as your webpage grows, you may find it easier to have the CSS in a different file than the HTML and link to it like this:

<link rel="stylesheet" type="text/css" href="Styles.css">

If you have multiple designs for different types of media, such as phones, printers, and regular computers, you can set the media tag like this:

<link rel="stylesheet" type="text/css" href="PrintStyles.css" media="print">


Can you make this Key-interable view of a List of Maps better?

Just parameterize with both types:

class ListKeyIterable<K,T extends List<? extends Map.Entry<K,?>>> implements Iterable<K>;


Looks good to me!

super minor nits:

        thread = threading.Thread(target=self.something)
        thread.start()

only uses the thread variable once, so you might as well do:

        threading.Thread(target=self.something).start()

Also, the only thing you use from threading is Thread so you might as well change your import to:

from threading import Thread

and then it can be just:

Thread(target=self.something).start()

...but again, these are super minor things!  It looks good to me; I may have to look at pyQT again :)


There is not need to go to streams at all for a piece of functionality already implemented in the containsKey member function of Map.

if(getCarsMap().containsKey(car.getModel())){
    if(!getCarsMap().get(car.getModel()).contains(car)){
        getCarsMap().get(car.getModel()).add(car);
    }
}


If you refactor your code a bit you can do it this way. I'm also making the assumption that you mean .hdid instead of #hdid there should only be one hdid per page if it's really an ID and not a CLASS. Here's a quick sample if you're interested in seeing it in action.

<script>
            var DeleteClass = function(hdid){
                $.ajax{
                    type: "POST",
                    url: "delete-class.php",
                    data: {hdid: hdid.val()},
                    cache:false,
                    success:function(){
                       hdid.parent().slideUp('slow',function(){$(this).remove();});
                    }
            }

    $(function() {
        $(".delete").click(function() {
            $('#load').fadeIn();
            $(this).children(".hdid").each(function(){
                DeleteClass($(this));
            });
            $('#load').fadeOut();
            return false;
        });
    });
</script>


Looks like that Grid and Cell should have parent-child relationship. Is it normal that I'm creating child objects at parent class?

There is no reason for a Grid and Cell to have any inheritance relationship. A Cell is not a kind of Grid, nor is a Grid a kind of Cell.

  I need somehow to give access to context var from Cell class without passing it via constructor.

Why? That's exactly how you should give a Cell access to the context. The constructor is the right way to do this. It's completely normal for a container class to pass needed context into its children.

  I had tried to play with prototypes but can't figure out how to do that.

It's a bad design to put data on the prototype. You would effectively make it impossible to have two independent Grids, if every single instance of Cell can only share access to one Grid's context via Cell's prototype. It's far better for each Grid to pass its context into all its Cells.


This is a very common interview question. However, your algorithm won't suffice: the array may be unsorted.

The method is to find the sum of the numbers in the array and then subtract it from the sum of numbers from 1 through 100. What's left over is what is missing from a complete list 1..100.

Sum of natural numbers \$1..N\ = \dfrac{N(N+1)}{2}\$.


K&R exercise 1-19: reversing each line of input

getlinea does too much: it reads the line and reverses it. A Single Responsibility Principle mandates restructuring the code:

while((len = getlinea(...)) > 0) {
    reverse();
    print();
}

Avoid naked loops. Each loop represent an important action, and deserves a name. The code:

reverse(char turnaround[])
{
    char aux[...];
    int len = length_of_string(turnaround);
    copy_backwards(aux, turnaround, len);
    copy(turnaround, aux, len);
}

is much easier to reason about.
The length of the input is known to the caller. Consider passing it as parameter:

reverse(char turnaround[], int len)
{
    char aux[...];
    copy_backwards(aux, turnaround, len);
    copy(turnaround, aux, len);
}

Finally, a string can be reversed in place. There is no need for aux. I hope you can figure a solution yourself.


You have an extra if statement in these that should be structured as an if/else statement, or even an if/else if statement

var distance = $('.site-header').offset().top,
    $window = $(window);

$window.scroll(function() {
    if ( $window.scrollTop() >= distance ) {
      $(".site-header").addClass("fixed");
    }
    if ( $window.scrollTop() < distance ) {
      $(".site-header").removeClass("fixed");
    }
});

You should write it like this instead:

$window.scroll(function() {
    if ( $window.scrollTop() >= distance ) {
        $(".site-header").addClass("fixed");
    } else if ( $window.scrollTop() < distance ) {
        $(".site-header").removeClass("fixed");
    }
});

If one is true you don't need to check the other condition.

Same thing with the other set of code as well

$(window).scroll(function() {
    var scroll = $(window).scrollTop();

    if (scroll >= 200) {
        $("body").addClass("scrolled");
    }
    if (scroll <= 200) {
        $("body").removeClass("scrolled");
    }
});

should be something like this

$(window).scroll(function() {
    var scroll = $(window).scrollTop();

    if (scroll >= 200) {
        $("body").addClass("scrolled");
    } else if (scroll < 200) {
        $("body").removeClass("scrolled");
    }
});

You were actually performing both if statements if scroll = 200, which is probably not what you wanted so I changed the equality expression to reflect what I thought you wanted.

Both functions could have an if/else instead of an if/else if because if you don't meet the criteria for the first statement you meet the criteria for everything else with the else if.

I also removed an unnecessary variable in the second function as well

$window.scroll(function() {
    if ( $window.scrollTop() >= distance ) {
        $(".site-header").addClass("fixed");
    } else {
        $(".site-header").removeClass("fixed");
    }
});

$(window).scroll(function() {
    if ($(window).scrollTop() >= 200) {
        $("body").addClass("scrolled");
    } else {
        $("body").removeClass("scrolled");
    }
});

Really what you are doing here is overloading that function, but you don't give it any options which function to run, so what would most likely happen is that both sets of functions will run.

I am not sure what the difference is between $(window).Scroll(function() ... and $window.Scroll(function()... is, maybe that is how you distinguish between which version of the function to run.

If you are going to run both code at the same time you could just put them together inside one function call.


Streamlined code for get:

get: function(key){
    var lh = location.hash.replace(/^#/, "");
    var pairs = lh.split("&");
    var obj = [], pair;

    for(var i = 0; i < pairs.length; i++){
        pair = pairs[i].split("=");
        if (pair.length === 1) {
            pair.push(1);
        }
        obj[pair[0]] = pair[1];
    }
    return typeof key !== 'undefined' ? obj[key] : obj;
},

I also don't see why there's a callback passed to .set()?  There's no async operation and the callback is executed at the end of the function with no args so the caller could just put that same code right after the .set() call.  There doesn't seem to be any reason for a callback argument.


Showing "open" or "closed" based on the current time

The first bug is that you are misusing setInterval().  You should be passing a function, not the void result of the function, when calling setInterval().

Even if you had used setInterval() correctly, you still have a second bug, which is that currentDate is set just once when the code loads.  If you call openClose() every five seconds, you would get the same result every time!

Third, the JavaScript sets .style.display = 'none', but never resets elements to be visible.  Therefore, even if the first two issues were corrected, your page would appear emptier and emptier through the course of the week.

The code should degrade gracefully in the absence of JavaScript.

Display decisions should be written in CSS.  Ideally, the JavaScript should refrain from making decisions like .style.display = 'none', and should restrict itself to doing the minimum necessary (i.e. setting classes) to let the CSS work.

There is a giant maintenance headache: the hours are encoded both in the HTML and the JavaScript.  It is likely that someone in the future would edit one but forget to edit the other accordingly.  Furthermore, the JavaScript representation is both cryptic (what does 17.5 mean?) and cumbersome (all those if conditions!).  I recommend changing the JavaScript code so that it interprets the opening hours from the HTML.  The easiest way would be to store the hours redundantly as machine-readable attributes in the HTML.

function isOpen(timeRangeEl, date) {
    var day = '' + date.getDay();
    var hhmm = ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);

    var days = timeRangeEl.getAttribute('data-days');
    var openTime = timeRangeEl.getAttribute('data-open');
    var closeTime = timeRangeEl.getAttribute('data-close');
    return days.indexOf(day) >= 0 && openTime <= hhmm && hhmm < closeTime;
}

function openClose() {
    var date = new Date();
    var display = document.getElementById('open-display');
    var els = display.getElementsByClassName('timerange');
    var anyActive = false;
    for (var i = 0; i < els.length; i++) {
        if (isOpen(els[i], date)) {
            anyActive = true;
            els[i].className = els[i].className.replace(/ *inactive\b/g, '');
        } else if (els[i].className.indexOf('inactive') < 0) {
            els[i].className += ' inactive';
        }
    }
    if (anyActive) {
        display.className = 'open';
    } else {
        display.className = 'closed';
    }
}

setInterval(openClose, 5000);
openClose();
#open-display.open > .timerange.inactive,
#open-display.open .days {
     display: none;
}
#open-display.open > .openclosed::before {
    content: 'Open';
}
#open-display.closed > .openclosed::before {
    content: 'Closed';
}

Sales: Mon - Thu 8am - 8pm

Sales: Fri 8am - 5:30pm


Code to generate a random date of birth which will always represent an age less than 18 years from current date

datetime.date has a .replace() method that returns a copy with some values changed.  This can be used to get the date 18 years ago.
end_date = date.today()
start_date = end_date.replace(year=end_date.year - 18)

datetime.date.toordinal returns an integer corresponding to the date. The ordinals for the start and stop date can be used in random.randint() to pick a random ordinal, which can then be converted back into a date with date.fromordinal().
random_date = date.fromordinal(random.randint(start_date.toordinal(), end_date.toordinal()))

date.isoformat() returns a date a as YYYY-MM-DD. Or use date.strftime() for more control over the date format.  In an f-string, a date is converted to ISO format, or a format string can be used:  f"{random_date:%a, %b %d, %Y}" -> 'Sat, Dec 14, 2013'.
If you want to generate a list of dates in the range, use random.sample() with a range object.
NUMBER_OF_DATES = 10

date_range = range(start_date.toordinal(), end_date.toordinal())
random_dates = [date.fromordinal(o) for o in random.sample(date_range, NUMBER_OF_DATES)]


0cm, 0px or 0x corresponding to 0, it doesn't need unit if it's of the same order of magnitude. 0px * 10cm is the same than 0 * 10cm.
In this case border-width corresponding to length's order of magnitude it's not necessary to precise the units.

Moreover, for my part, I never specifies the things which are default. Whatever the language. I think it's more readable and elegant. It's my opinion because some people I met prefers specify everything.

I hope my english is not so bad .


Determining if a string can be permuted to a palindrome

I much prefer your solution. It's easy to read and straightforward. The difference in size between the 2 is probably not that much. Their code has an unordered_set with a few elements in it. Your code has an unordered_map with likely 26 elements in it. We're talking about 26 * 5 = 130 bytes vs. say 5 or 10 bytes for the set on average. On modern systems, this is not a difference in memory usage. It's all below 1KB. If you're working with some old or oddball hardware and that becomes an issue, you can deal with it then.

However, if I were to see this code in production, I would probably want the following changes:

I would opt for using auto instead of the long type name in this line:

for(std::pair<char, int> letter : letter_count) {

I'd make it:

for(const auto& letter : letter_count) {

As mentioned in the discussion in the comments, making it a reference saves a copy of the pair and making it const lets a reader know that you aren't going to be modifying it.

I'd use more space between operators in the next line:

if(letter.second%2 != 0) {

would become:

if (letter.second % 2 != 0) {

It's just easier to read.

I might make that conditional into a named function just to make it clearer:

bool isOdd(const int x)
{
    return (x % 2) != 0
}

// ...
if  (isOdd(letter.second)) {


Turning a flat nested set into a hierarchy

What about idea (and removing categoryDtos.RemoveAll(x => x.Depth > 0); // Terrible):

if (parent != null)
{
    filteredCategories = categories.Where(x => x.Depth == (parent.Depth + 1) &&
                                               x.Left > parent.Left &&
                                               x.Right < parent.Right).ToList();
}
else
{
    filteredCategories = categories.Where(x => x.Depth == 0).ToList();
}

Or, if the function is used somwhere else as well, maybe additional parameter to function like bool onlyTopLevel.


If you have another point to improve, please comment or answer, I will change the accepted answer

To put in CakePHP pattern I remove both lines:

$this->autoRender = false;
$this->response->type('json');

and change how I create and return the JSON file change this:

$this->response->body(json_encode($response));

to this:

$this->set('response', $response);
$this->set('_serialize', 'response');

the result:

public function login()
{
    if ($this->request->is('post')) {
        $user = $this->Auth->identify();
        if ($user) {
            $this->Auth->setUser($user);
            $response = new ResponseMessage();
            $response->code = CodeEnum::LOGIN_GRANTED;
            $response->name = NameEnum::LOGIN_GRANTED;
            $response->type = TypeMessageEnum::SUCCESS;
            $this->set('response', $response);
            $this->set('_serialize', 'response');
        }else {
            $response = new ResponseMessage();
            $response->code = CodeEnum::LOGIN_DENIED;
            $response->name = NameEnum::LOGIN_DENIED;
            $response->message = MessageEnum::USER_PASS_INCORRECT;
            $response->type = TypeMessageEnum::ERROR;
            $this->set('response', $response);
            $this->set('_serialize', 'response');
        }
    }
}


ElasticSearch, Tire - refactor autocomplete method for multiple resources

I'll take autocomplete and leave the rest for others. Some notes:

Never write the pattern "empty array" + each + push + return array. That's a map (more on functional programming here)
Is this "lib" thing really in lib/? it should go to app/. In lib you only have generic code that may be reused across applications.
Don't write routes by hand, ever, that's terrible practice, use the helper router methods provided by Rails.
Don't write tags by hand, use content_tag.
Abstract and simplify by identifying repeated patterns in your code.

I'd write:

def autocomplete
  results.map do |result|
    title, caption, route = case result.type.to_sym
    when :past_event
      [result.content, "PastEvent", past_event_path(result)]
    ...
    end

    label = "%s %s" % [title, content_tag(:span, caption, class: 'search-type')]
    {title: title, label: label, value: route}
  end
end


You would hava a) thread-pools so that the code won't spawn a new thread on each sub-sort, b) a limit on the number of sorts split into threads so that there isn't a new thread spawned for a low number of elements and c) a single array where all the sorting takes place and which is paritioned like a stack among the sort-threads (afaik the whole length should be two times the size of the array).

That would be a much of work to gain an efficient implementation.


The usual way is a little more complex, but a lot faster when the exponent is large. It looks something like this:
template <class T>
T mul_mod(T a, T b, T m) {
    if (m == 0) return a * b;

    T r = T();

    while (a > 0) {
        if (a & 1)
            if ((r += b) > m) r %= m;
        a >>= 1;
        if ((b <<= 1) > m) b %= m;
    }
    return r;
}

template <class T>
T pow_mod(T a, T n, T m) {
    T r = 1;

    while (n > 0) {
        if (n & 1)
            r = mul_mod(r, a, m);
        a = mul_mod(a, a, m);
        n >>= 1;
    }
    return r;
}

pow_mod right-shifts n (the exponent) each iteration through the loop, so the number of iterations is proportional to the number of bits in the number (where yours in the question is proportional to the exponent itself). In other words, yours is linear on the exponent's magnitude, and this is roughly logarithmic exponent's magnitude.
Actual code review
Since this is CodeReview, not (for example) Stack Overflow, let's also take a look at reviewing your code.
Variable Definitions
You've defined multiple variables in a single definition:
int base,exponent,mod;

Many people find it more readable to define one variable per definition:
int base;
int exponent;
int mod;

... or at least use a separate line for each variable:
int base,
    exponent,
    mod;

Naming
A function's name should reflect what it really does. Using power for modular exponentiation borders on misleading. I'd rather the name included modular or at least mod.
formatting
At least IMO, a little white space can help readability quite a bit. For one example, instead of:
int power(int base,int exponent,int mod)

...I'd rather see a space after each comma:
int power(int base, int exponent, int mod)

In addition, where there's flow control, the controlled statements should be indented, so this:
if(mod==1)return 0;

would come out like:
 if (mod==1)
     return 0;

return from main
When execution "flows" off the end of main, there's an implicit return 0;, so you can eliminate that line from your code (though some prefer to keep it).
Use of endl
I'd avoid using std::endl (ever). Most of the time you really just want to write out a new-line, in which case \n is entirely adequate. On the (relatively rare) occasion that you really also want to flush the stream as endl also does, you should do so explicitly.
using namespace std;
Pulling in the entirety of namespace std; like this is generally frowned upon. It's all right for other (more sensibly designed) namespaces, but std defines a huge amount of "stuff", most of which you really don't want directly visible.


What is wrong with my knapsack alghoritm?

Branch&Bounding is not what you have implemented (at least I can't see the classic algorithm in there).

Branch And Bound is normally implemented as a recursive process. I don't see recursion here. Additionally, even if the recursion is unwound to your while loop, I can't see where the efficient Branching happens.... frankly, it's a bit confusing.

Additionally, as I read your code, I believe there is a bug in that your solution will always contain items[0] (the firstNode is always pushed to the stack, and the code completes when it is popped....).

The general solution for the knapsack algorithm is to try every combination of items and find ones that fit. This is a 'combination' problem. Using recursion to find combinations is quite easy, and it is well defined using the 'branch' part of Branch and Bound.

The Bound part of the problem is that you can eliminate whole branches based on the known state of the knapsack at that branch (i.e. adding anything more from that branch will cause the conditions to fail, so you can 'prune' the whole branch). The Bound part makes the Branch part more efficient.

I believe the Branch-side of your code is broken, so the Bounds-part comes later (when you have revised/reposted the branch side).

Working on the branch side of things, the easiest thing to do is to have recursion in a for-loop......

I recommend passing a 'Branch' Object back from the recursive method, and stipulating a target weight for the branch:

public Branch branch(Item[] items, int fromposition, int target) {
    if (fromposition >= items.length) {
        return null;
    }
    Branch best = null;
    for (int i = fromposition + 1; i < items.length; i++) {
        Branch current = new Branch(items[i]);
        // note that the recursion happens from fromposition+1
        current.addAll(branch(items, i, target - items[i].weight));
        if (current.weight <= target) {
            best = (best == null || current.weight > best.weight) ? current : best;
        }
    }
    return best;
}

With the above code we calculate the 'weight' of the Branch, and we compare that to the capacity remaining in the knapsack. If we compare every combination with our knapsack we would find the solution, but not in the most efficient way. This does the Branch but nothing about Bounds.

To compute the bounds there are a few solutions.... but, starting off with sorted items leads to the most efficient solutions.... so, sort your items in ascending order.

Then, your Bounds solution becomes the simple addition of a couple of constraints:

change:

for (int i = fromposition + 1; i < items.length; i++) {

to

for (int i = fromposition + 1; i < items.length && items[i].weight <= target; i++) {

Now we stop checking our branches the moment we find that the next option is too large, and we can skip processing anything after that item because our data is sorted, and we know that the rest of the stuff is even heavier.

Another bound we can add is to stop checking when we find a perfect solution:

        if (current.weight <= target) {
            best = (best == null || current.weight > best.weight) ? current : best;
        }

becomes:

        if (current.weight == target) {
            return current;
        } else if (current.weight < target) {
            best = (best == null || current.weight > best.weight) ? current : best;
        }

I have just typed this in, I have not verified any of the code, but, as you can see, the solution would be:

public void knapsack2(Item[] inputitems, int maxWeight) {
    // take a copy because we will sort the items...
    Item[] items = Arrays.copyOf(inputitems, inputitems.length);
    Arrays.sort(items, new Comparator<Item>() { ... sorts by weight...});
    Branch best = branchAndBound(items, 0, maxWeight);

}

public Branch branchAndBound(Item[] items, int fromposition, int target) {
    if (fromposition >= items.length) {
        return null;
    }
    Branch best = null;
    for (int i = fromposition + 1; i < items.length; i++) {
        Branch current = new Branch(items[i]);
        // note that the recursion happens from fromposition+1
        current.addAll(branch(items, i, target - items[i].weight));
        if (current.weight <= target) {
            best = (best == null || current.weight > best.weight) ? current : best;
        }
    }
    return best;
}

The Code for the Branch class will need to allow you to track the branch weight, and to add Items to the branch. Then, at the end, return the Items too.


Different ways of creating a multiplication grid in ruby

return from function anti-pattern

For the second example, doing

x = computation()
x

In a function is an anti-pattern, you should return the result directly:

computation()

It is more common and easier for the same result.

No Array

The first function does not need an array, just append to the string directly.


Implement an algorithm to find the Kth to last element of a singly linked string

To get the sub-list of the last n elements without computing the length first (see comments):

Go ahead with an end pointer until you have skipped n elements.
Now go ahead in parallel with a start pointer and the end pointer until the end pointer reaches the end of the list (the start and end pointers will stay n elements apart as you go).
Now start points to the desired sub-list.

In an interview, before you implement anything, it's often a good idea to first describe your plan. Counting first works and is no different in terms of the O notation, but I doubt it's what the interviewer wanted to see. Describing your plan can avoid spending time on something the interviewer might not really be interested in.


Vigenere Cipher - make code more concise?

As far as OOP languages go, Python has a very weak sense of encapsulation.

The only thing we do have are putting a single _ in front of a method or variable name, to signal that it is an internal variable/method and should not be used unless within the class itself and maybe derived classes. This is a pure convention, but should be understood similarly to protected in other languages.

In addition to this, when we put two underscores in front__ of the name, this signals that the variable/method is what we would call private in other languages. For these variables, Python does some name wrangling, so for some object a = A(), a.__x becomes accessible only as a._A__x. This should already signal that you should not normally use this from outside the class, these variables are definitely not part of the public API.

So, to put it shortly, just rename your __encrypt and __decrypt methods to encrypt and decrypt.

This has the added advantage that if you have a different encryption class (which you seem to do, called Caesar), the interface does not change. With both you can do cipher.encrypt(...) and cipher.decrypt(...), so the only thing you have to change when changing the encryption engine, is swap the actual objects.


Sadly, yes. If you want users of your library to write intArrayOf(1, 2, 3).extendEntries(5) then this is how it is done in Kotlin.

In fact, the Kotlin source code contains methods similar to it, with a specific function for each type of array: (kotlin.collections._Arrays.kt)

/**
 * Returns a single list of all elements yielded from results of [transform] function being invoked on each element of original array.
 */
public inline fun <R> ShortArray.flatMap(transform: (Short) -> Iterable<R>): List<R> {
    return flatMapTo(ArrayList<R>(), transform)
}

/**
 * Returns a single list of all elements yielded from results of [transform] function being invoked on each element of original array.
 */
public inline fun <R> IntArray.flatMap(transform: (Int) -> Iterable<R>): List<R> {
    return flatMapTo(ArrayList<R>(), transform)
}

/**
 * Returns a single list of all elements yielded from results of [transform] function being invoked on each element of original array.
 */
public inline fun <R> LongArray.flatMap(transform: (Long) -> Iterable<R>): List<R> {
    return flatMapTo(ArrayList<R>(), transform)
}

However, Kotlin uses a generator to generate such files, see the README at https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib

In your case, you might consider just implementing Iterable<T>.extendEntries as all of these specific types of arrays can be transformed to an Iterable<T> using the Kotlin stdlib .asIterable function.


Converts a user inputed string into a Integer

Nitpicks

void retreiveStringInput(char *str, size_t buffersize)

Misspelled.

void retrieveStringInput(char *str, size_t buffersize)

Not a critical mistake, since you used it consistently.  Don't forget to change other uses when you fix it.

            printf("Touble allocating memory, Please try again...\n");

This suggests that there is trouble allocating memory, but this code doesn't allocate memory.  It reads from input.

It also has a typo in "Trouble".

Keeping it simple

    size_t strsize = strlen(str);
    if (str[0] != 0) {
        for (size_t strIndex = 0; strIndex < strsize; ++strIndex) {
            if (isdigit(str[strIndex]))
                continue;
            else
                return false;
        }
        return true;
    }
    else {
        printf("String is empty...\n");
        return false;
    }

Consider

    if (*str == '\0') {
        printf("String is empty...\n");
        return false;
    }

    for (; *str != '\0'; ++str) {
        if (!isdigit(*str)) {
            return false;
        }
    }

    return true;

I find it easier to use positive if conditions with else statements.  So the if is the positive case and the else is the negative case.  In this situation, we don't need an else then, as we return in the if.

There is no point in a continue when there is no statement to skip.  Just let it go.  It will continue automatically.  You don't need an else case.

You only used the length as part of the condition check in the loop.  But we don't need it.  We can just check for the end of the string directly.  We know that the end of string marker is '\0', so we can just check for that.

It's true that '\0' is 0, but it is more readable to write it out in my opinion.

I changed str[0] to *str because I knew that I was going to be saying *str in the for loop anyway.  Rather than use two different things that return the same value, I picked the one that worked in both cases.  It would look kind of odd to repeatedly do str[0] and act as if the values would be different.  That's more understandable with *str.

I don't like the single statement form of control structures.  I always use the block form as being more robust against editing mistakes and a little easier to read.

Avoid unnecessary floating point operations

    size_t power = len - 1;
    int convertedString = 0;
    for (size_t strIndex = 0; strIndex < len; ++strIndex, --power) {
        convertedString += ((int)(str[strIndex] - '0') * pow(10,power));
    }

Consider

    int convertedString = 0;
    for (size_t strIndex = 0; strIndex < len; ++strIndex) {
        convertedString *= 10;
        convertedString += (int)(str[strIndex] - '0');
    }

We don't need power anymore.

We don't convert to and from a floating point type.  No danger of precision losses.  Everything is an integer type.  We probably don't even need the explicit cast to int.  I haven't run the code, so I left it.

Simplify

        if (strHasAllDigits(number))
            intNumber = strToInt(number);
        else {
            printf("Number must be a whole number containing no characters, please try again...\n\n");
            continue;
        }
        printf("Your number is: %d\n", intNumber);
        break;

Consider

        if (strHasAllDigits(number)) {
            int intNumber = strToInt(number);
            printf("Your number is: %d\n", intNumber);
            break;
        }

        printf("Number must be a whole number containing no characters, please try again...\n\n");

Now we don't have to declare intNumber outside the loop.  And we don't have to continue to skip the break.


(How) should I avoid writing procedural code in Haskell?

The code looks much better after refactoring!

Additionally I'd strongly suggest to keep line lengths within some limit. Usual choices are something between 72 and 80. There are two reasons for it:

People with smaller screens aren't able to see a piece code at once and have to scroll. This makes reading the code next to impossible (like when your snippet here on SO doesn't fit into its frame).
Even for a person with a wide screen it's difficult to read text with long lines. It's hard for eyes to focus where the next line starts.

Don't be afraid to use short identifiers, if theirs scope is limited to a short function. For example, in my opinion this

rotate_left :: Tree a -> Tree a
rotate_left (Branch l v (Branch rl rv rr _rc) c)
          = (Branch (Branch l v rl Red) rv rr c)

is more readable, and it's visually easy to spot what is going on.

One thing that will also help you make the code shorter more readable is using as-patterns (see also this question):

do_add :: (Ord a) => Tree a -> a -> Tree a
do_add branch@(Branch left node right colour) val
    | val < node = (Branch (add left val) node right colour)
    | val > node = (Branch left node (add right val) colour)
    | otherwise = branch -- HERE: we don't need to recreate the node
do_add Leaf val = (Branch Leaf val Leaf Black)

It also can give a small performance boost as we don't re-create objects identical to those we pattern match on.

Concerning fix_up: Let's try to factor out common and duplicate code. The common pattern is that we check some conditions on the sub-nodes of a node and if it's true, we apply a function or it. Otherwise we keep it intact. We can split this idea into two functions - one that is general, and other that is then specialized for branches:

fix_up :: Tree a -> Tree a
fix_up =
    onBr [is_red]                         [is_red] flip_colours .
    onBr [is_red, is_red . get_left_node] []       rotate_right .
    onBr [not . is_red]                   [is_red] rotate_left
  where
    -- Apply a function on a branch, if its left and right subnodes match
    -- given predicates.
    onBr :: [Tree a -> Bool] -> [Tree a -> Bool]
         -> (Tree a -> Tree a) -> (Tree a -> Tree a)
    onBr lps rps = on (\b -> all ($ get_left_node b) lps
                          && all ($ get_right_node b) rps)
    -- Apply a function on a value, if it matches a predicate.
    on :: (a -> Bool) -> (a -> a) -> (a -> a)
    on p f x | p x       = f x
             | otherwise = x

This allows us to represent the whole operation as the composition of several functions. And it localizes bindings of subnodes (l and r) to the predicates, which again helps readability.

I'd also like to draw your attention to AA trees. They have very similar performance as red-black trees, but are simpler and easier to implement.


Saving customized pizzas this way, looks OK but it also depends on how the rest of application is structured. I think your biggest concern here should be the historical data integrity you mentioned in your second question.

When it comes to data, the context they live in, helps you figure out how you should treat them. For example, when running a business like a pizza store with online ordering, toppings once available to customers can't just be "deleted". They can become unavailable, discontinued or something in these terms, but not deleted. You can't respond to customers that ask you to add pepperoni to their pizzas: "Oh, we deleted pepperoni!".

Once data hit production they will always be part of your application, despite how their status changes, so you have to treat them as if they will always be around.

This is somewhat a common issue and there are a few ways to solve it. I can mentioned two of them which I've used in the past.

1st Approach: Soft Data Deletion

The first approach, would be to go with some sort of soft delete policy for your data. You can find many posts across the internet about this technique and you can find many gems for ActiveRecord which could be used right out of the box. Practically, what you achieve with soft deletes, is that, when you're deleting data, you're not really deleting them, but you mark them as deleted so you can exclude them from your queries.

The most common ways to do this is either by adding a new column to your table that indicates a record has been deleted (e.g. deleted_at:datetime, deleted:boolean), or by adding a separate, mirror table in which "deleted" data will be moved (e.g. deleted_toppings). Both options have their pros and cons so it really depends on how the application is designed.

Keep in mind that soft delete may add complexity to your app. For example what will happen when you require Topping#name to be unique and you try to add a new topping with an identical name that already belongs to a soft-deleted topping?

2nd Approach: Separate model for customized ordered pizzas

The second approach would be to treat OrderedPizzaToppings in a completely different way. The idea here is to decouple OrderedPizzaTopping from PizzaTopping.

It could look like this:

class OrderedPizza < ActiveRecord::Base
  belongs_to :order

  has_many :ordered_pizza_toppings
end

class OrderedPizzaTopping < ActiveRecord::Base
  belongs_to :ordered_pizza
end

Every time an ordered pizza is created you will dump each Topping's data to a OrderedPizzaTopping instance and you'll save it. For example you could have something like this:

class OrderedPizzaTopping < ActiveRecord::Base
  belongs_to :ordered_pizza

  def self.from(topping = Topping.new)
    create!(data: topping.to_h)
  end
end

# ....

def create_order(pizza:, chosen_toppings:)
  Order.transaction do
    order = Order.create
    ordered_pizza = order.ordered_pizzas.create(name: pizza.name)
    ordered_pizza.toppings << chosen_toppings.map { |t| OrderPizzaTopping.from(t) }
    order
  end
end

If you noticed the only thing that OrderedPizzaTopping does is to store a hash version of PizzaTopping. Just a simple data structure containing name, description, price, image url, etc. Now, even if the PizzaTopping gets hard-deleted at some point, you'll always have the raw data which will allow you to represent the Order in any way you want. Optionally, you could store a reference to the original PizzaTopping in case it exists in your database.

Historical data integrity is not about deleted data only. What will happen if someone changes the price for a Topping that has been around for a year? All orders that include pizzas containing this topping will be affected.  I think the keyword here is auditing. Auditing a model, means to log data changes throughout time.


There are not many things to criticize here ... the basic algorithm in general looks good.

The three items I would caution you on are:

you are keeping track of the path-count in the paths static variable. This is a pattern that, although works, is not very 'pretty', there's a better way... I'll explain.
you modify the source array. This can be OK, but, in general, when you want to modify the source data you should instead work off a copy of the data.
all your other variables (the maze itself and the size of the maze) are static.

With a slight shift in the way you think of your search method, instead of updating the number of paths, you should instead think 'how many paths from here?'

Also, lets fix the static variable issues too (we will need two methods for this):

public static final int search(int[][] data) {
    int[] mymap = new int[data.length][];
    for (int i = 0; i < data.length; i++) {
        mymap[i] = Arrays.copyOf(data[i], data[i].length);
    }
    return search(mymap, 0, 0);
}

Now, the search(...) recursive method should return an int, and it takes the maze as input, not from a static variable.

To avoud the use of the 'n' variable, we use the basic information from the maze. The following is a copy/paste of your code with slight modifications:

it returns int
return-statements inside return a value now
the input includes the 'maze' (instead of being a static variable)
there are no references to n, just to the a array
it has an internal paths variable
it changes how it calls exist(...)

public static int search(int[][] a, int i, int j)
{
    if(!exist(i,j) || a[i][j] == 1)
        return 0; // no path here.
    if(i == a.length - 1 && j == a[i].length - 1)
    {
        return 1; // 1 path here.
    }
    a[i][j] = 1; // mark that we have seen this spot here
    int paths = 0; // introduce a counter...
    paths += search(a, i+1,j); // add the additional paths as we find them
    paths += search(a, i-1,j);
    paths += search(a, i,j+1);
    paths += search(a, i,j-1);
    a[i][j] = 0;
    return paths; // return the number of paths available from this point.
}

The exist() function will also need to change:

public static boolean exist(int[][] a, int i, int j)
{
    return i>=0 && j >=0 && i < a.length && j < a[i].length;
}

Note that this no longer references the n static variable either.

Finally, with these changes (and, really, in the scheme of things they are 'small'), your main method simply becomes:

    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int[][] a = new int[n][n];
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < n; j++)
        {
            a[i][j] = sc.nextInt();
        }
    }
    System.out.println(search(a));

For this, the a does not need to be static either.

If you code the process like I suggest then the methods become much more generic, and you have other advantages like:

the methods are all thread-safe now (you can find many paths in parallel using the same methods).
the data and the logic are both self-contained.
there are no static variables.

Finally, the variable names you have chosen are really short..... consider renaming the a variable at least.


Writing to rotating log file via channels

First up, as I understand it, you want to write to log files, but avoid constant IO operations. That's understandable. What I struggle to understand, however, is why you wouldn't use the standard golang packages to do buffered writes? the bufio package has a buffered writer that does just that.

Seeing as this is a code review site, allow me to first address some aspects of your code that could do with some more work. A quick overview of these things:

Avoid using new(). It's more idiomatic, and flexible, to actually create a literal: new(ChatLog) => &ChatLog{}. This has the advantage of offering the visual reminder that it's a pointer (&), and allows you to initialze any exported fields.

This allows you to write the following:

cl := new(ChatLog)
cl.logDir = LogDir
cl.Protocol = Protocol
cl.Server = Server
cl.logChannel = make(chan map[string]string, MaxQueue)

As a oneliner:

cl := &ChatLog{
    logDir: logDir,
    Protocol: Protocol,
    Server: Server,
    logChannel: make(chan map[string]string, MaxQueue),
}

That, to my eye looks a lot cleaner.
A similar thing can be said about your example usage snippet. make is a construct you use to create buffered channels, slices with a pre-set length and/or capacity. If you don't need to do that, you might just as well use a literal:

testEntry := make(map[string]string)
testEntry["Type"] = "PRIVMSG"
testEntry["Entity"] = "SomeUser"
testEntry["Content"] = "This is the message!"
testLog.AddEntry(testEntry)

Can be written as:

testLog.AddEntry(
    map[string]string{
        "Type": "PRIVMSG",
        "Entity": "SomeUser",
        "Content": "This is the message!",
    },
)

A lot cleaner, I'd say.

"Errors are values, just like any other" is an adage you might have heard. This is true, but when you're doing something quite fundamental like logging, it's a really, really bad idea to ignore errors. If your logging component fails, I'd argue the best thing to do at that point is simply to call it a day, and exit. It's a fatal error IMO.

This means, for example that in your Open function:

if err != nil {
    log.Println("Error opening file:", logFilename)
}
chatLog.logFile = f

You're using the standard log package to simply print out a line saying you couldn't open the log file, and then you happily go and assign what can only be a nil pointer to chatLog.logFile. The first time you try and log something, you'll get a runtime panic because you'll attempt to dereference a nil-pointer. What I'd do at that point is log the actual error value I received and call os.Exit(1) or something:

f, err := os.OpenFile(logFilename, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
    log.Println("Failed to open logfile %v - %v", logFilename, err)
    os.Exit(1)
}
chatLog.logFile = f

Some other things to consider (quite urgently)

Your code is not thread-safe. You're exporting both RotateIfNeeded and Write. Neither of these functions actually lock. I can see why, but what could happen if, when someone calls the RotateIfNeeded function, which then decides to open a new log, and in that time your Write function reaches the chatLog.logFile.Sync call? You close the logFile before you open a new one. These operations aren't atomic, not by a long shot, and you've got no means of locking. This is a very risky thing to do.
For every message you read from the channel, you're currently comparing the file name to a on-the-spot generated name. Wouldn't it be so much easier to move the occasional checking of the file to a routine instead? Just have it generate a new name every Nms, compare and if needed, acquire a lock on the os.File pointer, rotate the log file, and release? Whilst doing that, you'd only need to lock and release the a mutex every time you actually write a message to the log, instead of comparing file names. This has the added benefit that, owing to using a mutex, resolves to a large extent the concurrency problems mentioned earlier.
The risk of using channels for logging: You're using channels to write to a log, instead of writing to a log directly. This clearly suggests the use of routines. Given this, you have to understand that you stand to loose a great deal of logs should your main func return before you've worked through the entire set of messages on the channel. What would happen in that case? You're losing information you were trying to log. Plain and simple. This is unacceptable.
Reinventing the wheel: Logging is something that can be implemented cheaply, and without requiring the use of a mutex, or essentially re-implementing a mature tool like logrotate. Why not write your logs to stdout or stderr, and pipe those streams to a log, that is managed by logrotate for you? KISS


Nice and clean implementation. I tested this with the tests (the new ones) of my implementation and they all passed (skipping the tests with chunkSize == 0).

The code could be sligthly more readable by having some vertical space to group related code, for instance after validating the input.

You could improve this a little bit by just having this

if (chunkSize == 1)
{
    yield return value;
    yield break;
}

after the validation, in this way you wouldn't need to create a StringBuilder nor having the enumerator.

A slightly different approach could be to remove the for loop. It makes the intent more clear (IMO) and removes the need to double check return value of enumerator.MoveNext().

Unfortunately this makes the code 2 lines (3 with the vertical spacing) longer

        var sb = new StringBuilder(chunkSize);
        var enumerator = StringInfo.GetTextElementEnumerator(value);
        var counter = 0;
        while (enumerator.MoveNext())
        {
            counter++;
            sb.Append(enumerator.GetTextElement());
            if (counter == chunkSize)
            {
                yield return sb.ToString();

                sb.Length = 0;
                counter = 0;
            }
        }
        if (counter > 0)
        {
            yield return sb.ToString();
        }

Regarding naming of unit tests, I usually (not in the posted question of mine) use the pattern

UnitOfWork_StateUnderTest_ExpectedBehavior

like shown in the accepted answer over here: unit test naming best practices


file1_path == file2_path surely tells that paths refer to the same file. However, even if file1_path != file2_path they still may refer to the same file.

file1_exists = std::filesystem::exists(file1_path); introduces a TOC-TOU race condition. The file may exist at the time of test, yet disappear by the time of use. See the next bullet.

std::filesystem::rename may fail. You call it tree times. If the second, or third call fails (with an exception!), the filesystem ends up not exactly in a state one would expect. Use a noexcept overload, test the error_code after each call, and roll back all actions prior to failure. That would also automagically take care of the nonexistent paths.

Do not assert. It is only good to catch bugs, not the runtime problems. In the production code (compiled with -DNDEBUG) it does nothing, and your program wouldn't detect an mkstemp failure.

The program silently does nothing if called with, say, 4 arguments. It also takes so much effort if called with 2 arguments. Calling print_help() any time argc != 3 is much more straightforward.


Repositioning images in a gallery based on the current image

Because you have nice, predictable ranges, you don't need a loop at all. Just do a little math.

var thumbGalwidth = 795;

var n = Math.floor(((currSlide || 1)-1) / 5);

jQuery('#view-all-container').css('margin-left', '-' + thumbGalwidth*n + 'px');

If the largest n should be 5, then change the assignment to this:

var n = Math.min(5, Math.floor(((currSlide || 1)-1) / 5));


Calculating golf score against course par

The big thing worth mentioning here is:  Use an array for your scores.

The instant you do that, the code size shrinks dramatically.

$course = array(0, 4, 5, 4, 3, 5, 3, 4, 4, 4, 4, 4, 4, 4, 3, 5, 3, 4, 5);
$scores = array();

// $shots is your array of scores.  $shots[1] is the first hole, $shots[2] the second,
// etc.  If you remove the 0 at the beginning of `$course`, then $scores[0] will be
// the first, $scores[1] the second, etc, which is how arrays often look.  But with
// the zero, you can use the hole number as array index -- which might be more useful
// if these numbers are coming from an HTML form.

foreach ($course as $hole => $par) {
    if (!empty($shots[$hole])) {
        $scores[$hole] = $par - $shots[$hole];
    }
}

$scoresum = array_sum($scores);

if ($scoresum != 0) {
    $score = $scoresum;
}
else {
    $score = 'E';
}

But you could do even better than that, if you don't need those intermediate scores.

$course = array(0, 4, 5, 4, 3, 5, 3, 4, 4, 4, 4, 4, 4, 4, 3, 5, 3, 4, 5);
$score = 0;

foreach ($shots as $hole => $total) {
    if (!empty($total)) {
        $score += $course[$hole] - $total;
    }
}

if (empty($score)) $score = 'E';

And because this seems uncommon knowledge, and will simplify your life if these values are indeed from a form, you can get PHP to build your array for you by giving your inputs arrayish names.  Like so:

<form>
    <input type="text" name="shots[1]">
    <input type="text" name="shots[2]">
    <input type="text" name="shots[3]">
    <input type="text" name="shots[4]">
    <input type="text" name="shots[5]">
 </form>

(You can even leave out the index, if you don't mind the auto-number indexes PHP does.)

When this form is submitted, $_POST['shots'] will be an array of all the inputs.  Do something like:

$shots = array_map('intval', $_POST['shots']);

and you have an array containing the score entered for each hole (or 0 if the entered value didn't make sense as a number).


You can make it shorter by tackling the problem smarter, as in shift or work segments in relation to a DateTime or TimeofDay.  Trying brute force checks of minute-by-minute is a horrifically bad solution.  My answer may point you in the right direction but it is NOT TOTALLY CORRECT FOR ALL POSSIBLE INPUTS.
I would separate the logic into its own class.
public enum Shift { Day, Night }

// CAUTION: this class does not perform validation to make sure end times are after start time, or that
// start and end times are of the same DateTimeKind.
// This does not work for Kind = Local, specifically on fall back or spring forward transition days.
// It does work for Kind = Utc or Unspecified, since they do not observe DST.
public class WorkShift
{

    // A WorkShift may not be complete shift, but rather segments.
    public Shift Shift { get; }
    public DateTime StartTime { get; }
    public DateTime EndTime { get; }

    public WorkShift(Shift shift, DateTime startTime, DateTime endTime)
    {
        this.Shift = shift;
        this.StartTime = startTime;
        this.EndTime = endTime;
    }

    public static readonly TimeSpan NightShiftStart = new TimeSpan(22, 0, 0);
    public static readonly TimeSpan NightShiftEnd = new TimeSpan(6, 0, 0);

    // Shifts have an inclusive start time but an exclusive end time.
    public static bool IsNightShift(TimeSpan timeOfDay) => timeOfDay >= NightShiftStart || timeOfDay < NightShiftEnd;
    public static bool IsDayShift(TimeSpan timeofDay) => !IsNightShift(timeofDay);

    public static bool IsNightShift(DateTime time) => IsNightShift(time.TimeOfDay);
    public static bool IsDayShift(DateTime time) => IsDayShift(time.TimeOfDay);

    public static IEnumerable<WorkShift> GetShiftSegments(DateTime startTime, DateTime endTime)
    {
        var segmentEnd = startTime;
        while (segmentEnd < endTime)
        {
            var segmentStart = segmentEnd;
            var shift = IsNightShift(segmentStart) ? Shift.Night : Shift.Day;
            segmentEnd = GetShiftEndTime(shift, segmentStart);
            if (segmentEnd > endTime)
            {
                segmentEnd = endTime;
            }
            yield return new WorkShift(shift, segmentStart, segmentEnd);
        }
    }

    private static  DateTime GetShiftEndTime(Shift shift, DateTime segmentStart)
    {
        // Nice thing about Day is it occurs on the same date, but Night may crossover midnight into the next date.
        if (shift == Shift.Day)
        {
            return DateTime.SpecifyKind(segmentStart.Date + NightShiftStart, segmentStart.Kind);
        }

        if (segmentStart.TimeOfDay >= NightShiftStart)
        {
            // ending shift would be tomorrow.
            return DateTime.SpecifyKind(segmentStart.Date.AddDays(1) + NightShiftEnd, segmentStart.Kind);
        }

        return DateTime.SpecifyKind(segmentStart.Date + NightShiftEnd, segmentStart.Kind);
    }
}

Now the Main test can become:
static void Main(string[] args)
{
    var startTime = DateTime.Parse("2020-10-26 21:00:00");
    var endTime = DateTime.Parse("2020-10-27 07:00:00");
    Console.WriteLine($"Time Range From {startTime} To {endTime}");

    var workSegments = WorkShift.GetShiftSegments(startTime, endTime).ToList();

    for (var i = 0; i < workSegments.Count; i++)
    {
        Console.WriteLine($"   [{i}] = {workSegments[i].Shift},  Start:{workSegments[i].StartTime}, End:{workSegments[i].EndTime}");
    }

    Console.WriteLine("\nPress ENTER to close");
    Console.ReadLine();
}

Sample console output is:
Time Range From 10/26/2020 9:00:00 PM To 10/27/2020 7:00:00 AM
   [0] = Day,  Start:10/26/2020 9:00:00 PM, End:10/26/2020 10:00:00 PM
   [1] = Night,  Start:10/26/2020 10:00:00 PM, End:10/27/2020 6:00:00 AM
   [2] = Day,  Start:10/27/2020 6:00:00 AM, End:10/27/2020 7:00:00 AM

Press ENTER to close

CAUTIONS AND WARNINGS
A WorkShift instance may or may not represent a complete Day or Night work shift, but instead a segment depending upon the starting or ending time.
As the code comments say, there are no validation checks to ensure that the ending time occurs after the starting time.  Nor are there any checks to ensure that both the starting and ending times have the same DateTimeKind.
I did not check to see if the code works correctly for Local Kind.  My intuition tells me to be suspicious or very leery about it.  However, it should work when Kind is Utc or Unspecified, where neither observe DST and therefore neither will have a 23-hour Spring Forward Day or a 25-hour Fall Back Day.
It is important that both start and ending times belong the the same DateTimeKind when subtracting start from end.  If they belong to different kinds, the time range span may be incorrect.
Even if you are super careful about the Kind, keep in mind that certain operations may return a invalid date and time.  For instance, DateTime.Date returns a value at midnight with the same Kind as the input DateTime.  But if your local time is Brazil (or Brasil), then the Spring Forward transition day does not have a midnight.
There are so many gotcha's with dates, times, and local time zones, that I would urge you to read up on https://nodatime.org/,


Periodically run Bash Job A to conditionally restart Bash Job B based on output of Bash Job A

Is there any neater way I can accomplish the task?

        long_proc.terminate()  # kill Bash Job B

Well, sending SIGTERM is effective, but since you're in control of what Job B runs you might prefer to have it do IPC so it gracefully shuts down after completing a processing phase, rather than being interrupted at some arbitrary point. Could be as simple as creating a sentinel /tmp file that B looks for.

A bigger issue is that you're not doing wait4() child, like this:

        long_proc.terminate()
        long_proc.wait()

Instead you wrote a race with a 5-second delay to encourage the child to win. That long sleep implies wasted idle time. You could run the CPU flat out by synchronizing with exiting child.


Project Euler Problem #102 in F#: counting triangles that contain the origin

It looks OK to me. You can avoid the List.ofArray call, if you change the arguments to intToCoord and containsOrigin to arrays instead of lists:

let intToCoord [|x; y|] = { x = x; y = y }

let containsOrigin [|a; b; c|] =
    twiceTriangleArea a b c = twiceTriangleArea origin a b +
        twiceTriangleArea origin b c +
        twiceTriangleArea origin a c

let solution =
    System.IO.File.ReadLines "p102_triangles.txt"
    |> Seq.map (fun line ->
        line.Split ',' |> Array.map int |> Array.chunkBySize 2 |> Array.map intToCoord
    )
    |> Seq.filter containsOrigin
    |> Seq.length

Update:

You could though "rearrange" the mapping from string to a "triangle" in this way:

let toCoord [|x; y|] = { x = int x; y = int y}

let toTriangle line = (string line).Split ',' |> Array.chunkBySize 2 |> Array.map toCoord

And then change the main function to:

let solution =
    System.IO.File.ReadLines "p102_triangles.txt"
    |> Seq.map toTriangle
    |> Seq.filter containsOrigin
    |> Seq.length

In this way you gain more even abstraction levels in the pipe chain in the main function.


Sequential cohesion

From Code Complete, chapter 7, High-quality routines:

  Sequential cohesion exists when a routine contains operations that must be performed in a specific order, that share data from step to step, and that don’t make up a complete function when done together.

Consider these lines in the code:

printRightDiagonal.readMatrixDimensions();
printRightDiagonal.readInputEntries();
printRightDiagonal.validateInputEntries();
printRightDiagonal.insertIntoArr();
printRightDiagonal.findRDiagonal();

If you reorder these calls, the program will compile, but it won't work correctly. This is undesirable.

Consider this alternative:

Matrix matrix = readMatrix(new Scanner(System.in));
matrix.printRightDiagonal();

Where readMatrix does:

int size = readMatrixSize(scanner);
char[][] data = readMatrixEntries(scanner, size);
return new Matrix(data);

You can guess what readMatrixSize and readMatrixEntries do.
The point is, each function does one thing (functional cohesion),
the relationship between statements is clear,
and reordering the statements will result in compile errors,
protecting you from runtime errors.

Encapsulation

The idea of encapsulation is limiting the scope of low-level details (information hiding), to reduce the mental burden of understanding a program.

All these fields in the class are a mental burden:

private int rowSize;
private int colSize;
private char[][] matrix;
private Scanner scanner = new Scanner(System.in);
private String[] rows;
private String userInput;

They are a mental burden because these variables are accessible in the entire class, so if you want to know where they are read or modified, you have to read the entire program.

The fields rows and userInput are the worst offenders,
because they are only used during input.
They should not be exposed like this to the entire class,
but encapsulated by the input mechanism, hidden from the rest of the program.

Side effects, semantic rules, failure of encapsulation

This method suggests a deep flaw in the program:

private void readInputEntries(){
    System.out.println("Please enter the rows separated by comma. Example if the matrix is a 2x2 enter i/p as ab,cd");
    scanner.nextLine();
    userInput = scanner.nextLine();
}

What is the scanner.nextLine(); doing there?
It's there because in the earlier readMatrixDimensions call,
after reading the matrix dimensions,
the end of line character is not read.
This is a big problem, for several reasons:

Huge burden on the reader. In order to understand the purpose of this line, you have to read the caller of this method, and the calls before this method that affected scanner.
readMatrixDimensions is clearly not doing its job. It leaves the scanner in a state that's not ready for the next use. It forces the rest of the program to understand and remember the low-level details of its implementation.
If you remove this line, the method will look correct, perfectly fine, even though the program will be broken.

The fix is relatively simple. Make sure that methods don't have such invisible rules, hidden dependencies on the implementation details outside of them. In this example, if you move scanner.nextLine() to readMatrixDimensions, this problem disappears.

Usability, logic

There's a mix of usability and logical issues here:

System.out.println("Please enter the rowsize of the 2D array");
rowSize = scanner.nextInt();
System.out.println("Please enter the colsize of the 2D array");
colSize = scanner.nextInt();
if(rowSize!=colSize){
    System.err.println("Cannot find the diagonal of a matrix because the rowsize and column size are different");
    System.exit(0);
}

The messages talk about a 2D array, but that's an implementation detail. The data of a matrix could be stored in a 1D array.
Users don't have to know such low-level implementation details.

The program is designed to work with a square matrix.
So why give the user the opportunity to enter different row and column sizes? Ask to input a single size value. That will effectively prevent the user from entering invalid values.

The validation is insufficient. 0 or negative values will not work out well.

Exiting the program in case of invalid input is not very user friendly.
Consider asking until there is a valid value, for example:

private int readMatrixSize(Scanner scanner) {
    System.out.println("Please enter the size of the matrix");
    int size;
    while (true) {
        size = scanner.nextInt();
        if (size > 0) {
            break;
        }
        System.out.println("The size must be positive. Try again!");
    }
    // read the end of line character
    scanner.nextLine();
    return size;
}

Single responsibility principle

insertIntoArr does two things:

Creates a matrix
Prints the matrix

These should be separated into createMatrix and printMatrix methods.

Naming

findRDiagonal prints the diagonal. There's not much there to "find". So printRightDiagonal would be a better name.

Program control

It's generally a bad practice to call System.exit in methods other than main. This kind of control is best in the main method, there should be no other exit points. If at any point an invalid input occurs, it would be better to throw a custom exception, and let the main method handle it.


For each shape, you have this kind of code to generate the movement "recipe":

axiom = ...
for _ in range(self.num):
    replacement = 'some fixed string'
    axiom = axiom.replace(pattern, replacement)
    axiom = axiom.replace(pattern2, replacement2)

This can be generalized with a helper function that takes as parameters axiom and a list of pattern-replacement pairs. All shapes will be able to use this helper and thereby reduce duplication.

The execution of the movement commands is also repetitive. The code for the most complex shape would be able to draw all the simpler shapes, with a single parameter of the turn degrees.


Calculate the amount of savings I will have in n months

Welcome to Code Review. Few suggestions:

Formatting: the code should be formatted to make it easier to read. Many IDEs support auto-formatting, or you can use an online formatter.
Naming: the class name RetCalcJava shouldn't include Java as suffix, the extension .java already tells what type of file is. It's also hard to understand what a class called RetCalc does, consider a more meaningful name. I am not sure what Boucle means.
Typo and spacing: iniVal, println("intival" + iniVal). There are some typos and the result of the print is "intival1000", it needs a space.
Static method: The method futureCapital does not need to use instance variables, so it can be static. By making it static we don't need to instantiate the class.
Formatting the output: the capital can be formatted as 541,267.20 instead of 541267.1989622512 using System.out.printf and %,.2f.
Accumulation:
iniVal = initialCapital * (1 + interestRate) + monthlySavings;
intermediate = iniVal;
System.out.println("intival" + iniVal);
for (int i = 1; i < nbOfMonths; i++) {
    //...
    finalVal = intermediate * (1 + interestRate) + monthlySavings;
    intermediate = finalVal;
    // ...
}
return finalVal;

The temporary variables intermediate and initVal are not necessary, see the code below.

Revised code
public class RetCalc {
    public static double futureCapital(double interestRate, int months, int netIncome, int currentExpenses,
            double initialCapital) {
        double monthlySavings = netIncome - currentExpenses;
        double capital = initialCapital;
        for (int i = 0; i < months; i++) {
            capital = capital * (1 + interestRate) + monthlySavings;
            if (i == 0) {
                System.out.printf("Initial value: %,.2f%n", capital);
            } else {
                System.out.printf("Month: %d Capital: %,.2f%n", i + 1, capital);
            }
        }
        return capital;
    }

    public static void main(String[] args) {
        double futureCapital = RetCalc.futureCapital(0.04 / 12, 300, 3000, 2000, 10000);
        System.out.printf("Future capital: %,.2f%n", futureCapital);
    }
}

Output:
Initial value: 11,033.33
Month: 2 Capital: 12,070.11
...
Month: 300 Capital: 541,267.20
Future capital: 541,267.20


First of all, having scroll handlers is not the best idea. Usually it kills performance.
If you have no choise - use debounce-like function within - in 99% you do not need explict calls on every move.
Don't use $('smth') within your handler. Save them to variables somewhere before. Do not look for them in your DOM tree on every scroll event.


consec will wrap around and pair the last element of your list as consecutive with the first. This isn't documented in the comment and IMO a little bit problematic. While it lends itself well to the problem you're solving, I'd try to change the implementation of consec a little and being explicit about the cycle property in the name.

Consider:

consec :: [a] -> [(a,a)]
consec [] = []
consec [x] = []
consec (x:xs@(y:_)) = (x,y):consec xs

This implementation has the benefit of being more explicit over zip xs (drop 1 $ cycle xs). It can be trivially extended to a consecCycle like so:

consecCycle :: [a] -> [(a,a)]
consecCycle [] = []
consecCycle [y] = []
consecCycle xs@(x:_) = consec (xs ++ [x])

For what it's worth, this is basically a stylistic call. I'm more prone to overspecifying my functions, avoiding pointfree style. I guess I just dislike oneliners...

make2Tuple is a dangerous one. You're explicitly forcing the function to be called with a list of only two elements by accepting a runtime error of "Non-exhaustive patterns in function make2Tuple".

I'd consider this bad practice. To totally define the function you could consider using a Maybe like so:

make2Tuple :: [a] -> Maybe (a,a)
make2Tuple [x,y] = Just (x,y)
make2Tuple _ = Nothing

this instantly communicates that the function is not totally defined and it avoids a runtime error.

applyToFirst is cleanly written and it clearly communicates intent. Yet I dislike the function because you're using it as a helper for something that's cleaner to implement without it.

split is a weird name for that function, I'd instead use splitWhere or splitIf and supply a predicate, which leads to the following typesignature:

splitWhere :: (a -> Bool) -> [a] -> [[a]]

which can then be implemented as follows:

splitWhere :: (a -> Bool) -> [a] -> [[a]]
splitWhere _ [] = [[]]
splitWhere p ls = go [] ls
    where
        go accum (x:xs) = if p x then accum:go [x] xs else go (accum++[x]) xs
        go accum [] = [accum]

The advantage of this implementation is in the use of an "accumulator" instead of the applyToFirst you're using to achieve the same functionality.

It's also a tad easier to grasp, IMO, but YMMV

stringToInts is map read . words. Note that without an explicit type-signature GHCI can not infer the correct type, since read is not specified out enough.

Unfortunately this makes the work put into applyToFirst and split unnecessary :(

I'd simplify euclideanDistance's pattern by splitting up the tuple of tuples into separate parameters. To keep in line with how it's invoked you can then adjust computePerimeter to uncurry it like so:

computePerimeter xs = sum $ map (uncurry euclideanDistance) (consec xs)

Finally I find it hard to keep track of how your main works. It's probably easier to rewrite this as a do like so:

main = do
    vertices <- getLine
    polygon <- replicateM (read vertices) getInt2Tuple
    print $ computePerimeter (map fromJust $ filter isJust polygon)

This is IMO significantly easier to follow than your oneliner (and it also avoids all the fmap

Zeta noted that the last line can be shortened (and secured a bit) to:

print $ computePerimeter $ catMaybes polygon

Note that I've added the following imports and changed the getInt2Tuple signature to be an IO (Maybe (Int, Int)) instead:

import Control.Monad(replicateM)
import Data.Maybe(fromJust, isJust)


Tidying and deduplicating files listed in a DataGridView

I found some code that you could tidy up a bit right here

    j = FileNames.Count
    i = 0
    Do
        str = FileNames(i)
        If str.Contains("-00-") Then
            FileNames(i) = RemoveChar(str, "-00-") ' RemoveChar is a function that replaces "-00-" with a "-"
        End If
        i += 1
    Loop Until i = j

that seems like a lot of work for such a simple task.

use a for loop that goes from the base index to the FileNames.Count value.

Then use a Replace instead of creating a function that does a replace.  here is some code that does the same thing

keep in mind that a replace will only replace a string that it can find, so you don't have to check for the substring in your string before you call the Replace function on the string.

For i As Integer = 0 To FileNames.Count
    FileNames(i).Replace("-00-", "-")
Next


Saving a subscription plan with a payment

Some notes about your code:

Indentation of a call with multi-line hash: That's subjective, but this style you use wastes a lot of space, and it's pretty hard to read (because of the longer lines). If the hash is long I prefer to use the one-line-per-key/value JSON style. More on this here.
self.stripe_charge_id = charge.id: When you have a lot of sets + save! it is better just to use update_attributes!.
save!: The method is named save_with_payment, in a ActiveRecord context that means this method won't raise an exception, so you should call save.
if valid?: No else branch? The method seems to return a boolean so returning false in that case would be more consistent.
rescue Stripe::InvalidRequestError => e: That's a long and subjective topic. My opinion: don't wrap a whole method that is doing lots of things with a rescue, the logic forms now some kind of spaghetti. Wrap the specific parts of the code that may raise that particular exception.
Stripe::Charge.create: You asked if the code is too complex. I don't think so, at least not compared with typical Ruby practices, but it's probably more orthodox to create a separate method for this call.
errors.add :base,: I don't like this mixing of calls with parens and calls without, it looks messy. DSL-style code in Rails without parens -> ok, normal code in methods -> not so sure, I'd write them. Or at least be consistent.
self.plan: It's not idiomatic to write explicit self. to call instance methods.

I'd write:

def save_with_payment
  if !valid?
    false
  elsif !(charge = create_stripe_charge)
    errors.add(:base, "There was a problem with your credit card.")
    false
  else
    update_attributes({
      :stripe_charge_id => charge.id,
      :starts_at => Date.today,
      :amount => plan.price,
      :expires_at => 1.years.from_now,
    })
  end
end

def create_stripe_charge
  Stripe::Charge.create({
    :amount => (plan.price * 100).to_i,
    :currency => 'usd',
    :card => stripe_card_token,
    :description => "Charge for #{user.email}",
  })
rescue Stripe::InvalidRequestError => e
  logger.error("Stripe error while creating charge: #{e.message}")
  nil
end


I think you would be better off using set. It provides features like set difference by itself, thereby reducing a lot of work at your end:
set_one = set([('id_01','aaa','bbb'), ('id_02','aaa','bbb'), ('id_03','aaa','bbb'), ('id_04','aab','bbc')])
set_two = set([('id_01','aaa','bbb'), ('id_02','aaa','bbb'), ('id_03','aad','bbd')])
for difference in (set_two - set_one):
    print(f"There is a difference on {difference[0]} between the two lists")


It's basically like RubberDuck said.

  [...] the only action I want to expose for this class is the import functionality.

This means the validation logic is an implementation detail of the TestImporter class. When you test a unit, you only care about the public interface, and treat private members (which are called by the public ones) as implementation details; not testing them directly is fine, unless you do want to test that logic separately...

  How should I design this class in order to test my validation of Excel inputs?

So you want to test the validation logic? Great! Treat it as a unit then (as opposed to an implementation detail), and extract it into its own class.

You will want to decouple the validation logic from the TestImporter class though, and it's easier to do that if you code against an abstraction. Make a TestImporter constructor inject the dependency:

Private ReadOnly HeaderValidator As IHeaderValidationLogic

Public Sub New(validator As IHeaderValidationLogic)
    HeaderValidator = validator
End Sub

Now, instead of calling validateAll, you call into the IHeaderValidationLogic interface:

validationErrors.AddRange(HeaderValidator.Validate(sheet))

But this creates another problem: does the validation logic really needs to be coupled with an ExcelWorksheet object? What if you switched to the VSTO interop assemblies and worked off a Microsoft.Office.Interop.Excel.Worksheet object instead, would the logic be any different?

Best would be to abstract away that "worksheet", and make the validation logic work off what it actually validates: the contents of the worksheet.

Extract the values of range $A$1:$E$1 into an array, and pass that array (of strings?) to your header validation logic. Assuming we're returning a list of error messages, the IHeaderValidationLogic interface could look like this:

Public Interface IHeaderValidationLogic
    Function Validate(headerContents As IEnumerable(Of String)) As IReadOnlyList(Of String)
End Interface

Now, returning a list of error messages isn't very .NET-like. Why not do this instead?

Public Interface IHeaderValidationLogic
    Sub Validate(headerContents As IEnumerable(Of String))
End Interface

And then the implementation can throw some ValidationException, with whatever string content you want it to have.

And that exception would bubble up the stack to Import(fileName As String), which could now be a Sub - because again, returning errors isn't very .NET-like.

Note that your method names should be PascalCase, to follow the established VB.NET naming conventions.

If you're going to want to write a unit test for the actual Import procedure, you'll need to reduce coupling - otherwise your tests will incur I/O, which slows them down and makes them dependent on the file system, which isn't ideal.

Extract another interface.

Public Interface IExcelPackageProvider
    Function Open(fileName As String) As ExcelPackage
End Interface

Now you can mock this interface and make the Open method return a stub ExcelPackage with a fake ExcelWorksheet object that you've setup for your tests, and as a side-effect of doing this, you've extracted a highly specialised and reusable component from your Import procedure, making the class more cohesive and a little less coupled.

Private ReadOnly WorkbookProvider As IExcelPackageProvider
Private ReadOnly HeaderValidator As IHeaderValidationLogic

Public Sub New(provider As IExcelPackageProvider, validator As IHeaderValidationLogic)
    WorkbookProvider = provider
    HeaderValidator = validator
End Sub

It's now the job of WorkbookProvider to deal with file I/O and return a workbook object for the Import method to work with.


Frequency analysis based anagram checker

Avoid magic numbers, especially if they, like 26 in your code, are used repeatedly. Along the same line, keep in mind that the code only works in the "C" locale. Other locales may have alphabets of different size.
Prefer to declare variables as close to use as possible, e.g.

    for (size_t i = 0; i < l1; ++i) {
        int index1 = s1[i] - 'a';
        int index2 = s2[i] - 'a';
        ....

If the string contains non-lowercase characters, the code would do an out-of-bound access. You should ensure islower(s[i]) prior to computing indices, and ask the interviewer about what are the guarantees.
An opportunistic if (l1 != l2) return 0; is not an optimization. It still require a linear time to compute the lengths.
Along the same line, length computation is not necessary. An idiomatic C approach is to us pointers:

while ((ch = *s++) != 0)

The bullets above suggest splitting the loop into two:

while ((ch = *s1++) != 0) {
    if (islower(ch)) {
        alphabet[ch - 'a']++;
    }
}

while ((ch = *s2++) != 0) {
    if (islower(ch)) {
        alphabet[ch - 'a']--;
    }
}

Now, a DRY principle require factoring this loops into a function:

static void count_frequencies(char * s, int * alphabet, int addend) {
    while ((ch = *s++) != 0) {
        if (islower(ch)) {
            alphabet[ch - 'a'] += addend;
        }
    }
}

....
    count_frequencies(s1, alphabet, 1);
    count_frequencies(s2, alphabet, -1);

As a perk benefit, see how the /* count the frequencies of characters */ disappears.
For a very long string the integer in alphabet may overflow. Could be a nitpick, but could also be a failure, depending on the interviewer.


Translate datetime format from one standard to another

The strftime function is relatively well known, even if the formatting directives are not completely standardized across platforms.  On the other hand, pickadate.js is a relatively unknown library.  It would therefore be helpful to cite its specification, preferably in a docstring.  The use of doctests would also be a good idea here.

According to the pickadate.js documentation, you should escape any “rule” characters with an exclamation mark (!).

Doing string substitutions in multiple passes is, in general, a bad idea.  Not only is it more work to traverse the string several times, there is also the possibility that operating on the output leads to incorrect results.  Fortunately, you seem to be safe here, since the pickadate.js directives don't start with % like the strftime directives.  Still, a one-pass solution is preferable, and Python gives you a way to do that with re.sub():

  re.sub(pattern, repl, string, count=0, flags=0)

    …

    If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.

Using re.sub(), and handling special cases where strings that appear to be strftime and pickadate.js directives should actually be treated literally…

import re

def format_to_pickadate_format(fmt):
    """
    Convert a strftime format string to a pickadate.js template.
    http://amsul.ca/pickadate.js/date/#formats
    http://amsul.ca/pickadate.js/time/#formats

    >>> format_to_pickadate_format('%d/%m/%Y %H:%M')
    'dd/mm/yyyy HH:i'
    >>> format_to_pickadate_format('%Y %% d')
    'yyyy % !d'
    """
    TRANS = {
        '%d': 'dd',
        '%a': 'ddd',
        '%A': 'dddd',
        '%m': 'mm',
        '%b': 'mmm',
        '%B': 'mmmm',
        '%y': 'yy',
        '%Y': 'yyyy',
        '%H': 'HH',
        '%M': 'i',
        '%p': 'A',
    }
    return re.sub(
        r'%(.)|([^dmyhHiaA])|(.)',
        lambda m: TRANS.get(m.group(), m.group(1)) or m.group(2) or '!' + m.group(3),
        fmt
    )


I wouldn't call your implementation insertion sort as it's sorting in place using swaps, which as David pointed out makes it look more like a bubble sort.  An insertion sort sorts by building up a new list and inserting items into the proper place.  A very crude first pass at an insertion sort might look like:

def insertion_sort(unsorted_list):
    result = []
    for n in unsorted_list:
        inserted = False
        for i in range(len(result)):
            if n < result[i]:
                result.insert(i, n)
                inserted = True
                break
        if not inserted:
            result.append(n)
    return result

This could be greatly improved for larger data sets by making the inner search take advantage of the fact that s is sorted and doing a binary search for the insertion point.  Of course, this being Python, the whole mess could be optimized to sorted(unsorted_list). ;)


Here's the most elegant way I can think of writing this. I use transform to handle both Arrays and Objects as your tests showed you wanted to support them, though as pointed out in comments your code didn't.

These changes also allow you to use more than 2 pick properties (pickDeep(set, 'a', 'b', 'c', ['d', 'e'])) as you can with the normal pick/omit.

For lodash 3 and underscore 1.8? you'll need to change _.createCallback to _.iteratee the rest of the code should remain the same.

function pickDeep(collection, predicate, thisArg) {
    if (_.isFunction(predicate)) {
        predicate = _.createCallback(predicate, thisArg);
    } else {
        var keys = _.flatten(_.rest(arguments));
        predicate = function(val, key) {
            return _.contains(keys, key);
        }
    }

    return _.transform(collection, function(memo, val, key) {
        var include = predicate(val, key);
        if (!include && _.isObject(val)) {
            val = pickDeep(val, predicate);
            include = !_.isEmpty(val);
        }
        if (include) {
            _.isArray(collection) ? memo.push(val) : memo[key] = val;
        }
    });
}

This also fixes a the need to check pickDeep({a: [{a: 1}]}) twice to add it to the picked object


change space to underscore in filename using C

Although this indeed does something similar to your goal, here are some criticisms / improvements:

There's absolutely no need to take a copy of the original filename.
If you meet an error condition, return 1 (or better EXIT_FAILURE from stdlib.h), so scripts calling your tool get a chance to detect the error.
Use functions; this helps your code to keep structure
Your tool will not work correctly for filenames with paths, so better search from the end and stop replacing when you hit a path separator character.
When iterating through a string, it's often easier to just use pointers instead of array indexing.

I'd suggest something like this:

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

#ifdef _WIN32
#define isPathSep(x) ((x) == '\\' || (x) == '/')
#else
#define isPathSep(x) ((x) == '/')
#endif

char *sanitizeFileName(const char *filename)
{
    size_t namelen = strlen(filename);

    char *sanitized = malloc(namelen + 1);
    if (!sanitized)
    {
        perror("malloc");
        exit(EXIT_FAILURE);
    }

    strcpy(sanitized, filename);

    char *p = sanitized + namelen - 1;
    while (p >= sanitized)
    {
        if (isPathSep(*p)) break;
        if (*p == ' ') *p = '_';
        --p;
    }

    return sanitized;
}

int main(int argc, char **argv)
{
    if (argc != 2)
    {
        fprintf(stderr, "Usage: %s [filename]\n", argv[0]);
        return EXIT_FAILURE;
    }

    char *safename = sanitizeFileName(argv[1]);

    // instead of rename(), for demonstration:
    printf("%s -> %s\n", argv[1], safename);

    free(safename);

    return EXIT_SUCCESS;
}


Chaining 3 dependent HTTP request subscriptions one, which is polling

First of all, you are using some kind of C# code style in your typescript. I suggest the ng lint command-line to conform with typescript/angular code style. Moreover prefixing interfaces with I is not a typescript convention (https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines).

I think the difficult part of your code with rxjs is how to know which room we have to update when we receive a status.

I find a way to keep track of the room without changing the api of the floorService via zipping the observables returned by the floorService with an observable containing the room.

Here is a proposal with rxjs, I tried to fill the blanks in your posted code to make it run so focus on the zipWithRoom function and the onChange method:

the component with the dropdown:

import { Component } from '@angular/core';
import { FloorService } from './floor.service';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/zip';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/from';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/filter';

export interface IRoom {
  roomId: number;
}

export interface IDevice {
  deviceId: number;
}

export interface IStatus {
  occupied: string;
}

function zipWithRoom<T>(observable: Observable<T>, theRoom: IRoom) {
  return Observable.zip(observable, Observable.of(theRoom), (result: T, room: IRoom) => ({result, room}));
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  selectedFloor;
  rooms: { [roomId: number]: Array<String> };

  constructor(private floorService: FloorService) {
  }

  onChange(floor: any) {
    this.selectedFloor = floor;

    this.floorService.getRoomsInFloor(floor)
    // we create a sequence from the room array
      .mergeMap((rooms: Array<IRoom>): Observable<IRoom> => Observable.from(rooms))
      .mergeMap((room: IRoom) =>
        zipWithRoom<IDevice>(this.floorService.getDeviceInRoom(room.roomId), room))
      .mergeMap(({result, room}) =>
        zipWithRoom<IStatus>(this.floorService.getLatestStatusOfDeviceInRoom(result.deviceId), room))
      .filter(({result, room}) => !!result)
      .subscribe(({result, room}) => {
        // little change to the following line to make it more readable
        this.rooms[room.roomId][4] = result.occupied === 'true' ? 'red' : 'green';
        this.renderRooms();
      });
  }

  private renderRooms() {
  }
}

spec file:

import { TestBed, async } from '@angular/core/testing';

import { AppComponent } from './app.component';
import { FloorService } from './floor.service';
import { Observable } from 'rxjs/Observable';

describe('AppComponent', () => {

  const mockedFloorService = jasmine.createSpyObj(['getRoomsInFloor', 'getDeviceInRoom', 'getLatestStatusOfDeviceInRoom']);

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
      providers: [
        {provide: FloorService, useValue: mockedFloorService}
      ]
    }).compileComponents();
  }));

  it('should update the status of the rooms', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;

    app.rooms = {
      1: [],
      2: []
    };

    mockedFloorService.getRoomsInFloor.and.returnValue(Observable.of([{roomId: 1}, {roomId: 2}]));
    mockedFloorService.getDeviceInRoom.and.returnValues(Observable.of({deviceId: 11}), Observable.of({deviceId: 12}));
    mockedFloorService.getLatestStatusOfDeviceInRoom.and.returnValues(
      Observable.of({occupied: 'true'}),
      Observable.of({occupied: 'false'})
    );

    app.onChange(2);
    expect(mockedFloorService.getRoomsInFloor).toHaveBeenCalledWith(2);
    expect(app.rooms[1][4]).toBe('red');
    expect(app.rooms[2][4]).toBe('green');
  }));
});


Almost always auto. Only write down the specific type when you have to, it's shorter, clearer, and less error-prone.

You currently handle an empty list as a special case. Don't, it's neither efficient nor elegant.
Instead, use a pointer to pointer, and everything is simplified. As an example:

void push_back(const Type& data) {
    auto p = &head;
    while (*p)
        p = &(*p)->next;
    *p = std::make_unique<Node<Type>>(data);
}

Good of you to avoid recursive descent in the dtor. But, you know that's not spelled destroy()?


Inserting robot moves into an SQLite3 database

Just a philosophical answer here.

I think you're asking the wrong question. You shouldn't ask yourself "is my SQL code safe or vulnerable?" This is too hard to answer in any individual case, and coming up with the right answer could depend on a lot of contextual things such as the system configuration, the whole program structure, etc.

You don't want to have to consider all these things when writing code. People have already considered them a lot, and based on their experience they have come up with best practices.

Instead you should ask the question,

  Does my code follow the standard best practices for preventing SQL injection?

As alluded to in another answer, using string interpolation to build queries is against best practices. So, while it doesn't seem like this creates a vulnerability in your code, we can't rule out that there is some edge case based on the rest of your program structure that would allow an attacker to put something into this string interpolation.

Unless you have a very good reason for doing so, follow the best practices, even if you don't need to. Then you can sleep well and ignore pathological edge cases.


A character array of arbitary length with 'R', 'B', 'W' is needed to be sorted in that order

Don't bother swapping.  Just do a counting sort!

public static void sort(char[] arr) {
    // Count occurrences of each letter
    int r = 0, b = 0, w = 0;
    for (char c : arr) {
        switch (c) {
          case 'R': r++; break;
          case 'B': b++; break;
          case 'W': w++; break;
          default: throw new IllegalArgumentException();
        }
    }

    // Write out the appropriate repetitions of each letter
    int i = 0;
    while (r-- > 0) arr[i++] = 'R';
    while (b-- > 0) arr[i++] = 'B';
    while (w-- > 0) arr[i++] = 'W';
}

Not only is the code easy to understand, it's also gentle to the cache since you always proceed linearly down the array.


Parallax animation running well on Chrome but slow on Safari

parallaxElements = [];

// Push elements to array
s.parallaxElements.each(function (i) {
  var i = {
    element: $(this),
    ratio: $(this).data('parallax-ratio'),
    offset: $(this).closest('.parallax-section').offset().top - 60,
    current: 0
  };

  parallaxElements.push(i);
});

This looks like transforming one array to another on a 1:1 basis. This is best done with array.map. Also, you should cache the result of $(this) so that you don't call it repeatedly. Additionally, this inside a jquery.each is the current item, which should be the same as the first argument in array.map's callback.

var parallaxElements = s.parallaxElements.get().map(element => {
  const wrappedElement = $(element);

  return {
    element: wrappedElement,
    ratio: wrappedElement.data('parallax-ratio'),
    offset: wrappedElement.closest('.parallax-section').offset().top - 60,
    current: 0
  };
});

Now for your animation, I suggest you avoid using requestAnimationFrame in this case. It will still be running even when no position changes are taking effect, eating up cycles.

Since your parallax effect only takes place only when scroll position has changed, I suggest you listen for the window's scroll event and do changes when scrolled. As for the movement animation, use CSS transitions.

$(window).scroll(event => {
  // Update element positions using transform translate
});

.parallax-element{
  transition: transform 0.2s;
}


Rating tennis players in a database, taking days to run

Without knowing what your csv file is structured, it is hard to give too much concrete.  I do have some suggestions, however.

You can most likely drastically increase performance by converting strings like the player names to categorical data.  Strings are slow in pandas, especially string lookup in a large column (as you have here many times).  Using categeorical data converts it to integers seamlessly behind-the scenes, so you can benefit from using strings while still have fast lookups.
You should loop over the rows rather than re-indexing so much.  In fact all you really need is the winner name and loser name from each match, which you can get at the beginning of each loop.
You may not be able to calculate the Rating all at once, but you can calculate Number of Games all at once by just counting how many times a player is a loser and adding that to how many times the same player is a winner.
Your other functions are one-liners.  This is probably a small part, but it would be better to not have them as functions at all.