Tonelli-Shanks algorithm implementation of prime modular square root

Good job! I don't have a lot to comment on in this code. You have written straightforward clear code whose only complexity stems directly from the complexity of the operation it is performing. It would be good to include some of your external commentary (such as the renames of R and n) in the code itself to make it easier for someone to follow the documentation on wikipedia. You may want to include some of that documentation as well.

For reference, the rest of this review assumes that the code functions correctly; I don't have my math head on tonight.

There appears to be one case of redundant code, unless m can ever be 1, resulting in an empty range and thus no reassignment of i. Otherwise you can skip the assignment to i in the following:

i, e = 0, 2
for i in xrange(1, m):
    ...

There are a number of small strength-reduction optimizations you might consider, but in Python their impact is likely to be minimized - definitely profile before heading too deeply down the optimization path. For example in the following while loop:

# Factor p-1 on the form q * 2^s (with Q odd)
q, s = p - 1, 0
while q % 2 == 0:
    s += 1
    q //= 2

Both operations on q can be reduced. The modulus can be rewritten as a binary and q & 1, and the division as a binary shift q >>= 1. Alternately, you can use divmod to perform both operations at once.

Similarly, 2**(m - i - 1) is identical to 1 << (m - i - 1) for non-negative exponents.


Using reference to head node while reversing linked list using recursion

Extra variable unnecessary

Your variable current in the first code snippet is assigned to head and never changes, so it is unnecessary.  You can just use head directly instead, as in the second code snippet.  Therefore I feel the second version is superior.

Iterative version

Consider using an iterative version to reverse the list instead of a recursive version.  An iterative solution uses \$O(1)\$ space instead of \$O(n)\$ space, and is much easier to understand as well.  All you need to do is take each element of the list and add it to the head of a new list, like this:

public static List ReverseList(List head)
{
    List newHead = null;

    while (head != null) {
        List next = head.next;

        head.next = newHead;
        newHead   = head;
        head      = next;
    }
    return newHead;
}


Pandas calculations per columns and per rows for very big datasets

One quick and obvious improvement is possible in these two lines:

denominator = denominator_df.sum(axis=1).values.tolist()
denominator = sum(denominator)-len(denominator)

This is equivalent to:

denominator = denominator_df.sum(axis=1)
denominator = denominator.sum() - len(denominator)

which should be a lot faster since converting to a temporary list will be quite slow, as is summing using the Python built-in instead of using the pandas vectorized method.

Since you only care for the count in the numerator case, just use sum:

numerator = (denominator_df[peer] == 1).sum()

Note that checking for denominator_df[base] == 1 is unnecessary since that was already done in the construction of denominator_df.

But the real speed gains are probably in eliminating the double for loop altogether and writing this using vectorized methods. With some example input that might be possible.


// Good: Object properties are in a logical order
// (alphabetical order isn't always best)
this.state = {
  cellRows: generateRandomCellDistribution({height: 50, width: 50}),
  size: {height:50, width:50},
  gameState: 'playing',
  speed: 1,       // This property should be on its own line like the rest.
  generation: 0
};

// Style should be consistent (Source: Code Complete)
// Object properties on their own lines like above
// (even as parameters).
componentDidMount() {
  this.setState({
    gamteState: 'playing',
    // No magic numbers (Source: Code Complete)
    // Why 200/speed? What does that represent?
    // Assign a variable above like var tickSpeed = 200/this.state.speed
    // Something to explain why you're doing the division.
    // Even better would be to put that in another function
    // to be used in all places you do this conversion.
    interval: setInterval(this.stepGame, 200/this.state.speed)
  });
}

// Function name should describe what the function does
// (rather than what triggers it) (Source: Code Complete)
squareClicked(row, column)  -->  handleClickInSquare(row, column) or updateStateForCell(row, column)

// Same here. Function doesn't just return a random grid,
// it changes the grid to be a random grid (affects state).
generateRandomGrid()  -->  setGridToRandomGrid() or randomizeGrid()

// This one is pretty good, but toggle usually refers to
// something with two options like Caps Lock (Source: Google define).
// This is tricky and you might think up an even better name that
// includes the facts that you're increasing the speed, there are
// several options, and it wraps around back to the first option.
toggleSpeed()  -->  cycleSpeed(), increaseSpeedOrWrap(), or selectNextFasterSpeed()

// It's better to select clear iterators although it's not
// uncommon to see i, j, and k. Not sure what q is, though.
// How about i --> row, q --> cell. (Source: Code Complete)
// I've changed the code to demonstrate my suggestions.
// I also recommend using currentCellGrid or similar
// to make it clear that you have a 2D array.
for(var row = 0; row < currentCellGrid.length; row++) {
  // Here you could add a variable to clarify what currentCellGrid[row] is.
  // Use more variables to document what the code is doing.
  // (Source: Code Complete)
  var currentRowCells = currentCellGrid[row];
  for(var cell = 0; cell < currentRowCells.length; cell++) {
    newCellGrid[row][cell].state = getNewState(currentRowCells[cell].state, getAliveNeighbours(currentCellGrid, row, cell));
  }
}


Get property value from object tree in a recursive way

Given the map() function used at the question having the same signature as jQuery.map() function used at the question, in order to avoid chaining .filter() to get the value at index 0 of the returned, you can use destructuring to assign id to the value at index 0 of the array returned from the function.

function getIdConditionValue(cond) {
  if (Array.isArray(cond.and)) {
    return $.map(cond.and, getIdConditionValue);
  } else if (Array.isArray(cond.or)) {
    return $.map(cond.or, getIdConditionValue);
  }
  if (cond.id) return cond.id;
}

var condition = {
  or: [{
    and: [{
      id: 3
    }, {
      pageId: '1'
    }]
  }, {
    age: 10
  }]
}

const [id] = getIdConditionValue(condition);

console.log(id);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>

For Loash and Underscore signatures of map() signature (each library's _.map() returns an array having two elements, the fist is the expected result, the second undefined)  you can use

const [[id]] = getIdConditionValue(condition);

For an alternative recursive solution you can create a function that accepts an object and a property name for parameter, utilizes the recursive replacer function of JSON.stringify() and JSON.parse(). If the property name is found during recursive iteration of property names of the object passed, a parameter of an immediately invoked arrow function declared as undefined is set to the property value, else undefined is returned from the function.

const condition1 = {and: [{id:3}, {pageId:'1'}]};
const condition2 = {or: [{and: [{id: 3}, {pageId: '1'}]}, {age: 10 }]};
const condition3 = {and:[,,]};
const condition4 = {and:{or:[]}};
const condition5 = {or:[{or:[{id:1}]}]};

const getObjectPropertyValue = (o, prop) => (result =>
  (JSON[typeof o === 'string' ? 'parse' : 'stringify'](o, (key, value) =>
    key == prop ? (result = value) : value), result))(void 0);

let prop = 'id';

const id1 = getObjectPropertyValue(condition1, prop);

console.log(id1);

let condition2json = JSON.stringify(condition2);

const id2 = getObjectPropertyValue(condition2json, prop);

console.log(id2);

const id3 = getObjectPropertyValue(condition3, prop);

console.log(id3); // `undefined`

const id4 = getObjectPropertyValue(condition4, prop);

console.log(id4); // `undefined`

const id5 = getObjectPropertyValue(condition5, prop);

console.log(id5);


Project Euler - Smallest multiple (Ruby)

Array provides lcm() which gives you the least common multiple of two numbers. You can apply this to an entire array by applying it to each result as you go through it. This is what reduce does.

puts (1..20).reduce{|m,n| m.lcm(n)}

or even shorter:

puts (1..20).reduce(:lcm)

Because most of the calculations are done in the ruby implementation (e.g. C for MRI), this will be fast.


Algorithm for motion detection using ultrasonic sensor on Arduino

Late or spurious echoes
One thing that can happen is that during one ping interval of 50ms you can get echoes from objects up to 8.5m away (0.05[s] *354[m/s] / 2 ). If the object is a little further than that, say 9m, you will get the echo early during the next ping period instead.
As you can guess, this would be bad, it would wrongly appear as being a close echo while it in fact is distant. I'm not familiar with the strength of the ultrasonic on your chip; 8.5m may be out of range in which case this isn't the problem. But if it isn't then your library should send each ping request with a different frequency and check the frequency of the echo to know if you got the right echo, it should also check the amplitude of the echo for feasibility. Again I don't know if your library does any of this but you should check. Otherwise this might be causing your troubles. If 8.5m is just on the edge of the range it is conceivable that some times you get the echo and some times you don't.
Filtering
If you can rule out the above and you're certain your implementation is not at fault, then you can simply assume that it's a transient at work. They happen when dealing with sensors, and sound is finicky that way with echoes and everything.
Best way to deal with transients is to use some kind of filtering. Median might work well for you and I see that NewPing has a "ping_median" function, try this with a filter size of maybe 5 or thereabouts see if that helps.
Variance
Using two samples to estimate any kind of variance is way too little, the result is not in any way reliable. You are also very sensitive to transients and errors are you are calculating the square of the values. I would suggest another approach.
Another approach
If you want to detect movement you want to detect changes in the echo delay. So what you do is setup your timer to consistently ping at a fixed rate then keep a low pass filtered running average of the echo delay and look at the differential of this (the rate of change).
Some pseudocode:
float g = 0.9f
float avg_time = max_time
float avg_dt = 0.0f
float dt_hysteresis = 0.01f
for each 50ms
   if no echo for 10 iterations
      avg_time = max_time
      continue

   float echo_time = sensor.read()

   if avg_time == max_time
       avg_time = echo_time
       avg_dt = 0.0f
   else
       float prev_avg_time = avg_time;
       avg_time = avg_time * g + (1.0f - g) * echo_time
       avg_dt = avg_dt * g + (1.0f - g) * (avg_echo_time - prev_avg_time);

   if avg_dt < -dt_hysteresis
       // Some one approaching
   else if avg_dt > +dt_hysteresis
       // Some one leaving
end for

Explanation
g is a filter coefficient between 0 and 1.0, the higher it is the more "inert" your filter will be. It will be slower to react but be highly resistant to noise. If g is low the filter will react quickly but also more susceptible to noise, to put it simply. You can think of it as a low-pass filter where g implicitly controls the cut-off frequency. Normal values are in the range 0.7 to 0.95.
Every 50 ms you send out a ping and look for the echo. If you don't get an echo for 10 iterations or so, simply reset the avg_time variable so that you can start fresh the next time you get an echo and not be affected by what happened to be stored there since the last echo.
If you get an echo you low pass filter it with avg_time = avg_time * g + (1.0f - g) * echo_time and then look at the lowpass filtered change in the lowpass filtered time value avg_dt = avg_dt * g + (1.0 - g) * (avg_echo_time - prev_avg_time). If this change is larger than +- the hysteresis threshold dt_hysteresis you then deduce that some one is approaching or moving away from the sensor. You can also consider looking directly at avg_echo_time - prev_avg_time the extra lowpass filtering is simply to get rid of noise which is always present when we differentiate a real signal.
Hope this was of some help :s


Yes there is a solution. The obvious solution is of course to use loops.
Here is my try using a composite dictionary. It is functionally equivalent to your code and will save you about a dozen lines but hopefully adds flexibility. This was a quick job, so maybe you can take it further.

from PyQt5.QtWidgets import *
import sys

class ButtonWidget(QWidget):

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

        groups = {"Left Group": ("Sinus", "Cosines"),
            "Middle Group": ("Red", "Green"),
            "Right Group": ("Solid", "Dashed")
        }

        # Main Group
        main_group = QGroupBox("Main Group")
        main_group_layout = QHBoxLayout()

        # loop on group names
        for group, buttons in groups.items():
            group_box = QGroupBox(group)
            group_layout = QVBoxLayout()
            for button_text in buttons:
                group_layout.addWidget(QRadioButton(button_text))

            group_box.setLayout(group_layout)
            main_group_layout.addWidget(group_box)

        main_group.setLayout(main_group_layout)

        # Widget
        main_widget = QWidget()
        main_widget_layout = QVBoxLayout()
        main_widget.setLayout(main_widget_layout)
        main_widget_layout.addWidget(main_group)
        # Layout Set
        self.setLayout(main_widget_layout)

        self.show()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    ui = ButtonWidget()
    sys.exit(app.exec_())

NB: you'll probably have to add names to the generated controls (the buttons at least).

PS: personally I use the QT designer to build forms unless I need a highly dynamic layout. Adding controls in code is tedious and less visual.


Not too many things to remark.

I'll review regarding this assumption : Stack is to be viewed as a Stack datastructure, only peek, pop, push, size and isEmpty are to be used. The fact that java.util.Stack is also a List is not to be exploited.

The sort() methods structure falls into three cases size is 1, size is 2, and size is greater than 2. It would help readability to extract the second and third case as separate methods :

public static <E extends Comparable<? super E>> void sort(final Stack<E> stack) {
    if (stack.size() < 2) {
        // Trivially sorted.
        return;
    }

    if (stack.size() == 2) {
        sortSize2Stack(stack);
        return;
    }

    sortLargerStack(stack);
}

For the size two stack case you can avoid popping the second element if it's greater than the first.
These variables are used only once each :

final int size = stack.size();
final int auxStackLength = size / 2;

They should be inlined.
Help from the java libraries could be avoided here by rolling your own reverse method (I guess it just fell outside the focus of the exercise for you)

Collections.<E>reverse(aux1);
Collections.<E>reverse(aux2);

You could merge in reverse order, and call reverse only once, on the merged stack. To me that seems more readable, but it's a judgement call I guess.


Your code only works for small values of N. The algorighm is effective, but unfortunately your overflows are real.

Factorial numbers get very big, very fast... I think it is around 12! that you run out of space in a 32-bit integer, and about 20! that your run out of space in a 64-bit long.

You need to convert your logic to use BigInteger instead of Long for it to work at all.


c# Converting from one object to another without using foreach

You can use the LINQ syntax:
var studentInfo =
    (from student in result
     select new StudentSystemRecordRequest
        {
            FirstName = student.FirstName,
            LastName = student.SurName,
            DateOfBirth = student.DateOfBirth,
            Address = student.Address1
        }
    ).ToList();

If you are happy with IEnumerable instead of List, you can omit ToList(), but keep in mind that in that case the resulting enumerable will be lazy, which means that the elements will be created only when the result is enumerated. But since result is probably a list, which is strict, it should not be a problem.


Neat idea.
template<typename T1, template <typename> typename Container, typename T2>
bool contains (Container<T1> const &source, T2 const &val)

I’m not sure a template template parameter is necessary here, or even a good idea. It prevents the function from being used with containers that aren’t templates… or that aren’t the kind of templates you expect.
There is a standard definition for “container”. (There’s also a more-or-less matching proposed concept in the range-v3 library.) Under that definition you could get T1 as typename Container::value_type.
if constexpr (std::is_same<T1, T2>::value)

I don’t think is_same is the test you really want to be applying here, because it precludes all kinds of useful cases. For example, let’s say you have a vector of strings, and the key you want to search for is a string_view:
auto strings = std::vector<std::string>{/*...*/};

auto const search_key = "to be found"sv;

// This won't work
if (contains(strings, search_key))
    // ...

What you want is really the C++20 concept std::equality_comparable_with. Lacking concepts in C++17, you could roll a type trait that does the same test.
return std::find(std::cbegin(source), std::cend(source), val) != std::cend(source);

Using the fully-qualified forms of std::cbegin and std::cend prevents ADL, which could break basically any container not defined in the std namespace.
You should use the standard pattern:
using std::cbegin;
using std::cend;

return std::find(cbegin(source), cend(source), val) != cend(source);

Also, I’d suggest using begin and end rather than cbegin and cend. Why? Because it doesn’t matter, since source is const, but third-party containers may not have bothered to add support for cbegin and cend (begin and end should be universal).
I think you really need some additional type traits (or concepts, if you’re targeting C++20) to make this work. First, a type trait is_container would be very handy for making the function produce better errors, and for helping with the internals:
template <typename Container, typename T>
auto contains(Container const& source, T const& val) ->
    std::enable_if_t<is_container_v<Container>, bool>

Or perhaps, rather than using SFINAE, you could use a static_assert:
template <typename Container, typename T>
auto contains(Container const& source, T const& val) -> bool
{
    static_assert(is_container_v<Container>);

You could also use an equality_comparable_with trait, to allow for more flexibility:
template <typename Container, typename T>
auto contains(Container const& source, T const& val) -> bool
{
    if constexpr (is_equality_comparable_with_v<typename Container::value_type, T>)
        // ...

Those two type traits will also help when testing for whether recursion is possible.
template <typename Container, typename T>
auto contains(Container const& source, T const& val) -> bool
{
    if constexpr (is_equality_comparable_with_v<typename Container::value_type, T>)
        // just use std::find
    else if constexpr (is_container_v<typename Container::value_type>)
        // recurse
    else
        // error

Those type traits will help a lot when there are problems; they can make a huge difference in the size and readability of the error messages you get if you’re dealing with deeply nested containers.
Other than that, the only other thing I can think to suggest is to make the function constexpr. Because why not?
Questions
You say "containers that aren’t templates" and " templates you expect", can you add 1 or 2 examples of this?
In order for a container-like type to work with your template template parameter, 3 things must be true:

It must be a template.
It must have 1 template type parameter (with any subsequent template parameters aliased or defaulted away).
That parameter must be the same as the container’s value type.

For an example that fails the first case: std::filesystem::directory_iterator. It is not a template. So this works:
auto dir = std::filesystem::directory_iterator(".");
if (std::find(begin(dir), end(dir), "foo") != end(dir))
    std::cout << "foo is in current working directory";

but this won’t work:
auto dir = std::filesystem::directory_iterator(".");
if (gco::contains(dir, "foo"))
    std::cout << "foo is in current working directory";

For an example that fails the second case: std::array. Your function expects a template with a single type parameter (and anything else defaulted away). std::array has a type parameter… and a non-type parameter (which is not defaulted). It’s certainly a container, and a template, but not the kind of template you expect.
So this works:
auto numbers = std::array<int, 5>{1, 2, 3, 4, 5};
if (std::find(begin(numbers), end(numbers), 3) != end(numbers))
    std::cout << "found 3";

but this won’t work:
auto numbers = std::array<int, 5>{1, 2, 3, 4, 5};
if (gco::contains(numbers, 3))
    std::cout << "found 3";

For an example that fails the third case… I can’t think of anything off the top of my head. This would require a container template whose first template parameter is not the container’s value type. That would be an odd thing to do (there’s certainly nothing like that in the standard library)… but it could happen!
You suggest to use the standard definition for container. Can you show me how this is done?
In a perfect world, the standard library would have done this for you. (And it will do it for you, but not until C++20.)
But if we’re going to get into this, we really need to tighten up some terminology. I don’t think you want contains() to be a container operation. I think you want it to be a range operation.
In C++ lingo, a container is a type that holds a bunch of stuff. std::vector, std::list, std::map, and so on, they’re all containers. They own their contents; when the container is destroyed, so are all the contents.
But there are other things that are container-like but not containers. As of C++17, there are also views.
A view is a type that provides a container-like view of stuff, but does not hold that stuff. As of C++17, the only view in the standard library (unless I’m forgetting something) is std::string_view, though there are lot more in the pipes, like C++20’s std::span. std::string_view does not own its contents. By contrast, std::string, which is a container, does.
I’m pretty sure you’d want gco::contains() to work with std::string_view. So obviously you want to support more than just containers.
And there are still other things that are neither containers nor views, but still seem like they should be able to work with gco::contains(). There’s nothing really in the standard library yet, but there’s a lot coming in future. For example, coroutines would bring generators. I can imagine a function that checks whether a number is part of the Fibonacci sequence that works something like this:
// fibonacci_sequence() is a generator that returns successive
// elements in the Fibonacci sequence: 1, 2, 3, 5, 8, 13, ...
if (gco::contains(fibonacci_sequence(), number))
    std::cout << number << " is in the Fibonacci sequence";

The generic C++ concept that covers both containers and views and more (including types that provides a container-like view of stuff, but not only don’t own the stuff, the stuff might not actually exist) is range. C++20 will be bringing a long-awaited range library, but C++ has been taking baby steps to support ranges since all the way back in C++11, with the range-for-loop.
I think what you’re making is not a library of generalized container operations, but rather a range library.
Now, if this were C++20, everything would be trivial. You could just do:
template <typename> struct dependent_false : std::false_type {};

template <typename T>
constexpr auto dependent_false_v = dependent_false<T>::value;

template <std::input_range Container, typename T>
constexpr auto contains(Container const& source, T const& val) -> bool
{
    using value_type = std::ranges::range_value_t<Container>;

    using std::begin;
    using std::end;

    if constexpr (std::equality_comparable_with<value_type, T>)
        return std::find(begin(source), end(source), val) != end(source);
    else if constexpr (std::input_range<T>)
        return std::any_of(begin(source), end(source), [&val](auto&& el) { return contains(el, val); });
    else
        static_assert(dependent_false_v<Container>);
}

Unfortunately, in C++17, you don’t have concepts, so you have to roll your own type traits to do the tests.
Okay, so… how? Well, the first thing you need to do is figure out what the requirements are. A minimal range is anything that works with range-for. That requires at least:

begin()
end()
that the return types of begin() and end() can be equality-compared
that the return type of begin() supports operator++; and
probably a few other things I’m forgetting.

You can test the first two requirements with something like:
template <typename Range>
constexpr auto adl_begin(Range&& r)
{
    using std::begin;
    return begin(r);
}

template <typename Range>
constexpr auto adl_end(Range&& r)
{
    using std::end;
    return end(r);
}

template <typename T, typename = void>
struct has_begin_support : std::false_type {};

template <typename T>
struct has_begin_support<T, std::void_t<decltype(adl_begin(std::declval<T>()))> : std::true_type {};

template <typename T, typename = void>
struct has_end_support : std::false_type {};

template <typename T>
struct has_end_support<T, std::void_t<decltype(adl_end(std::declval<T>()))> : std::true_type {};

Then make similar type traits to check that the return type of begin() is equality comparable with the return type of end(), and that the return type of begin() is an input iterator, and so on… and eventually put it all together as a single type trait.
Yes, that’s a shitload of work (unless you use a library like range-v3 which I HIGHLY recommend), but that’s why C++ programmers get the big bucks.
Now, this next bit is an opinionated rant:

 Honestly, I’ve started suggesting to programmers to consider targeting C++20, rather than C++17, even though C++20 isn’t fully officially out yet, and compiler support is as yet anemic. C++20 is the biggest update to C++ since C++11… and it might be even bigger. EVERYTHING will change once C++20 is the norm, probably even far more so than it did when C++11 came around. The amount of code you’d have to write to do contains() well in C++17 is dozens and dozens, if not hundreds of lines of arcane SFINAE crap that only experts understand with bullshit like enable_if and void_t. In C++20? It’s like, 10-12 lines, all obvious, simple, and brief (well, except maybe for the dependent_false trick, but that might not even be necessary, depending on how clear compiler errors are in C++20 mode).

 So it might be worth your while to hold off on writing a container ops library, and for now spend the time reading up on what’s coming in C++: like concepts, modules, and particularly the ranges library. Then when you’re ready, hopefully compiler support will have caught up, and you can roll out this library easily.

 If you really want to target C++17 with your library, that’s fine—there’s very little you can’t do in C++17 (it’s just MUCH easier in C++20). Just understand that you will be diving into a deep, deep well of very, very complicated stuff, and—and this is the worst part—even if you just want to do it for the learning experience, it will be mostly a waste of time, because the skills you’ll learn will be obsolete in a few months.

you suggest either using 'std::enable_if_t' or a static_assert. Is one of the two preferred or more common?
That’s an engineering question, meaning the answer is: there is no right answer; it depends on what you want.
Both methods will trigger a compile error if the constraints are not met. The difference is how.
static_assert is easier to understand. If the constraint fails, the compile just dies. That’s it. Nothing fancy. It’s so brutally simple, that it actually requires tricks to make it not fail when you don’t want it to. If you look at the C++20 version of contains() I wrote above, the static assert uses dependent_false:
static_assert(dependent_false_v<Container>);

If I’d just done:
static_assert(false);

it would just fail, always. Literally always—no code that uses contains() would compile. “But,” you say, “that static_assert is in the else part of an if constexpr!” Doesn’t matter. static_assert doesn’t care. When that function is compiled, if the compiler sees static_assert(false), it just dies immediately, before even bothering to check the rest of the function, before even realizing which branch of the if constexpr it’s in. The dependent_false trick is a way to confuse the compiler temporarily: it doesn’t see the false until after it parses everything in the function… at which point it then sees it’s in an else that doesn’t apply, so it ignores the assertion.
enable_if is more complicated. What it does (assuming you use it right) is remove the function from the overload set temporarily.
To understand what that means, imagine you have two overloads of template <typename T> foo(T) with different return types, then you call foo(0) (with T as an int):
template <typename T>
auto foo(T) -> T { std::cout << "int"; return {}; }

template <typename T>
auto foo(T) -> typename T::value_type { std::cout << "T::value_type"; return {}; }

foo(0); // what happens?

Well, first the compiler collects all the possibilities. So the overload set consists of both foo() functions.
Then the compiler eliminates obvious failures. In this case, foo(0) can’t possibly be calling the overload that returns T::value_type… because int does not have a value_type subtype: int::value_type is nonsense. So that overload is eliminated, leaving only the overload that returns T.
With only one possibility left, the compiler accepts that foo(0) means the first overload. The program compiles, and prints “int”.
If you try to use a std::string (which has a value_type) instead of an int, both overloads are valid, and you’ll get an error because the call is ambiguous.
What enable_if does is gives you control over the elimination step. It basically says “only include this function in the set of potential overloads if the condition is true”. If the condition is false, then it’s as if the function doesn’t exist.
Why is that cool? Well consider if you did this:
template <typename Container, typename T>
auto contains(Container const& source, T const& val) -> bool
{
    static_assert(is_container_v<Container>);

Then when you call contains(something, other) and something is not a container, the static_assert fires, and the whole compile dies. That may be exactly what you want.
But!… Maybe if something is not a container, there is some other overload of contains() that might be suitable (“contains” is a common name, after all!).
So if you did this:
template <typename Container, typename T>
auto contains(Container const& source, T const& val) ->
    std::enable_if_t<is_container_v<Container>, bool>

(or used a concept; a concept basically does the same thing as enable_if), then called contains(something, other) where something is not a container, you don’t immediately get a compile failure. Instead, this function just… disappears. Like it was never written. The compiler goes on searching for all the other overloads of contains() (for everything that is not a container), and if it finds a match, then good! If not, well, then that’s an error as always.
So that’s the difference:

With static_assert, if someone calls contains() with inappropriate arguments, the compile just dies immediately, even if there are other (and better) possibilities that might work.
With enable_if, if someone calls contains() with inappropriate arguments… the compiler just pretends the function doesn’t exist, and keeps looking for other possibilities. If it finds one, it uses it. If not, then that’s an error as always.

Which one is preferred?  It depends on what you want.
If you can be reasonably sure that no one will ever name another function contains() that might be confused with your function (which is a perfectly reasonable assumption!), then static_assert is just fine. But if you think you might be sharing the name contains() with other stuff… maybe you might not want to trigger a hard error right away; maybe you might want your function to “step aside” to give other functions with the same name a chance.
Hope all this helps!


Scala implicit conversion to add methods to Int

First of all, what Scala version are you using? If you're using 2.10 or newer versions, the language has introduced implicit classes which help you avoid the definition of implicit conversions - as a side note implicit classes are translated to implicit conversions by the compiler so let's say they are some type of syntactic sugar.

As you might now, the implicit modifier cannot be used on top-level definitions - that includes implicit classes as well, so we must wrap them in a class / trait / object. As a best practice it's best to put them in an object (or package object like you did). The other constraints of implicit classes are already explained in the first link, so I won't go through them here.

A final note before we get to the code is that you will often see that implicit classes are used as value classes. Please consult this post if you're curious to see how when you should mix them with value classes.

Enough talk, let's see the code now:

package object arithmetic {
  implicit class RichInt(val value: Int) extends AnyVal {
    def isPrime: Boolean = ???
  }
}

object ArithmeticTest extends App {
  import arithmetic._
  1.isPrime
}

That's it! Hope it helps.


Multiple column sorting and arraging algorithm

It seems that the transform you are after is a k-way merge in disguise.

In the nutshell, set up a min-heap of pairs <col_id, vector<int>::iterator>. On each iteration construct a vector of values equal to heap head, 0 otherwise; push it to the resulting matrix; remove those entries from heap an pull new values from the respective columns. Sorry if I miss something obvious.

I don't think you shall strive for in-place transform.

I am pretty sure that merging rows deserve a separate pass.

The

                col.push_back(0);
                std::rotate(col.begin()+row,col.end()-1,col.end());

is no better than col.insert(col.begin() + row, 0);

The static_cast<int>(col.size()) suggests that row should not be int, but along the lines of std::vector<int>::size_type.


When it is X’s turn, and they make a move, only player X can win.  Similarly, only Y can win on Y’s turn.  So why all these tests?

win = tt[0].value == 1 ? "X" : "O";

If there is a winner, just test p1turn in the if (winner) { code!

String win = p1turn ? "X" : "O";

Okay, you may want to move p1turn = !p1turn; to the end of the function, first, to avoid X/O confusion.

This code is checking if the row has all the same symbols, and the symbol is not blank:

if (tt[0].value == tt[1].value && tt[0].value == tt[2].value && tt[0].value != -1) {

When the player moves, this.value is set to their code.  And only they can win on this move.  So we could instead write:

if (tt[0].value == value && tt[1].value == value && tt[2].value == value) {

Slightly shorter.  But we can do better.

Change X’s & O’s values to +1 and -1.  Use 0 for blank.  Then, if a row sums to +3 or -3, you have a winner!

if (tt[0].value + tt[1].value + tt[2].value == 3*value) {

Similarly for other winning directions.


I'm glad we established in the comments that your code doesn't in fact run slow. When you use the word "efficiency", most people would take that to mean run-time speed (or space, depending on the context).

You should never optimize for efficiency unless there is a demonstrated lack of efficiency that has a negative impact on humans beings. Optimize for humans, not for computers. Computers don't care.

In this case, if I had gone down the path of trying to make it run faster, we would probably have ended up with less readable, less maintainable code.

We can certainly optimize for readability or style though, as you pointed out in the comments.

I should say first that I don't have a problem with your code. I think it's fine.

(This is one bug, however. Instead of Sort Last, you should do Sort Last,First. "Bloggs, Jane" should come before "Bloggs, Joe" in the output.)

I've rewritten the code below how I would personally write it. There are a couple of techniques that you may not be familiar with that can be very useful.

One is "capturing groups" in regular expressions. E.g. (?<first>.+), that matches a group named "first", and we can get the captured text with this: $matches['first']

($matches is a "magic variable" defined by PowerShell, if you are wondering.)

Another technique is "calculated properties" with Select-Object. You can make properties by supplying a property name and a script block that calculates the value. That is often more straightforward than creating objects with [PSCustomObject].

# E.g. "Bloggs;Joe" ==> "Bloggs, Joe"
function NormalizeName($fullName)
{
    $separators = '\s|,|;'
    if ($fullName -match "^(?<last>[^$separators]+)[$separators]+(?<first>.+)")
    {
        $last  = $matches['last']
        $first = $matches['first']
        "$last, $first"
    }
    else
    {
        # Doesn't match, so return unchanged.
        $fullName
    }
}

Import-Csv .\Cust.csv |
    Select-Object @{name="FullName"; exp={NormalizeName $_.FullName} }, StreetAddress, City, Postcode |
    Sort-Object FullName


Optimising this simple jQuery script that vertically centers elements on pages

From the comments above, I think the code is ok :)


Knuth-Morris-Pratt Search Algorithm 2 Python

naming

The name of a variable is part of the documentation of your code. Try to use meaningful names, that don't shadow built-ins.

wrd: sub (as in str.find)
str: whole
w: sub_index
s: whole_index

Generators

Instead of filling a list and returning that list, I prefer to work with generators in almost every case. If getting the result in a collection afterwards is very simple

Looping

in KMP_table you are essentially looping by index (position). Instead, loop over the word and enumerate

small things

candidate += (position - candidate) is essentially candidate = position
lenWrd is used twice, lenStr is used once, so they an be inline

result

def KMP_table(whole):
    # example: B A A B D C B A A A C A B -> [-1, 0, 0, -1, 1, 2, -1, 0, 0, 0, 4, 5, -1]
    candidate = 0
    for position, wrd_position in enumerate(whole):
        diff = position - candidate
        if whole[candidate] == wrd_position:
            yield -1
            candidate = position
        elif wrd_position == whole[diff] or candidate == 0:
            yield 0
        else:
            yield diff

def KMP_search(word, sub):
    if not word or not sub:
        raise ValueError("Empty lists")

    word_index, sub_index = 0, 0
    table = tuple(KMP_table(word))
    while (sub_index + len(word) - 1) < len(sub):
        if word[word_index] == sub[word_index + sub_index]:
            if word_index == len(word) - 1:
                yield sub_index
                sub_index += 1
                word_index = 0
            else:
                word_index += 1
        else:
            if table[word_index] > 0:
                sub_index += (word_index - table[word_index])
            elif word_index == 0:
                sub_index += 1
            else:
                sub_index += word_index
            word_index = 0

tuple(KMP_search('aba', 'aaababa'))

(2, 4)


I converted my timer loops to Reactive Extensions a while back to avoid the memory leaks created by event subscriptions and event handlers.  A snippet doing the same thing as yours is...

        var timer = Observable
            .Timer(TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(3))
            .Subscribe(q =>
                {   // this executes every 3 seconds in a detached loop
                    Console.WriteLine("do something here " + q);
                });
        // other work goes here
        GC.KeepAlive(timer);

Of interest here is the last line.  This tells the GC that the object should not be garbage collected until it is reached.  You can use the same strategy for your event driven timer.

If you wanted a fascinating glimpse into the new garbage collector introduced in 4.5, Maoni Stephens (the lady who actually wrote the GC) made a video that's a 'must see'...  http://channel9.msdn.com/posts/Maoni-Stephens-CLR-45-Server-Background-GC


There's quite a lot of code here, so for now I'm just going to look at the dispose function. You'll see that there's more than enough to say about this function for one answer.

1. Review

There's no docstring. What does this function do? How do I call it? What values do I pass for parameters? What does it return? It's very hard to maintain code when you don't know what it is supposed to do. This doesn't have to be long-winded or laborious: a quick explanation like the following is perfectly adequate.

"""Choose n*n*dens positions in matrix with the value 0, uniformly at
random, and set them to sp. Return matrix."""

There's no good reason to abbreviate the parameter to dens. It only appears once in the function body, and we're not running out of letters, so call it density.
The function takes a parameter s but this is not used. Better to omit it.
The function uses the global variable n. It would be better to pass this in as a parameter, or even better, deduce it from the size of matrix. Presumably the intention is that matrix is always an n × n array, in which case you should write matrix.size instead of n * n.
The name dispose is vague and does not convey much to me. I think the name populate would be better.
The function always returns matrix, which is useless, as the caller already knows about matrix.
The name matrix is slightly misleading, as Numpy has a matrix class but this parameter does not belong to it! It's actually an ndarray. I would call the parameter array or maybe just a.
The name sp is rather too specific. Presumably it is short for "species", but really nothing about this function depends on this value representing a species. You can imagine other types of lattice simulation where the array entries represent molecules, grains of sand, people, etc. So for generality I'd name this parameter value.
The value 0 is arbitrary and so for extra generality it should be a function parameter (taking the default value 0). Imagine having a "speciation" operation in which you replace some fraction of a species with a descendant. It would be nice to be able to reuse this code.
If dens is greater than 1, then limit will be greater than the number of elements in the array, and so the function will run forever.

Even if dens is less than 1, there might still not be enough positions in the array with value 0, and so the function will run forever.

Perhaps you plan not to fill very much of the array, but even so it is a good idea to write robust code in case you change your plans or want to reuse this code in other programs.
The way that the positions are found is to repeatedly generate random coordinates and check to see if the position is 0. This is inefficient. Imagine that dens is 1, so that all positions must be set to sp. How long will this take, on average? This is the well known "coupon collector's problem" so the expected number of coordinates to be randomly generated is \$ n^2 \log n^2 \$.

Perhaps you plan not to fill very much of the array, but again, it is a good idea to write code with the right asymptotic complexity, in case you change your plans or want to reuse this code in other programs.

So it would be better to find the positions containing 0 (using numpy.flatnonzero), then choose a random sample of those positions without replacement (using numpy.random.choice), and then set all the positions.

2. Performance

Putting all this together, I'd write the function like this:

def populate(array, density, value, original=0):
    """Choose array.size * density positions in array that are equal to
    original, uniformly at random, and set them to value.

    """
    a = array.reshape(-1)
    count = int(a.size * density)
    a[np.random.choice(np.flatnonzero(a == original), count, False)] = value

Note the use numpy.reshape to create a flattened view of array, so that we can use numpy.random.choice, which requires a 1-D array. We then use this view to update the original array.

However, this has unacceptably poor performance compared to dispose when density is small:

>>> a = np.zeros((1000, 1000))
>>> timeit(lambda:dispose(a, 0.01, None, 1), number=1)
0.0184222329990007
>>> timeit(lambda:populate(a, 0.01, 1), number=1)
0.2894051409966778

The reason for this poor performance is that numpy.random.choice computes a sample without replacement by permuting the whole array and using an initial prefix of the permutation. This is expensively wasteful when only a small part of the permutation is needed.

So what about sampling with replacement instead (which is fast), eliminating duplicates using numpy.unique and looping until we have enough choices (as in the original post)? Here's the implementation:

def populate(array, density, value, original=0):
    """Choose array.size * density positions in array that are equal to
    original, uniformly at random, and set them to value.

    """
    a = array.reshape(-1)
    count = int(a.size * density)
    while count:
        p = np.random.choice(a.size, count)
        p = np.unique(p[a[p] == original])
        a[p] = value
        count -= p.size

This is adequately fast: it's about ten times as fast as the original code, and more than a hundred times as fast as my first attempt above:

>>> a = np.zeros((1000,1000))
>>> timeit(lambda:populate(a, 0.01, 1), number=1)
0.0019981740042567253

However, it's not robust: it suffers from the same problems as the original code, discussed in §1.10 and §1.11 above. What we really need is a hybrid implementation: that tries the approach that's fast for small densities, but measures how well it's doing, and switches to the slow but sure approach for large densities. For example:

def populate(array, density, value, original=0):
    """Choose array.size * density positions in array that are equal to
    original, uniformly at random, and set them to value.

    """
    a = array.reshape(-1)
    count = int(a.size * density)
    while count:
        p = np.random.choice(a.size, count)
        p = np.unique(p[a[p] == original])
        a[p] = value
        count -= p.size
        if count > p.size * 10:
            # Not making much progress: switch to robust but slow algorithm
            a[np.random.choice(np.flatnonzero(a == original), count, False)] = value
            return

This remains very fast when density is small:

>>> a = np.zeros((1000, 1000))
>>> timeit(lambda:populate(a, 0.01, 1), number=1)
0.0022136839979793876

but still completes in a reasonable time when density is large:

>>> a = np.zeros((1000, 1000))
>>> timeit(lambda:populate(a, 0.99, 1), number=1)
0.3501391080208123
>>> a = np.zeros((1000, 1000))
>>> timeit(lambda:dispose(a, 0.99, None, 1), number=1)
5.953548110992415

and doesn't go into an infinite loop if there aren't enough spaces remaining:

>>> timeit(lambda:populate(a, 1.1, 1), number=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  ...
  File "mtrand.pyx", line 1106, in mtrand.RandomState.choice (numpy/random/mtrand/mtrand.c:11223)
ValueError: Cannot take a larger sample than population when 'replace=False'


Passing multiple parameters to an SQL query

Sub Module2 is a terrible name to use for a procedure. Not only it doesn't say anything about what it does, it looks like the [default] name of some standard code module.

Name things, it's important. Procedures do something, their names should start with a verb, and you should be able to read it and know roughly what it does just by the name.

Consider:

Public Sub InsertOrUpdateEstimates()

Also indent your code - it's harder to read code that begins in column 1 no matter what.

Instead of this:

Sub DoSomething()
DoSomeThings
DoSomeMoreThings
End Sub

Consider:

Sub DoSomething()
    DoSomeThings
    DoSomeMoreThings
End Sub

You're defining 5 parameters per command, but declare only 1 ADODB.Parameter object variable; this changes the meaning of the variable as the procedure executes, and this makes for bug-prone and confusing code. If a variable stands for "the UserID parameter", then it's reasonable to expect that variable to mean the same thing throughout the scope of the procedure. Same for the connection objects.

The problem is exactly that: the scope of the procedure is too wide - it's doing too many things.

You've essentially written a script - it goes top to bottom and executes an ordered sequence of operations and then completes.

You don't need to "consolidate" the code, you need to tear it apart and extract each responsibility into its own function, break it down into multiple, smaller, more specialized procedures.

You want to run a command for each row of a given range: you need a procedure that runs a command for a single row, and call it from another procedure.

The command takes 5 parameters; make the procedure receive 5 values as ...parameters:

Private Sub InsertOrUpdateEstimate(ByVal CD as String, ByVal theDate As Date, ByVal test As Single, ByVal EDtm As Date, ByVal UserID As String)

The body of that procedure will need to create an ADODB.Parameter object for each parameter value: instead of repeating the code for that 5 times, make another function that's responsible for creating an ADODB parameter - something like this:

Private Function CreateCommandParameter(ByVal name As String, ByVal value As Variant, Optional ByVal numPrecision As Integer = 4, Optional ByVal numScale As Integer = 4) As ADODB.Parameter

    Dim result As New ADODB.Parameter
    result.Direction = adParamInput
    result.name = name
    result.value = value

    Select Case VarType(value)
        Case VbVarType.vbBoolean
            result.Type = adBoolean

        Case VbVarType.vbDate
            result.Type = adDate

        Case VbVarType.vbCurrency
            result.Type = adCurrency
            result.Precision = numPrecision
            result.NumericScale = numScale

        Case VbVarType.vbDouble
            result.Type = adDouble
            result.Precision = numPrecision
            result.NumericScale = numScale

        Case VbVarType.vbSingle
            result.Type = adSingle
            result.Precision = numPrecision
            result.NumericScale = numScale

        Case VbVarType.vbByte, VbVarType.vbInteger, VbVarType.vbLong
            result.Type = adInteger

        Case VbVarType.vbString
            result.Type = adVarChar

        Case Else
            Err.Raise 5, Description:="Data type not supported"
    End Select

    Set CreateCommandParameter = result
End Function

Now, InsertOrUpdateEstimate can look like this:

Private Sub InsertOrUpdateEstimate(ByVal conn As ADODB.Connection, ByVal CD As String, ByVal theDate As Date, ByVal test As Single, ByVal EDtm As Date, ByVal UserID As String)
    With New ADODB.Command
        .ActiveConnection = conn
        .CommandType = adCmdStoredProc
        .CommandText = "EstimateInsertUpdate"
        .Parameters.Append CreateCommandParameter("CD", CD)
        .Parameters.Append CreateCommandParameter("Date", theDate)
        .Parameters.Append CreateCommandParameter("Test", test)
        .Parameters.Append CreateCommandParameter("EDtm", EDtm)
        .Parameters.Append CreateCommandParameter("UserID", UserID)
        .Execute
    End With
End Sub

Notice it's receiving the ADODB.Connection as a parameter, so it's responsible for executing a command, but not for setting up the connection.

So all that's left to do is to call that procedure inside the body of some loop that iterates all the rows we want to look at.

But there's more to consider: what if an error occurs because some of the data in row 7 is of the wrong type? What if the connection times out?

It would be a good idea to initiate a transaction before we start looping, and only commit the transaction once all rows have been correctly processed - and if any error happens, we can rollback the entire transaction, fix things and start over.

Think of a transaction as a bank transaction: you're moving dollars from one account to the other - if something wrong happens in the middle of the transaction, you don't want the money to be withdrawn from the source account but not deposited into the target account! A transaction either runs completely, or not at all: wrapping all these insert/update commands in a transaction is probably a good idea.

To do this correctly you need to handle runtime errors. Consider this procedure:

Public Sub InsertOrUpdateEstimates()
    Const connString As String = "..."
    Const fromRow As Long = 1
    Const toRow As Long = 10

    Dim CD As String
    Dim theDate As Date
    Dim test As Single
    Dim EDtm As Date
    Dim UserID As String

    On Error GoTo CleanFail

    Dim conn As ADODB.Connection
    Set conn = New ADODB.Connection
    conn.Open connString

    conn.BeginTrans

    Dim currentRow As Long
    With Sheet1
        For currentRow = fromRow To toRow
            CD = .Cells(currentRow, 2).value
            EDtm = .Cells(currentRow, 4).value
            test = .Cells(currentRow, 5).value
            theDate = .Cells(currentRow, 6).value
            UserID = .Cells(currentRow, 7).value
            InsertOrUpdateEstimate conn, CD, theDate, test, EDtm, UserID
        Next
    End With

    conn.CommitTrans

CleanExit:
    conn.Close
    Exit Sub

CleanFail:
    conn.RollbackTrans
    MsgBox Err.Description & vbNewLine & "Transaction was rolled back, no changes were made", vbExclamation
    Resume CleanExit

End Sub

Notice the Sheet1 object is being referred to directly instead of being fetched from the Worksheets collection everytime it's needed; the With block removes all redundancies here. Also we're reading the values using the Cells function instead of Range, so we can easily supply a row/column number to pick up a single value.

You can push the segregation of responsibilities to the next level by moving the whole ADODB-handling code to its own class - see materializing any ADODB query and creating ADODB parameters on the fly for more information; the For loop above could look something like this (and that replaces the helper CreateCommandParameter function and CreateCommandParameter procedure, too):

Const sql As String = "exec dbo.EstimateInsertUpdate ?,?,?,?,?;"
conn.BeginTrans

With Sheet1
    For currentRow = fromRow To toRow
        SqlCommand.ExecuteNonQuery conn, sql, _
            .Cells(currentRow,2).value, _
            .Cells(currentRow,4).value, _
            .Cells(currentRow,5).value, _
            .Cells(currentRow,6).value, _
            .Cells(currentRow,7).value
    Next
End With

conn.CommitTrans

The fewer things a procedure does, the clearer the code becomes; there shouldn't ever be a reason to copy+paste code - if you find yourself pressing Ctrl+C, ask yourself "is there not a better way?" before you press Ctrl+V.


Design:

Good job on setting up everything in main(), then passing off control to another function.
Declare and initialize file after checking the command line arguments.
Initialize fizz, buzz, and count.
Don't use !feof(file) to control your loop.  See this answer for more details.
Check the return value of fscanf() to make sure we're reading good data.
Good job remembering to close the file.

Readability & Maintainability/Performance

I'm grouping these two categories together for this review, since they happen to go hand in hand.

Your for loop can be refactored down a bit:

if (i % fizz == 0) fputc('F', stdout);
if (i % buzz == 0) fputc('B', stdout);
if (i % fizz && i % buzz)) fprintf(stdout, "%d", i);

Some people may find issue with the duplicated check on i with fizz and buzz, but we cut out some conditional branches doing this and the more branches we cut, the less susceptible to branch prediction we are.  There may be a better way to write this, but I can't think of it right now.
Note how I used fputs() and fputc() in the code above instead of printf().  This is because those functions are \$ O(1) \$ operations instead of \$ O(n) \$ to loop over the string and format it.  This may speed up your program by a hair, if that, but the main reason I recommend this change is to make clear we aren't modifying any strings.
Since the range of \$ X \$, \$ Y \$, and \$ N \$ is 1-20, it would be good to change the type representing these variables to something a bit more compact in memory.

Depending on what we want to optimize for (memory or performance), I would recommend either uint_least8_t or uint_fast8_t.

uint_least8_t: give me the smallest type of unsigned int which has at least 8 bits. Optimize for memory consumption.
uint_fast8_t: give me an unsigned int of at least 8 bits. Pick a larger type if it will make my program faster, because of alignment considerations. Optimize for speed.


If the destructor does nothing remove it:

Cards::Suit::~Suit()
{}

We can shorten that switch statement to make it readable.

    switch (type)
    {
        case Type_Hearts:   name = "Heart";  break;
        case Type_Diamonds: name = "Diamond";break;
        case Type_Clubs:    name = "Club";   break;
        case Type_Spades:   name = "Spade";  break;
        default:            assert(false);   break;
    }

Or we can replace it with a look up:

    static std::string  names[] = {"NULL", "Heart", "Diamond", "Club", "Spade"};
    if (type == Type_Null)
    {    assert(false); // Or throw.
    }
    name =  names[type];

If you want more checking:

    static std::vector<std::string>  names = {"Heart", "Diamond", "Club", "Spade"};
    name =  names.at(type-1); // will throw on bad value.

This seems a bit over keen.

        name[0] = static_cast<std::string::value_type>(::tolower(name[0]));

std::string::value_type by definition is char.
tolower() may return an int unless you pass in an EOF you will get a character back.

I would have just done:

        name[0] = ::tolower(name[0]);

In this switch use fall throug:

switch (type)
{
    case Type_Hearts:    /* fall through */
    case Type_Diamonds:  return true;

    case Type_Clubs:     /* fall through */
    case Type_Spades:    return false;
    default:  assert(false);
        // prevent compiler warning
        return true;
}

Is A Null_Suit the same as another Null_Suit?
in double a NaN is not equal to another NaN you may want that kind of functionality.

bool Cards::Suit::operator == (const Cards::Suit& other) const
{
    return this->type == other.type;
}


I know it's obvious but I really have to say this: outside a programming exercise do not write your own encryption function.

Let's now talk about code...

The first thing to do is to separate responsibilities. Encrypt() and Decrypt() methods (note PascalCase, you should follow C# naming guidelines) should do only one thing: encrypt and decrypt a string. To get user input and to provide an output is something else responsibility.

If you strip out all the console I/O your Encrypt() will be much simpler and you may note you can make it even simpler (to read):

static (IEnumerable<int> key, string encrypted) Encrypt(string text)
{
    var key = GenerateEncryptionKey(text.Length);
    return (key, new String(text.Zip(key, (v, k) => (char)(v + k))));
}

static IEnumerable<int> GenerateEncryptionKey(int length)
    => new Enumerable.Range(0, length).Select(x => _rnd.Next(1, 9));

static _rnd = new Random();

What I did:

I moved the generation of the encryption key to a separate function. In real world it will be a service you set separately. This gives you the ability to test the Encrypt() code with edge-cases using well-known and repeatable encryption keys (what will happen if v + k - which is Int32 - is higher than UInt16.MaxValue when casting back to char? Try and see).
I used Enumerable.Zip() function instead of manually looping through the input + key. Whenever possible you should use available functions to perform a task because they make your code faster to write, easier to read and...less buggy (they already been tested!) Take the time to explore LINQ functions, when working with collections they provide many things you may need.
I moved everything not directly related to encryption out of this function. Now I can test encryption in isolation!

It's an exercise for the reader to do the same thing for the Decrypt() function and to move magic values (like 0 and 9) to appropriate const int fields. Also, as exercise, think that adding a random value to a character does not necessarily produce another valid character (Unicode surrogates) and the string resulting from concatenation may not be a valid or representable string (you'd better encode the IEnumerable<int> produced by encryption instead of simply creating a string out of it).

Your logic for looping in the Main() method is little bit weird. You have a loop, you exit the loop and you recursively (from the encryption/decryption functions...) call Main() again. I will skip the StackOverflowException because you probably won't ever use this app long enough but it makes the program flow really hard to follow.

There are many ways to implement this but let's start with something easy:

static void Main()
{
    while (true)
    {
        var actionToPerform = Prompt("(E)ncrypt, (D)ecrypt or (Q)uit?");
        if (actionToPerform.Equals("e", StringComparison.CurrentCultureIgnoreCase))
        {
            ReadTextAndEncrypt();
        }
        else if (actionToPerform.Equals("d", StringComparison.CurrentCultureIgnoreCase))
        {
            ReadTextAndDecrypt();
        }
        else if (actionToPerform.Equals("q", StringComparison.CurrentCultureIgnoreCase))
        {
            return;
        }
        else
        {
            Console.WriteLine("Unknown option. Try again.");
        }
    }
}

The same can be done using a dictionary (<string, Action>) but for now let's keep it simple. For string comparison I do not use ToLower() but the appropriate overload of String.Equals() where I can specify a StringComparison value. The schoolbook example about case insensitive comparison is the i in Turkish (== performs comparison using current culture) where "i" != "I".ToLower() (and similarly "i".ToUpper() != "I").

Note the Prompt() function which is also reused elsewhere:

static string Prompt(string prompt)
{
    Console.Write(prompt + ' ');
    return Console.ReadLine();
}

We can now write our ReadTextAndEncrypt() function putting the things together:

static void ReadTextAndEncrypt()
{
    (string key, string encrypted) result = Encrypt(Prompt("Enter the text to encrypt:"));

    var key = new String(result.key.Select(x => (char)('0' + x)));
    Console.WriteLine("Encryption key is: {0}, key);
    Console.WriteLine("Encrypted string is: {0}, result.encrypted);
}

That's all, now, as exercise, write ReadTextAndDecrypt() with the same logic. You may also add Console.Clear() and Console.ReadKey() as appropriate (also that conversion for result.key isn't something to be proud of...)

In this example where I wrote (T1 key, T2 encrypted) I used value tuples (a C# 7 feature), it's similar to Tuple<T1, T2> but with an attached compile-time name. Function may be well rewritten as:

static Tuple<IEnumerable<int>, string> Encrypt(text)
{
    var key = GenerateEncryptionKey(text.Length);
    var encryptedText = new String(text.Zip(key, (v, k) => (char)(v + k)));

    return Tuple.Create(key, encryptedText);
}


a Python2 to Python3 print fixer in perl

\h matches horizontal white spaces

/x modifier instructs regex to ignore white spaces (readability)

/m modifier instructs ^ $ anchors to match begin/end of line, instead of string!

local $/; # read all text at once

while (my $line = <>) {
    $line =~ s/print \s+ (.+? (?: [^\\]\h*$ ) )/print($1)/xgsm;
    print $line;
}


Finding mongodb records in batches using mongoid

Actually there is no need to take this way since mongodb cursor by defaults returns batchwise


I'd use longer attribute names (firstName instead of fName, middleName, lastName).
It's easier to read and maintain.
Are you sure that latin1 is enough for every data? Consider using UTF-8.


You didn't specify which version of Laravel is used, so I am going to presume it is 5.x. If that is incorrect, please notify me and update your post with such relevant information

I am not sure exactly how to reduce the queries for comments but the suggestion below should allow remove the loop of queries for the user on each game.

Eager Loading

(Nested) Eager Loading - utilizing the with() method - can be used to populate the user property for each item in the collection:

$games = Game::join('comments', 'games.id', '=', 'comments.commentable_id')
->where('comments.commentable_type', Game::class)
->latest('comments.created_at')
->groupBy('games.id')
->take(10)
->with('comment.user')
->withCount('comments')

Variable naming

The lambda/closure passed to each() accepts a parameter named $games. Isn't it actually a representation of a game? If so, $game would be more appropriate. Additionally, other developers reading the code may be confused because $games is also used for the assignment of the collection.


Get list of indices from searching for values in list of lists

The most straightforward approach would be

    for listno, alist in enumerate(list_of_lists):
        for n in alist:
            indices[n] = listno

It surely gives better performance. Is it enough, I don't know.


Using flexbox to replace fixed and absolute positioning

If you want the header to be "sticky" the only way is to make it position:fixed. In order to to push the rest of the content down, you need to know the headers height. Then you set a margin-top to your #hero.


String extension method that truncates at sentence punctuation

It's an interesting problem isn't it :)

Here's my extension method that does the same (stripped of some additional options)

public static string TruncateTo(
    this string input,
    int truncateLength,
    bool addEllipsis = true)
{
    // Check to see if we even need to bother truncating
    if (string.IsNullOrWhiteSpace(input) || input.Length <= truncateLength)
        return input;

    // copy the input
    var temp = input;

    // Define a list of characters that we can safely break on
    char[] anyOf = { '.', ',', ';', ':', '?', '!' };

    // LastIndexOfAny starts at the max position works backwards thru' the string
    var truncatePosition = temp.LastIndexOfAny(anyOf, truncateLength);

    // no appropriate place to truncate.
    if (truncatePosition == -1)
    {
        // Return original string but you could fall back to splitting on last space
        return temp;
    }
    temp = temp.Substring(0, truncatePosition + (addEllipsis ? 0 : 1));
    return addEllipsis
        ? temp + "..."
        : temp;
}

I've added comments but I think the code is pretty clear. I've also modified the code a fair bit as we support quite a few different ways of deciding where to split.

You'll also notice that it's greedy - I.e. it tries to keep the string as long as possible.


Immediate Smaller Element Time Limit Exceeded

Things to improve

You are looping over the input twice; (1) when splitting the raw input string Console.ReadLine().Trim().Split(' ') (2) when going over the splitted items for (int i = 0; i < arrSize - 1; i++). Try finding a way to go over the raw input in a single pass.
You are parsing most items twice, once as arr[i+1] and once as arr[i] in the next cycle. Try avoiding redundant parsing.
Writing to the console is time expensive. Console.Write("-1" + " "); Try to find a way to build the string and write the result to the console once.

I just tested a solution taking into account the above and I got Execution Time: 1.21. So it's definately possible to go < 3.496


Stored Procedure enhancement for updating columns in a subset

Anonymized code
Object/variable names should tell us something about what they actually mean. For instance, these variables:
  DECLARE @val1 NVARCHAR(10)
  DECLARE @val2 INT

What does val1 and val2 actually stand for? In fact everything in the query looks like example code, so it leaves us to guess what the code is actually designed for.

SELECT INTO #table
You would most likely get performance improvements with regards to that temp table if you created it manually instead of using SELECT ... INTO. That would at least let you create some indexes on it. I've gained huge performance improvements with that technique in the past so I strongly recommend explicitly creating your temp tables along with indexes for performance-critical queries.

Cursor
You would likely get better performance in row-by-row operations if you used a cursor, instead of doing an update both to the source table and the temp table in a while loop. See cursors on MSDN for reference.

Print @msg
I'm not really sure why you would print the @msg variable. According to your question, the purpose of the code is:

The code attempts to change the value of test.[stat] to 'R' if a subset is found with the corresponding stat values.

So printing that message to the console seems like a waste of resources. I notice you are returning @msg as output anyways, so if the calling code needs that, it's easy to get it without printing it to the console.


Rabin Karp algorithm improvement for string contains A to Z only

The code looks good, this probably improves the runtime in some cases, but I am not sure if hash matches happen often enough for this to be effective on average.
Efficiency/Logic

It's probably a good idea to check for the pattern size at the beginning of your method, to avoid overflows. This technically won't happen in python as it will be automatically change the storage to big-int, but the performance of that will be much worse.

Minor optimization for runtime is to save the value of base ** (len(pattern) - 1) before your loop. Exponentiation is an expensive function, so it's better to do it only one time.

Readability

Try to avoid one letter variables like i and j, except for numeric loop indices. A more expressive variable name would improve readability a lot.
Look for repeated parts in your code, and see if it makes sense to extract them into functions. One example in your code is calculating the letter index which is repeated multiple times.
Might make more sense to return None instead of -1 in case of no match.

Modified code
def letter_position(letter):
  return ord(letter) - ord('A')

def rabin_karp_match(source, pattern):
    base = 26
    p_hash = 0
    s_hash = 0
    for letter in pattern:
        p_hash = p_hash * base + letter_position(letter)

    first_letter_base = base ** (len(pattern) - 1)
    for i, letter in enumerate(source):
        s_hash = s_hash * base + letter_position(letter)
        i < len(pattern) - 1:
          continue

        match_start_index = i - len(pattern) + 1
        if s_hash == p_hash:
          return match_start_indexj

        s_hash = s_hash - letter_position(source[match_start_index]) *  first_letter_base
    return None


Join ArcGIS tables in Python of plant greenness in response to prior month's rainfall

You should do a maintainability pass before you start optimizing. In that spirit:

Imports

from datetime import datetime
import dateutil.relativedelta

should be at the top of the file, and should not be repeated. Also, this:

arcpy.env.addOutputsToMap = 0

should be moved past the imports section.

Pathlib

These:

ws1=glob.glob(r'D:\GIS_Files\NEW_LA_FULL_SERIES\ALL_DATA_2000_2020\CITY_POLYs\*.shp')
ws2 = glob.glob(r'D:\GIS_Files\NEW_LA_FULL_SERIES\ALL_DATA_2000_2020\PRECIP_preprocessed_2000_2020\CITY_ZONAL_TABLES\*.dbf')

should get a little love from pathlib:

Factor out the common directory -

data_dir = Path(r'D:\GIS_Files\NEW_LA_FULL_SERIES\ALL_DATA_2000_2020')
ws1 = (data_dir / 'CITY_POLYs').glob('*.shp')
ws2 = (data_dir / 'PRECIP_preprocessed_2000_2020' / 'CITY_ZONAL_TABLES').glob('*.dbf')

Hard-coded string slices

These:

[35:41]
[12:18]

are a nightmare. I don't know what they're actually selecting, but I can nearly guarantee that there's a better way. It seems like a slice out of a path, and paths are structured - you should not have to do indexing like this.

Nomenclature

You, currently, understand what these variables mean:

ws1
ws2
r
r2
r3
result

But no one else does, and you might not in six months. Do yourself a favour and give these meaningful names.

Logical combination

        if STR_PREV_POLY==STR_PREV_PRECIP:
            if STR_PREV_PRECIP==basename_FINAL:

should simply be

if STR_PREV_POLY == basename_FINAL:

That intermediate variable has no effect.


I would suggest that, as you are looking to implement your code around session management, you would think about it more globally.  Having several lines of procedural code to manage session logout, rather than a logout() method on a class that provides methods to manage sessions, limits re-use of this code.  Why should you need to route a user to a specific URL to log them out as opposed to just having ability to do something like Session::destroy() from anywhere in your application, with that method basically doing what is in your code now?

Perhaps take a look at existing libraries to see if they meet you needs (for example something like https://github.com/auraphp/Aura.Session).

For better depth of knowledge around securely handling sessions, I would recommend you read and understand the PHP sessions "basics" documentation at http://php.net/manual/en/features.session.security.management.php

In particular, I would point you to this section:

  Session Data Deletion

  Obsolete session data must be inaccessible and deleted. Current
  session module does not handle this well.

  Obsolete session data is better to be removed as soon as possible.
  However, active sessions MUST NOT be removed immediately. To satisfy
  these requirements, you MUST implement time-stamp based session data
  management by yourself.

  Set and manage expiration time-stamp in $_SESSION. Prohibit access to
  obsolete session data. When obsolete session data access is detected,
  it is advised to remove all authenticated status from the user's
  sessions and force them to re-authenticated. Obsolete session data
  access could be an attack. To do this, you must keep track active
  sessions per user.

  Note: Access to obsolete session could happen by unstable network
  and/or concurrent access to web site also. Server tried to set new
  session ID via cookie, but Set-Cookie packet may not be reached to
  client due to lost connection. One connection may issue new session ID
  by session_regenerate_id(), but another conncurrent connection may not
  get the new session ID yet. Therefore, you must prohibit access to
  obsolete session a while later. i.e. Time-stamp based session
  management is mandatory. In short, do not destroy session data by
  session_regenerate_id() nor session_destroy(), but use time-stamp to
  control access to session data. Let session_gc() to remove obsolete
  data from session data storage.
  In short, do not destroy session data by session_regenerate_id() nor
  session_destroy(), but use time-stamp to control access to session
  data. Let session_gc() to remove obsolete data from session data
  storage.

Note particularly here the bolded text.

What you should take away from this is that you need to begin to think of sessions and authentication (login) separately.  Really the sole purpose of the session is to persist data on the server between client calls.  PHP Sessions are not authentication or reliable data access control mechanisms.

You do not need to "destroy" the session at all upon a logout event in your application.  You can simply regenerate_session_id() upon this change in authentication state (just as you would need to do when user logs in). But before that action you would need to programmatically set the data to expire on the current session id.  This is the only reliable way to "lock out" this session data.  This of course means that you would also always need to validate that the session id passed to the page does not contain expired data directly after calling session_start() near the beginning request processing and treating this as an invalid session if expired data is encountered.

Also, think of it from an application functionality perspective.  Just because a user is logged out, doesn't mean your application might not need to still store some data in session.  For example, maybe you might need to store something in session before performing a redirect to let the destination page know some piece of information (like the fact that the user just logged out).  That target page might need to change the display on page the user is redirected to (like perhaps a successful logout message in your case).

if(session_id() != "") {
    session_destroy();
}

Why the conditional here? It doesn't seem necessary. Would you ever expect to be in a condition when session_id would NOT be set anyway? (Again I question use of session_destroy() at all based on earlier comment)

if(isset($_COOKIE[session_name()])) {
    // Delete the session cookie
    setcookie(session_name(), "", time() - 1);
}

Again, the conditional doesn't seem necessary.  Why would you ever get into the state where you have an active session and don't have this cookie set?

If you are running your sessions in strict mode (you should be).  Then this code is really not necessary, as the cookie would in essence be ignored going forward.  If you are trying to be specific about overall cookie size then this code still makes sense.

$cookie_contents = $_COOKIE['authUser'];
list($selector, $plain_token) = explode(':', $cookie_contents);

//Empty the values
$query = $dbh->prepare("UPDATE auth_tokens SET token=:token, expires=:expires WHERE selector =:selector");
$query->execute(array(
    ":token" => "",
    ":expires" => "",
    ":selector" => $selector
));

$count = $query->rowCount();
if($count == 0) {
    die('Something went wrong..Could not log you out.' );
}

I would consider taking this functionality and building a class (or function) around it (perhaps userAuthPersistence or similar).  You could get this to something like:

if(isset($_COOKIE['authUser'])) {
    try {
        userAuthPersistence::persist($_COOKIE['authUser']);
    } catch (Exception $e) {
        // do something here to handle error
    }

    // Delete the authentication cookie
    setcookie('authUser', "", time() - 1);
}

list($selector, $plain_token) = explode(':', $cookie_contents);

I would consider moving away from using your own serialization methodology (in this case simply concatenating with :) in favor of using PHP's serialization methods, JSON, or some other well-structured, well-supported approach to serializing structured data into a string.  I think over time you will find them more powerful, more flexible, and less fragile.

$query = $dbh->prepare("UPDATE auth_tokens SET token=:token, expires=:expires WHERE selector =:selector");

This line of code is to long and harder to read.  Consider getting in the habit of making sure the SQL within your PHP is visually differentiated from surrounding code to make it easier to read.

$sql = <<<'EOT'

UPDATE auth_tokens
SET
    token = :token,
    expires = :expires
WHERE selector = :selector

EOT
$statement = $dbh->prepare($sql);

I like using heredoc or nowdoc syntax (especially on longer queries), but even breaking up the SQL string across lines in a standard string assignment works.

Note also the change in variable name from $query to $statement which is my guess as to what you are actually representing in this variable.

die('Something went wrong..Could not log you out.' );

It is generally a bad idea to just echo errors to standard out.  Consider at least logging an error here.  You also might want to have portion of code closer to display layer handle the actual end user messaging.


Simple function to turn array of objects to array of key value pairs

Ryan,

Here's how I would do it. Since you're making something backwards compatible with CF8, which does not explicitly have the 'Local' scope, and you've already declared it via the 'var', then we'll put all other function local variables within this struct, and only return that which is needed.

<!---
 *  FUNCTION toKeyValuePairArray
 *  Method to create a simple object reference array to reduce overhead and improve performance.
 *  This assumes that your objects have Getters for their primary properties.
 *  (no need to instantiate every object, every time, when all you need is a number or a name)
 *
 *  @theArray (array) - an array of objects
 *  @idGetterFunctionName -  Function name for getter function that pulls the object's id
 *  @valueGetterFunctionName - Function name for getter function that pulls the object's name
 --->
<cffunction name="ToKeyValuePairArray" returntype="array" output="false" access="public">
    <cfargument name="theArray" type="Array" required="true" hint="an array of objects" />
    <cfargument name="idGetterFunctionName" required="true" type="string" hint="Function name for getter function that pulls the object's id" />
    <cfargument name="valueGetterFunctionName" required="true" type="string" hint="Function name for getter function that pulls the object's name" />

    <cfset var LOCAL = StructNew() />
    <cfset LOCAL.retArray = ArrayNew(1) />

    <cfloop array="#ARGUMENTS.theArray#" index="LOCAL.theComponent">
        <cfset LOCAL.tmpObjVals = StructNew() />
        <cftry>
            <cfinvoke component="#LOCAL.theComponent#" method="#ARGUMENTS.idGetterFunctionName#" returnvariable="LOCAL.id" />
            <cfinvoke component="#LOCAL.theComponent#" method="#ARGUMENTS.valueGetterFunctionName#" returnvariable="LOCAL.value" />

            <cfset LOCAL.tmpObjVals["id"] = LOCAL.id />
            <cfset LOCAL.tmpObjVals["value"] = LOCAL.value />

            <cfset ArrayAppend(LOCAL.retArray,Duplicate(LOCAL.tmpObjVals)) />
            <cfcatch><!--- Empty Catch ---></cfcatch>
        </cftry>
    </cfloop>

    <cfreturn LOCAL.retArray />
</cffunction>

Since we 'var' one core variable (creating our own function local scope, so to speak) we no longer have to declare the temp object at the top of the method, since you reset it at the top of each loop iteration anyway. I also standardized your struct and array initialization across the method, to maintain that backward compatibility (and standardization of form is just good practice).

You aren't really doing any additional processing on the return variables from your 'getter' calls, so I applied them directly to the tempObj, so we don't create any unnecessary variables. You don't have to upper case scope names. I do that to make them stand out better when looking at code. I did uppercase the function names. This is just something I got from college: begin uppercase the function calls, and begin lowercase on variable names, then camel case the remainder.

NOTE: Adjusted some of my code, to work in some of Dan's (good) suggestions. I understand the 'try/catch' conceptually, but I did make them required args so it would throw errors if you didn't have them.


The number generation technique is generally sound.  I just have the following minor suggestions:

The idiomatic way to repeat something 10 times is

for (int idx = 0 ; idx < 10 ; ++idx) { … }

Use the fRandom instance variable; you shouldn't need to create new Random() in each function.
You hard-coded values in each function; those constants should probably be pulled out to the class level.
showRandomInteger() should be changed to return a random value instead of logging it.
The compiler will implicitly do String.valueOf() for you, so you can just write

log("Generated : " + getGaussean(MEAN,VARIANCE));

getGaussean() should be spelled getGaussian().


Replacing names in text fields with aliases to help de-identify data

You seem to run a separate UPDATE command on each row of the cursor. That's inherently slow and will likely be a lot quicker when you run the UPDATE based on a SELECT statement that does the required projection for all matching rows at once.


Some thougts:

above all, using a user-level code pulling keyboard state periodically is much less reliable then kernel-level driver which OS pushes key events to
40 milliseconds sleep is much too high
if you could open the file handle once instead of each time a key is pressed, you'd get a significant performance boost, at the cost of taking care to close file after the script stops
if you could do file writing asynchronously (e.g. in a dedicated thread or leveraging an async API), this would reduce the risk of missing a key press because of I/O blocking
using a sound timer API allows resolution much better than what is achievable with thread sleeps
maybe it's worth increasing priority of the keylogger process, to reduce the risk of missing key due to thread context switch

(thanks Sam for your corrections)


A few notes:

First off, your UploadStatus structure only contains one variable, which is somewhat useless IMO.  Instead, I would make some sort of email structure that contains all the necessary parts of an email in order for your program to send it off.  Here's a structure that I came up with to use:

 typedef struct
 {
     const char* to;
     const char* from;
     const char** email;
     size_t pos;
 } EmailData;

You may note that I changed your lines_read to pos and made it a size_t since I doubt you will ever read a negative number of lines.
The payload_source() method looks to be your CURLOPT_READFUNCTION, but it doesn't have the right format.  It should look like this prototype according to the documentation:

size_t read_callback(char *buffer, size_t size, size_t nitems, void *instream);

Also, the current name of your function doesn't really convey to me that it is a callback when reading your code.  To aid readability, I would change it to something such as readCallback().
Right now you have your email hardcoded within your code... something I would definitely look to change to be more dynamic.  I would suggest creating a sort of message constructing function that would fulfill such a purpose, store it in your EmailData struct, and then pass that structure to your callback function as the instream parameter.
To fix your formatting I would look at the original HTML email that is sent from a Gmail client and then dissect that.  Here is an example of one that I sent off:

MIME-Version: 1.0
Received: by 10.37.194.194 with HTTP; Tue, 11 Aug 2015 18:42:25 -0700 (PDT)
Date: Tue, 11 Aug 2015 20:42:25 -0500
Delivered-To: person@gmail.com
Message-ID: <CJYf78Vnxbma4wdV1mZuBXHPeEptOzyjH1vLMzLwnhoXsPw@mail.gmail.com>
Subject: Gmail Test
From: syb0rg <person@gmail.com>
To: 5555555555@tmomail.net
Content-Type: multipart/alternative; boundary=001a11c04f6ca3e68e051d1354cc

--001a11c04f6ca3e68e051d1354cc
Content-Type: text/plain; charset=UTF-8

Body content

--001a11c04f6ca3e68e051d1354cc
Content-Type: text/html; charset=UTF-8

Body content

--001a11c04f6ca3e68e051d1354cc--

The actual dissection of each line of this email is done in my final code with comments

Final Code

Please note that this code leaks memory and doesn't contain a unique ID generation method.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <curl/curl.h>

typedef struct
{
    const char* to;
    const char* from;
    const char** email;
    size_t pos;
} EmailData;

EmailData* initEmailData(EmailData* data, const char* to, const char* from, const char* subject, const char* input)
{
    data->to = to;
    data->from = from;

    // the added numbers to the length of the string are the pre-computed
    // lengths of the strings to be concatenated + 1 (for termination char)
    size_t htmlSize = strlen(input) + 24;
    char *html = malloc(htmlSize);
    snprintf(html, htmlSize, "%s%s%s", "
", input, "
\r\n");

    size_t headerSize = strlen(subject) + 12;
    char *header = malloc(1);
    snprintf(header, headerSize, "%s%s%s", "Subject: ", subject, "\r\n");

    size_t receiverSize = strlen(to) + 7;
    char *receiver = malloc(receiverSize);
    snprintf(receiver, receiverSize, "%s%s%s", "To: ", to, "\r\n");

    size_t senderSize = strlen(from) + 9;
    char *sender = malloc(senderSize);
    snprintf(sender, senderSize, "%s%s%s", "From: ", from, "\r\n");

    size_t timeSize = 40;
    char* timeString = malloc(timeSize);
    time_t rawtime = 0;
    time(&rawtime);
    struct tm *timeinfo = localtime(&rawtime);
    strftime (timeString, timeSize, "Date: %a, %d %b %Y %T %z\r\n", timeinfo);

    const char **payload = malloc(sizeof(char*) * 17);
    const char* setup[] =
    {
        // extends the format of email to support more data (vidoes, audio, etc)
        "MIME-Version: 1.0\r\n",
        // when the email was sent
        timeString,
        // who the email is to
        // TODO: multiple recipient support
        receiver,
        // who the email is from
        sender,
        // https://en.wikipedia.org/wiki/Message-ID
        //"Message-ID: <CJYf78Vnxbma4dV1mZuBpXPeEptOzyjHvLMBzLwnhoXsPw@mail.gmail.com>\r\n"
        // email subject, optional
        header,
        // describe the data contained in the body
        // https://tools.ietf.org/html/rfc2046#section-5.1.1
        "Content-Type: multipart/alternative; boundary=border\r\n",
        // empty line to divide headers from body, see RFC5322
        "\r\n",
        // all boundaries must start with two hyphens
        "--border\r\n",
        // let recipient interpret displaying text, send plain text & HTML
        // specify the plain text encoding
        "Content-Type: text/plain; charset=UTF-8\r\n",
        "\r\n",
        input,
        "\r\n",
        "--border\r\n",
        // specify the HTML encoding
        "Content-Type: text/html; charset=UTF-8\r\n",
        "\r\n",
        html,
        "\r\n",
        // final boundary ends with two hyphens as well
        "--border--\r\n",
        NULL
    };
    for (int i = 0; setup[i]; i++)
    {
        *(payload + i) = setup[i];
    }
    data->email = payload;
    data->pos = 0;
    return data;
}

size_t readCallback(char *ptr, size_t size, size_t nmemb, void *userp)
{
    if((size == 0) || (nmemb == 0) || ((size * nmemb) < 1)) return 0;

    EmailData *upload = (EmailData*) userp;
    const char *email = upload->email[upload->pos];

    if(email)
    {
        size_t len = strlen(email);
        if (len > size * nmemb) return CURL_READFUNC_ABORT;
        memcpy(ptr, email, len);
        upload->pos++;
        return len;
    }
    return 0;
}

int main(void)
{
    CURLcode res = CURLE_OK;
    struct curl_slist *recipients = NULL;
    const char *from = "person@gmail.com";
    const char *password = "password";
    const char *to = "5555555555@tmomail.net"; // see http://www.emailtextmessages.com/
    EmailData data = {0};
    initEmailData(&data, to, from, "Test Subject", "Test content");
    CURL *curl = curl_easy_init();

    if (curl)
    {
        // set username and password
        curl_easy_setopt(curl, CURLOPT_USERNAME, from);
        curl_easy_setopt(curl, CURLOPT_PASSWORD, password);
        curl_easy_setopt(curl, CURLOPT_URL, "smtp://smtp.gmail.com:587/");
        // start with normal connection, and upgrade to TLS using STARTTLS
        curl_easy_setopt(curl, CURLOPT_USE_SSL, (long) CURLUSESSL_ALL);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
        curl_easy_setopt(curl, CURLOPT_MAIL_FROM, from);
        recipients = curl_slist_append(recipients, to);
        curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);
        curl_easy_setopt(curl, CURLOPT_READFUNCTION, readCallback);
        curl_easy_setopt(curl, CURLOPT_READDATA, &data);
        curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
        // useful for debugging encryped traffic
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

        // send the message
        res = curl_easy_perform(curl);
        if(res != CURLE_OK) fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
        curl_slist_free_all(recipients);
        curl_easy_cleanup(curl);
    }

    return (int) res;
}


C function to print arrays of arbitrary data type

First of all this is a good attempt to provide polymorphism for print functionality. Few comments that might help:

I studied the print_array function and we can certainly do few improvements to it.

1) int print_array(const void *array, size_t length, char *type)

The type parameter is defined as char *. Since this function will support only a predefined types its better to have those as enum values. for e.g. you could do a typedef as

typedef enum{
INT = 0,
DOUBLE,

MAX_TYPES,
}SUPPORTED_TYPES;

2) if (!strcmp(type, TYPE_INT))
We can avoid these comparisons by making use of a Map like feature. Your current approach requires changing print_array function for any new type that we add. For e.g. tomorrow if you add support for print_char you will have to make those changes in print_array as well. Wouldn't it be better if print_array required no change. Ok so how to do it. In C++ there is a rule to replace conditional statements with polymorphism or maps. We will use maps here.

Since we already changed the type to an enum we can define a new struct which holds what functions to call for what data-types and the size of data-type as below:

typedef struct{
    void (*function)(const void *number);
    int size_of_elements;
}FunctionMap;

Now we create a mapping for data-types to function and store it in a global variable say print_map

const FunctionMap print_map[] = {
    [INT] = {print_int,sizeof(int)},
    [DOUBLE] = {print_double,sizeof(double)},
};

Now your print_array function changes just to few lines i.e. a lookup into this print_map for the type that is passed.

int print_array(const void *array, size_t length, SUPPORTED_TYPES type)
{

    assert(type<MAX_SUPPORTED);
    assert((sizeof(print_map)/sizeof(FunctionMap)) == MAX_SUPPORTED);

    void (*function)(const void *number);
    const void *cast_array = array;
    size_t size;
    size_t i;
    function = print_map[type].function;
    size = print_map[type].size_of_elements;
    for (i = 0; i < length; ++i) {
        function(cast_array + i * size);
    }
    printf("\n");
    return 0;
}

Note that I have added few asserts to make sure that the user passes proper values for type and that the implementer has add all data-type mappings in print_map. Now whenever you define a new print type say print_char you don't need to change print_array. Just add that function and its mapping in print_map and everything should work as it is.

Hope this helps.


If the length is always identical you can save 1000000 calls to new().

Because new String(char[]) uses Arrays.copyOf(), you don't need a new char[] in every loop.

private static int ourlen = 1024;
private static char[] chars = new char[ourlen];

public static String getAlphaNumeric() {
    for (int i = 0; i < ourlen; i++) {
        chars[i] = ch[random.nextInt(ch.length)];
    }
    return new String(c);
}


Does using promise.all suffice to promote concurrency?

It's not really Promise.all that does it. You're starting your requests without waiting for the previous ones to complete, so yes, they run concurrently. All Promise.all does is let you know when all of the promises you give it have resolved (or when the first one rejects).

  can someone suggest any improvements?

Some thoughts:

In getInfoViaConcurrency:

Your use of map is incorrect, kind of a mash-up of your original forEach (from your now-deleted post on SO) and map
You can pass getInfoViaAjax directly to map
The then handler on the Promise.all serves no purpose and can be removed

In getInfoViaAjax, you could use fetch on modern browsers rather than XMLHttpRequest

So getInfoViaConcurrency could be:

function getInfoViaConcurrency(ids) {
  return Promise.all(ids.map(getInfoViaAjax));
}

and if you want to use fetch, getInfoViaAjax could be:

function getInfoViaAjax(id) {
  return fetch({/*...appropriate options and URL...*/}).then(response => {
      if (!response.ok) {
          throw new Error(/*...whatever you want to say here...*/);
      }
      return response.text();
  });
}