Report on user-input chacters by their type

Answering your main question:

  So, is this code any good?

Your code is good in the sense that it works as expected in the context of the English alphabet. That's a good start and for a small program like this we could live with that.

But there are a couple of things to be done better.

    Console.WriteLine("Input anything and the program wil tell you how many vowels, consonants, numbers and other symbols you gave.");
    text = Console.ReadLine().ToLower();

Your prompts are a little too descriptive. Make them shorter and more "demanding" like:

Console.Write("Enter the text: ");
text = Console.ReadLine().ToLower();

Notice the use of Console.Write(...) instead of Console.WriteLine(...). The effect is, that the user enter the text on the same line after the prompt, which is common practice in the console.

If you want to inform the user of the meaning by the program, then provide a explanation once in the beginning - before to loop.

  var hsVowels = new HashSet<char> { 'a', 'e', 'i', 'o', 'u' };
  var hsConsonants = new HashSet<char> { 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z' };
  var hsNumbers = new HashSet<char> { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

These variables are constant and do not change per loop, so no need to instantiate them in every loop. Instead place them in the beginning of the method:

  string repeat;

  var hsVowels = new HashSet<char> { 'a', 'e', 'i', 'o', 'u' };
  var hsConsonants = new HashSet<char> { 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z' };
  var hsNumbers = new HashSet<char> { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

  do
  {
    //asks for input

    int vowels, consonants, numbers, otherSymbols;

Declaring variables like this is allowed, but considered bad practice. Instead use one line per variable:

    int vowels = 0;
    int consonants = 0;
    int numbers = 0;
    int otherSymbols = 0;

It's easier to find them and hence understand the code - especially for reviewers.

    //calculates
    vowels = text.Count(c => hsVowels.Contains(c));
    consonants = text.Count(c => hsConsonants.Contains(c));
    numbers = text.Count(c => hsNumbers.Contains(c));
    otherSymbols = text.Length - (vowels + consonants + numbers);

Here you use the LINQ extension Count() which is usable for many things, but here it is rather inefficient in that calling text.Count(...) for every char type will cause the text to be parsed three times. For a small text it will probably be OK, but for larger texts it will slow down the process significantly. Instead a single foreach-loop could do the same in just one iteration:

    foreach (char ch in text)
    {
      if (hsVowels.Contains(ch))
        vowels++;
      else if (hsConsonants.Contains(ch))
        consonants++;
      else if (hsNumbers.Contains(ch))
        numbers++;
      else
        otherSymbols++;
    }

It looks maybe not so smart and modern but is a lot more efficient.

    Console.WriteLine("Your input has {0} vowels, {1} consonants, {2} numbers and {3} other Symbols.", vowels, consonants, numbers, otherSymbols);

Printing the result on one line is not very readable. A tabular form will be more clear:

    Console.WriteLine("Result: ");
    Console.WriteLine($"Original Text: {text}");
    Console.WriteLine($"Vowels:        {vowels,15}");
    Console.WriteLine($"Consonants:    {consonants,15}");
    Console.WriteLine($"Numbers:       {numbers,15}");
    Console.WriteLine($"OtherSymbols:  {otherSymbols,15}");

    Console.WriteLine("Would you like to try again? (yes/no)");
    repeat = Console.ReadLine();
    //tests if the users input was valid (yes/no)
    while (!(repeat.ToLower().Contains("yes") || repeat.ToLower().Contains("no")))
    {

Here, the user is forced to type "yes" or "no". "y" or "n" would do the trick:

Console.Write("Would you like to try again? (Y/N): ");

you use repeat.ToLower() every time you use repeat so why not lower it once:

repeat = Console.ReadLine()?.ToLower();

When it comes to the overall structure you should think about splitting the code into meaningful methods. The program has three major parts:

User input
The calculation
Display of the result

and because you allow the user to enter more than one text it must run in a loop like:

  string textInput;

  while ((textInput = GetUserInput()) != null)
  {
    TextInfo info = CountElements(textInput);
    PrintTextInfo(textInput, info);
  }

This is easy to understand, and each functionality of the program can be written and maintained separately:

private string GetUserInput()
{
  Console.Clear();
  Console.Write("Enter some Text [To exit press: Enter]: ");
  string text = Console.ReadLine();
  if (string.IsNullOrWhiteSpace(text))
    return null;
  return text;
}

private void PrintTextInfo(string textInput, TextInfo info)
{
  Console.WriteLine("Result: ");
  Console.WriteLine($"Original Text: {textInput}");
  Console.WriteLine($"Vowels:        {info.Vowels,15}");
  Console.WriteLine($"Consonants:    {info.Consonants,15}");
  Console.WriteLine($"Numbers:       {info.Numbers,15}");
  Console.WriteLine($"OtherSymbols:  {info.OtherSymbols,15}");
  Console.WriteLine("Press Enter to Continue...");
  Console.ReadLine();
}

For the TextInfo info = CountElements(textInput); you could write a text analyzer class that could be instantiated like:

  CharTypeAnalyzer analyzer = new CharTypeAnalyzer("aeiouAEIOU", "bcdfghijklmnpqrstvwxyzBCDFGHIJKLMNPQRSTVWXYZ");

with the definition of vowels and consonants as string arguments. This will make it more reusable for other languages than English (the use is of course limited to languages where the terms "vowel" and "consonant" are meaningful).

Using this class will change the main method to:

static void Main()
{
  CharTypeAnalyzer analyzer = new CharTypeAnalyzer("aeiouAEIOU", "bcdfghijklmnpqrstvwxyzBCDFGHIJKLMNPQRSTVWXYZ");

  string textInput;

  while ((textInput = GetUserInput()) != null)
  {
    TextInfo info = analyzer.Analyze(textInput);
    PrintTextInfo(textInput, info);
  }
}

where TextInfo is defined as:

public struct TextInfo
{
  public int Vowels;
  public int Consonants;
  public int Numbers;
  public int OtherSymbols;
}

and CharTypeAnalyzer as:

public class CharTypeAnalyzer
{
  string _vowels;
  string _consonants;

  public CharTypeAnalyzer(string vowels, string consonants)
  {
    _vowels = vowels;
    _consonants = consonants;
  }

  public TextInfo Analyze(string textInput)
  {
    TextInfo info = new TextInfo();

    foreach (char ch in textInput)
    {
      if (IsVowel(ch))
        info.Vowels++;
      else if (IsConsonant(ch))
        info.Consonants++;
      else if (IsDigit(ch))
        info.Numbers++;
      else
        info.OtherSymbols++;
    }

    return info;
  }

  private bool IsVowel(char ch)
  {
    return _vowels.Contains(ch);
  }

  private bool IsConsonant(char ch)
  {
    return _consonants.Contains(ch);
  }

  private bool IsDigit(char ch)
  {
    return char.IsDigit(ch);
  }
}

In this way the code is easy to review and maintain, and you can easily debug and test each part separately.

It can be done in many other ways, but the essential messages are:

Keep things simple
Split the code into meaningful parts - methods and classes


I actually take issue with functions written like this in general. It screams "I am smarter than a compiler", and flies in the face of most of what C++ is about at a philosophical level.

It's not portable, it's not future-proof, it's severely hamstringing the compiler, so optimizations implemented in future versions of the compiler will likely not be able to be applied.

All this to say: for me, there needs to be a crazy strong rationale to motivate the existence of something written like this in a non-toy codebase.

The biggest culprit of this in your code is the "writing more data than the size returned" part of it. The chances of this eventually stomping out-of-bounds memory is simply not worth the marginal performance difference. Considering the places in code where such encodings tend to be used, I find it highly unlikely that it has any measurable performance impact in anything that benchmarks this in context with some other code around it.

So, now that that's out of the way, here's my feedback of the function as written:

Don't use builtins where you don't have to.

I get using __builtin_clzll, but there is no valid reason to use __builtin_memcpy over std::memcpy.

Don't use magic values where unnecessary

That 64 coould easily be 8 * sizeof(value). Same goes for the 9, it could be sizeof(value) + 1.

I know you only care about X86_64, and unsigned long long int is always 8 bytes on that platform, but if being safe does not cost you anything (which is the case here), then there is no excuse not to be.

Alternatively, if you really want 64 bits exactly, just use std::uint64_t instead.

Separation of concerns

The main issue I see with your function is that it conflates the encoding and the storage. You would be better off separating them, and letting the compiler reconciliate.

In the following, encode_and_store() compiles to effectively the same thing as your enc(). On top of that, since enc() is now a pure function, and does not involve any side effect anymore, the compiler is a lot more free to mix and merge it with the calling context, so odds are it'll end up being faster in actual use.

std::tuple<unsigned long long int, int> enc(unsigned long long int value) {
    int nUsedBits = 64 - __builtin_clzll(value|1);
    int nBytesNeeded = (nUsedBits+6)/7;

    if (nBytesNeeded<9) {
        value = ((value<<1)|1)<<(nBytesNeeded-1);
    }
    return std::make_tuple(value, nBytesNeeded);
}

int enc_and_store(unsigned char *result, unsigned long long int value) {
   auto [data, bytes] = enc(value);
   if(bytes >= 9) {
       *result++ = 0;
   }

   __builtin_memcpy(result, &data, 8);
   return bytes;
}


Go web application with a mock user repository

To really understand the blog post, I recommend looking at its example project (https://github.com/benbjohnson/wtf - see also http branch).

Ben Johnsons posted another post detailing its steps: https://medium.com/wtf-dial/wtf-dial-domain-model-9655cd523182).

Regarding the organization of your code, it would be like this:

project.go // the exported interfaces
mock/      // the mock implementations
http/      // http handler/server
mysql/     // the mysql implementations
cmd/       // the 'glue'

A major point is that you can only import parent (sub)packages.
For instance your http subpackage can not depend on the mysql subpackage (http should only depend on the interfaces defined in project.go - project.UserService for instance).

The only exception to this rule is your main.go (or your tests).
For instance, you import project/http and project/mysql and connect them :

Since the mysql.UserService struct implements the project.UserService interface it is transparent for the http package which expects a project.UserService interface

project.go

take a look at https://github.com/benbjohnson/wtf/blob/http/wtf.go

package project

type UserID int

type User struct {
    Name string
}

type UserService interface {
    GetByID(UserID) (*User, error)
}

// HTTPService is similar

mock/user.go

take a look at https://github.com/benbjohnson/wtf/blob/http/mock/mock.go

package mock

import (
    "your/project"
)

type UserService struct {
    GetByIDFn      func(id project.UserID) *project.User, error
    GetByIDInvoked bool
}

func (s *UserService) GetByID(id project.UserID) (*project.User, error) {
    s.GetByIDInvoked = true
    return s.GetByIDFn(id)
}

mysql/user.go

Your actual implementation with a MySQL database for instance (adapt to your own user backend)

http/*.go

take a look at https://github.com/benbjohnson/wtf/tree/6d855c355488361b22b1a5ba13d9453e39141292/http

package http

import (
    "your/project"
    "net/http"
)

type HTTPService struct {
    // Here you embed some UserService Interface
    UserService project.UserService
}

func (h *HTTPService) HandleHTTP(w http.ResponseWriter, r *http.Request) {
    // Use the UserService Interface (don't care if it's mock or real)
    h.UserService.GetByID(...)
    // write response
}

cmd/mocked/main.go

Glue everything (be careful of import names conflicts!):

package main

import (
    "your/project/http"
    nethttp "net/http"
)

func main(){
    server := http.HTTPService{
        UserService: mock.UserService{},
    }

    nethttp.ListenAndServe(":8888", server)
}


IEEE 754 square root with Newton-Raphson

This answer uses pointer-casting for type-punning just to save space.  In practice keep using your union (safe in ISO C99, and in C++ as a GNU and MSVC extension) or memcpy (safe in C and C++).  This pointer-casting is only safe in MSVC, or GNU-compatible compilers with -fno-strict-aliasing

Initial approximation

Packed bit fields are not only unnecessary here, they make the result worse. You do something along the lines of:

uint64_t i = *(uint64_t*)&f;           // double to int
i = i - (1023 << 52);                  // remove IEEE754 bias
i = i >> 1;                            // divide exponent by 2
i = i + (1023 << 52);                  // add IEEE754 bias

If you change the order of operations, you can handle the biasing in a single constant:

uint64_t i = *(uint64_t*)&f;           // double to int
i = i >> 1;                            // divide exponent by 2
i = i + (1023 << 52) - (1023 << 51);   // remove/add IEEE754 bias

The constant can then be simplified to:

uint64_t i = *(uint64_t*)&f;           // double to int
i = (i >> 1) + (1023 << 51);           // all of the above

Note that I didn't bother to mask when shifting, so the exponent's rightmost bit drops into the mantissa, which is shifted as well. This is a feature, not a bug. The IEEE754 formats are deliberately chosen to be monotonic when interpreted as integers, so carry-overs between exponent and mantissa are explicitly allowed.

With my approximation, the mapping is as follows (linear mapping within intervals):

original   number is    exponent   manitssa   orig interval
exponent  in interval   in sqrt   first bit     maps to
   0     [  1.0,  2.0 )    0         0       [  1.0,  1.5 )
   1     [  2.0,  4.0 )    0         1       [  1.5,  2.0 )
   2     [  4.0,  8.0 )    1         0       [  2.0,  3.0 )
   3     [  8.0, 16.0 )    1         1       [  3.0,  4.0 )
   4     [ 16.0, 32.0 )    2         0       [  4.0,  6.0 )

With your code, the mapping is (also linear within intervals):

original   number is    exponent  orig interval
exponent  in interval   in sqrt     maps to
   0     [  1.0,  2.0 )    0     [  1.0,  2.0 )
   1     [  2.0,  4.0 )    0     [  1.0,  2.0 )
   2     [  4.0,  8.0 )    1     [  2.0,  4.0 )
   3     [  8.0, 16.0 )    1     [  2.0,  4.0 )
   4     [ 16.0, 32.0 )    2     [  4.0,  8.0 )

Newton-Raphson

Given a good approximation, Newton-Raphson doubles the number of significant digits on each iteration (quadratic convergence). The above approximation provides about 4 bits of accuracy (max error: 6% or ~1/16), so 3 Newton-Raphson iterations are required for single and 4 iterations for double precision.

The entire code could look like this:

float sqrtf(float x)
{
    float y = x;
    // Approximation
    uint32_t* i = (uint32_t*)&x;
    *i = (*i >> 1) + (127 << 22);
    // Newton-Raphson
    x = (x + y/x) / 2;
    x = (x + y/x) / 2;
    x = (x + y/x) / 2;
    return x;
}

double sqrt(double x)
{
    double y = x;
    // Approximation
    uint64_t* i = (uint64_t*)&x;
    *i = (*i >> 1) + (1023 << 51);
    // Newton-Raphson
    x = (x + y/x) / 2;
    x = (x + y/x) / 2;
    x = (x + y/x) / 2;
    x = (x + y/x) / 2;
    return x;
}

Subnormals and other hazards

You already have special handling for nan, inf, 0 and x < 0, which is good, but we need to handle subnormal numbers as well. The code, both yours and mine, fails when confronted with such numbers. As a remedy, I suggest you scale subnormal numbers by 2^200 and scale the result by 2^-100. I chose 2^200 because it safely brings all subnormals back into normal range for all precisions, including quad, but other numbers work equally well (but only powers of two retain full precision).

Also observe that my code relies on IEEE754 properties. It doesn't work for non-IEEE754 numbers, most notably x86's 80bit extended double format. If you want to handle such numbers, you can convert them to float or double for the approximation step and back to extended double for Newton-Raphson.


Add elements to an array inside a foreach loop

maybe I am missing something, but why do you even need to have two different arrays $i and $w? second thing, $file_names array should go outside of the foreach loop since this array doesn't depend on the iteration of the first foreach loop.

I am not sure about the exact output which you expect but it seems that you can only iterate through the file names array and when you need to update this line

'value' => "" . $ws . ""  , you could just look up the value of $ws in the particular array rather than iterating the entire array every time.


Regarding the number of variables:

For displaying all "small" values, you could introduce a variable of type string in which you save all small numbers. But since you haven't yet learned about functions and arrays, this would make your code much more complicated than it is now.

So for now, just keep the program as-is, using one variable per number.

In the rest of the review, I'm going straight from the top to the bottom of your code.

#include "stdafx.h"
#include "iostream"

The #include "stdafx.h" is fine. When an include file comes from your own project (which stdafx.h does), you should surround it with double quotes.

But all other include files (especially system headers like iostream) should not be enclosed in "double quotes" but in <angle brackets>. So it should be #include <iostream>.

using namespace std;

As soon as you start writing serious code, you should omit the using namespace std. This line imports several hundred names from the std namespace, such as min, max, sort, depending on the system headers you included. This can lead to confusion when you make typos or just forget to declare a function that is also defined in that namespace.

int _tmain(int argc, _TCHAR* argv[])
{
    float val1, val2, val3, val4;
    float sum = 0, multiply = 1;

Whenever possible, use the data type double instead of float, since it is more precise (15 digits instead of 7).

    cout << "Enter the first number: ";
    cin >> val1;

Imagine what happens when the user of the program doesn't enter a number here but simply types hello program. how are you today?. In that case val1 will not get any value, and whatever value was stored there before will be used by the program. This leads to unpredictable behavior.

To fix this, write the following code:

    if (!(std::cin >> val1)) {
        std::cerr << "Error: could not read the first number\n";
        return 1; // Any nonzero value means failure.
    }

Continuing with your code …

    if(val1 < 20) {
        multiply *= val1;
    } else if(val1 > 25) {
        sum += val1;
    }

Very nice. Short and readable. I would just change the variable name multiply into product, since variables usually get passive names. Later, when you write functions, these will get the active names, like multiply two numbers.

    cout << "Enter the second number: ";
    cin >> val2;
    if(val2 < 20) {
        multiply *= val2;
    } else if(val2 > 25) {
        sum += val2;
    }

    cout << "Enter the third number: ";
    cin >> val3;
    if(val3 < 20) {
        multiply *= val3;
    } else if(val1 > 25) {
        sum += val3;
    }

    cout << "Enter the fourth number: ";
    cin >> val4;
    if(val4 < 20) {
        multiply *= val4;
    } else if(val4 > 25) {
        sum += val4;
    }

    if(val1 <= 25) cout << "The number(s) below or equal to 25 are/is: " << val1 << endl;
    if(val2 <= 25) cout << "The number(s) below or equal to 25 are/is: " << val2 << endl;
    if(val3 <= 25) cout << "The number(s) below or equal to 25 are/is: " << val3 << endl;
    if(val4 <= 25) cout << "The number(s) below or equal to 25 are/is: " << val4 << endl;

The are/is doesn't look convincing. To make the output nice, you could count the numbers that are less than or equal to 25. Then, add the following code:

    if (lessOrEqual25Count == 0) {
        std::cout << "No numbers are below or equal to 25.\n";

    } else {
        if (lessOrEqual25Count == 1) {
            std::cout << "One number is below or equal to 25:";
        } else {
            std::cout << lessOrEqual25Count << " numbers are below or equal to 25:";
        }
        if (val1 <= 25) std::cout << " " << val1;
        if (val2 <= 25) std::cout << " " << val2;
        if (val3 <= 25) std::cout << " " << val3;
        if (val4 <= 25) std::cout << " " << val4;
        std::cout << "\n";
    }

Continuing with your code …

    cout << "When we multiply the numbers below 20 we get: " << multiply << endl;
    cout << "When we add the numbers above 25 we get: " << sum << endl;

    return 0;
}

All in all, this is a nice program. It works fine, and it's good that you will learn about arrays and functions soon. They will really make programming easier, since currently you have to repeat large sections of your code over and over.


Conditional AND statement- which is more readable?

I don't know coffeescript, but in general, extracting complex conditions to a helper function is a common refactoring technique. When you do that, you effectively give a name to the previously nameless condition, which works like documentation, and can naturally improve readability.

Another advantage is that such function would hide the details of the inner workings of determining whether the automation status was successful or not. So if later you want to change the underlying conditions, the place to do that will be well identified, in a dedicated function, rather than buried inside some other function.

Of course, this doesn't mean that you should extract every less-than-trivial boolean condition to a helper function. Where you draw the line may be different from person to person. The fact that you're asking this question seems to suggest that you're inclined to make this move. (Personally I would extract it too.)


Transferring a CSV file to a database while merging some columns

csv.DictReader accepts 'restKey' 3rd parameter.

with open(data_filename) as f, sqlite3.connect(db_filename) as conn:
        conn.executescript(SQL_create_table)
        cursor = conn.cursor()
        next(f, None)      # Skip the headers
        reader_object = csv.DictReader(f,['important1','important2'],'item_list')
        row_count = 0
        for row_dict in reader_object:
            row_count += 1
            row_dict['item_list'] = repr(row_dict['item_list'])  # convert list to string first
            cursor.execute(SQL, row_dict)


Already answered by @Thomasky:

double dt = ((double)tm) / n;

There are some common subexpressions, multiplications, you need to do only once. like b*(s0*i0) (integer multiplication first).

The while loop would better go as (more precise, faster):

for (int j = 0; j < n; ++j) {
    double bsi = dt*b*(s0*i0);
    double ai = dt*a*i0
    s0 -= (int) -bsi;
    i0 += (int) (bsi - ai);
    //r += ai; // As unused?
}

Variables can (and should) be declared as locally as possible, a declaration in a loop does not do more work as outside; there is just one slot reserved on the function stack.

The cast of (int) does no rounding.
As you might imagine, n*dt increases the approximation error in dt by n-fold. However more precision, a correction, would cost time.

Maybe using doubles, say double s1 = s0; double i1 = i0; instead of s0 and i0 would give a better solution. No idea.

And finally this task is solvable with a bit of math.


Repeatedly multiplying digits until a single digit is obtained

Python 3.x bug

Did you know that your program outputs 1 for the number 39 if executed on Python 3?

This is because of the / division operator on this line:

return get_digits(num / 10, digits)

The meaning of / in Python 3.x was changed (PEP 238). Switching to // would be a quick fix.

Improving the solution

  I was thinking I might consolidate these three little recursive
  functions into one function containing all three..

What if we would get all the digits of a number by iterating over the string representation of an integer and converting every digit back to an integer - map(int, str(num)). In order to multiple the digits of a number we can use reduce() applying the operator.mul (multiplication operator) function:

from functools import reduce
from operator import mul

def persistence(number, count=0):
    # recursion base case - exit once the number is less than 10
    if number < 10:
        return count

    # get new number by multiplying digits of a number
    new_number = reduce(mul, map(int, str(number)))

    return persistence(new_number, count + 1)

Note that you don't actually need the while loop at all, since you are going recursive and have a num < 10 base case as a recursion "exit condition".

Note that you can also approach the "getting digits of a number" "mathematically" instead of converting the types back and forth:

from functools import reduce
from operator import mul

def get_digits(number):
    """Generates digits of a number."""
    while number:
        digit = number % 10

        yield digit

        # remove last digit from number (as integer)
        number //= 10

def persistence(number, count=0):
    if number < 10:
        return count

    # get new number by multiplying digits of a number
    new_number = reduce(mul, get_digits(number))

    return persistence(new_number, count + 1)

This would also be generally faster than the first version.


You have committed a grave error here with operator precedence, which should have easily been caught with simple testing:

X1 = Sector4Arithmetic / 2 * a;

The variable names SectornArithmetic are bizarre.  Most of those intermediate results don't need to be assigned to a variable.  The most complex intermediate result, b * b - 4 * a * c, has a standard name: "discriminant", which you should use.

You can use if (discriminant < 0) to detect that there are no real roots.  The other tests — (b == 0) and (c == 0) — are superfluous and harmful, as there is no justification for prohibiting those coefficients from being 0.

As mentioned in the previous Python review, system("pause") is inappropriate.  Just call std::getline() and discard the result.

Calling main() recursively is worse than a goto, as you are deepening the call stack for no reason.  Write a proper loop instead.  Furthermore, the return 0; statement is unreachable and should be eliminated.


A function that moves a tile in the game of fifteen

Reading past array bounds
Each of your four checks has the possibility of reading past array bounds.  Very bad things can happen when that happens.  I will illustrate with an example:
Let board be defined as int board[3][3], and lettile = 1, space[0] = 2, space[1] = 2.  When the code reaches this first check:

  if ( board[ space[0] ][ space[1] + 1 ] == tile ) {

    board[ space[0] ][ space[1] + 1 ] = 0;

    board[ space[0] ][ space[1] ] = tile;
    space[1]++;

    return true;
  }

It will read the value of board[2][3], which is past the end of the board array.  The memory location corresponding to board[2][3] is 4 bytes past the end of board, and will probably be occupied by some other global variable in your program.  Suppose this memory location contains the value 1.  In this case, you will swap the 1 with the 0 in board[2][2], and then you will set space[1] to 3 which is outside of your board dimensions.  So now:

Whatever global variable held the value 1 will now have the value 0 for no reason.
The next time you call into this function, you will be reading even further out of bounds because space[1] is 3, which will cause you to read from board[2][4].

Simplify with loop
Instead of writing each of your four direction checks separately, you can combine them into a single loop.  Here is how I would do that (with additional bounds checking as well to fix the first problem):
bool move(int tile, int space[])
{
    int dx[4] = {  0,  0,  1, -1 };
    int dy[4] = {  1, -1,  0,  0 };

    // Check in each of the four directions.
    for (int i = 0; i < 4; i++) {
        int x = space[0] + dx[i];
        int y = space[1] + dy[i];

        // If out of bounds, skip this direction.
        if (x < 0 || x >= BOARD_SIZE || y < 0 || y >= BOARD_SIZE)
            continue;

        // If we find the tile, swap them with the empty space.
        if (board[x][y] == tile) {
            board[x][y] = 0;
            board[space[0]][space[1]] = tile;
            space[0] = x;
            space[1] = y;
            return true;
        }
    }
    return false;
}


There isn't really all that much to say, your code is generally good.

Declare variables where they are needed: you do not use pounds in the if statement, so I would remove it and just use MIN_WEIGHT_POUND in the return directly. Alternatively, you could move the declaration of pounds to after the if.
Try to minimize white space: It's good to sort code by using newlines, but too much isn't good either. remove the newline after the if statement, and maybe some more.
Try to minimize use of brackets: No need to wrap the boolean expression in brackets.

With these changes, your code would look like this:

private static int idealBodyWeight(int feet, int inches) {
    if (feet > MIN_HEIGHT_FEET) {
        inches += (feet - MIN_HEIGHT_FEET) * INCH_PER_FEET;
    }
    return MIN_WEIGHT_POUND + inches * POUND_PER_INCH;
}


This sure looks like a fun game!

So far, it's pretty well constructed, so I just have some suggestions:

To answer your questions...

  Q1. Can this code be simplified/ made more efficient?

Yes. I recommend putting it in a class for simplicity. As far as efficiency goes, the largest running time is O(n), so it is already efficient. It might be possible to simplify it to allow the max running time to be O(log n), but I don't know how.

Class version:

# Whenever possible, only import specific functions from the library
from random import choice
from time import sleep

class Hangman:
    """
    A Hangman class.
    """
    _HANGMAN = (
        """
         ------
         |    |
         |
         |
         |
         |
         |
         |
         |
        ----------
        """,
        """
         ------
         |    |
         |    O
         |
         |
         |
         |
         |
         |
        ----------
        """,
        """
         ------
         |    |
         |    O
         |   -+-
         |
         |
         |
         |
         |
        ----------
        """,
        """
         ------
         |    |
         |    O
         |  /-+-
         |
         |
         |
         |
         |
        ----------
        """,
        """
         ------
         |    |
         |    O
         |  /-+-/
         |
         |
         |
         |
         |
        ----------
        """,
        """
         ------
         |    |
         |    O
         |  /-+-/
         |    |
         |
         |
         |
         |
        ----------
        """,
        """
         ------
         |    |
         |    O
         |  /-+-/
         |    |
         |    |
         |   |
         |   |
         |
        ----------
        """,
        """
         ------
         |    |
         |    O
         |  /-+-/
         |    |
         |    |
         |   | |
         |   | |
         |
        ----------
        """)

    _WORDS = ("APPLE", "ORACLE", "MIMO", "TESLA")
    _POSITIVE_SAYINGS = ("Well done!", "Awesome!", "You Legend!")

    def __init__(self):
        """
        The Python constructor for this class.
        """
        self._word = choice(self._WORDS)
        self._so_far = "-" * len(self._word)
        self._used = []
        self._wrong_answers = 0

    def play(self):
        """
        This is the main driver of the game.
        Plays the game.
        """
        self._reset_game()
        self._start_game()

        # The amount of incorrect answers should be no greater than the length
        # of HANGMAN.
        #
        # Use the length of HANGMAN to ensure there's no index
        # overflow error when printing current progress.
        while self._wrong_answers < len(self._HANGMAN) and self._so_far != self._word:
            self._print_current_progress()
            guess = self._user_guess()
            self._check_answer(guess)

        self._print_result()
        self._play_again()

    # ---------------------------------
    # "Private" methods

    def _check_answer(self, guess):
        """
        Checks to see if the user's guess is correct.
        :param guess: User's guess
        """
        if guess in self._word:
            print(choice(self._POSITIVE_SAYINGS), "...Updating word so far...")

            for i in range(len(self._word)):
                if guess == self._word[i]:
                    # so_far is spliced this way:
                    # so_far [from the start : up until, but not including the
                    #     position of the correctly guessed letter]
                    # + guessed letter
                    # + so_far [from the position next to the
                    #     correctly guessed letter : to the end]
                    self._so_far = self._so_far[:i] + guess + self._so_far[i+1:]

        else:
            print("INCORRECT! Try again!")
            self._wrong_answers += 1

    def _play_again(self):
        """
        Asks the user if he or she would like to play again.
        If the user wants to play again, calls play().
        Otherwise, thanks the user for playing.
        """

        print("Would you like to play again?")
        user_input = input("Enter Y for yes or N for no: ").upper()

        if user_input == "Y":
            self.play()

        else:
            print()
            print("Thank you for playing!")

    def _print_current_progress(self):
        """
        Prints the current progress of the game.
        """
        print()
        print(self._HANGMAN[self._wrong_answers])
        print("Word so far: ", self._so_far)
        print("Letters used: ", sorted(self._used))

    def _print_result(self):
        """
        Prints the result (win or lose).
        """
        sleep(1)
        print()
        print("Calculating result...")
        sleep(1)
        print()
        if self._wrong_answers == len(self._HANGMAN):
            print("UNLUCKY! Better luck next time!")
        else:
            print("WINNER! Congratulations!")

    def _reset_game(self):
        """
        Resets the game by calling the constructor.
        """
        self.__init__()

    def _start_game(self):
        """
        Starts the game by printing an introduction
        and asks the user to hit the ENTER key to continue.
        """
        print()
        print("\t\tWelcome to Hangman!")
        print()
        input("Press Enter to START:")

    def _user_guess(self):
        """
        Asks for the user to guess a letter.
        :returns: User's guessed letter.
        """
        guess = input("Guess a letter: ").upper()
        sleep(1)  # Time delay - allows user friendly reading
        print()

        while guess in self._used:
            print("Try again... You've already used this letter")
            guess = input("Guess a letter: ").upper()
            sleep(1)
            print()

        self._used.append(guess)

        return guess

if __name__ == '__main__':
    game = Hangman()

    game.play()

This is also available on secret Gist

If you want to just focus on the method part, you can see the method version by clicking on my Github Gist link

  Q2. Why does the following code have to be indented in the way that it is?
  used.append(guess) and
  so_far = new

From the code in your question, used.append(guess) needs to be outside of the while loop or the guessed letter will be added to the used list repeatedly as long as the while condition is true.

so_far = new needs to be outside of the for loop for the same reason. In my suggested code, you will have no need to use the new variable because string splicing is used instead.

  Q3. Out of interest, is there a way to print the hangman figure once and just replace the previous figure, to avoid mass text/ reloading in the Python Shell?

Currently, I don't know. I'll keep it in my mind and let you know if I find a way.

Update:

In one of your comments below, you asked if the code above was OOP. The answer is kind-of, but no. I didn't define a model or the logic in a separate entity. However, I did create a Gist link that is the OOP version of the code.

You can click on this Gist link to see the OOP version.


You should be giving your variables proper names. This would really improve the readability of your code. After all, code is read more times than it is written. As an outsider not all too well versed in advanced data structures, it's really hard to tell what k or v is supposed to be. Your code will effectively be self documenting if you change c and all other one character identifiers to something more reasonable like subtree_size or at least subsize. You won't need comments like /* left and right subtrees */.


What would be the best way to update data from associative array?

"Premature optimization is the root of all evil."

As long as this code works and causes no problem, nothing should be really done. Trying to "improve" it, most likely you will cause a severe harm to readability, maintainability and - ironically - performance.

The only thing could be suggested out of the blue is to wrap the loop in a transaction. It will be a sensible move by itself, and and also could improve the speed in case of some certain settings of the database engine.


Since the instruction is a 32-bit number, you should use uint32_t, rather than assuming that unsigned is 32 bits on the host.

The first version is fine, I think, because it has the least clutter.  An experienced programmer will have no problem figuring out what it does.  If you are concerned about the mental arithmetic required to figure out the width of the bitmasks, you could write it like this:

void instruction_partition(uint32_t instruction, unsigned *op, unsigned *r1, unsigned *r2, unsigned *r3, unsigned *funct, unsigned *offset, unsigned *jsec)
{
    assert(op && r1 && r2 && r3 && funct && offset && jsec);

    *op     = (instruction >> 26) & ((1 << 6) - 1); /* 6 most significant bits */
    *r1     = (instruction >> 21) & ((1 << 5) - 1);
    *r2     = (instruction >> 16) & ((1 << 5) - 1);
    *r3     = (instruction >> 11) & ((1 << 5) - 1);
    *offset = (instruction >>  6) & ((1 << 5) - 1);
    *funct  =  instruction        & ((1 << 6) - 1); /* 6 least significant bits */
    *jsec   =  instruction        & ((1 << 26) - 1);
}

This should compile to identical code as your first implementation.  Technically, the opcode doesn't need to be masked:

    *op = instruction >> 26;


Prim's Algorithm using heapq module in python

1. Review

There is no docstring. What does prims do? What argument does it take? What does it return? The text in the post would be a good starting point for a docstring.
The code has a lot of sequence lookups [1] and [0]. This makes it hard for the reader to follow (what does [1] mean?). It's clearer to use Python's sequence unpacking to provide names for these elements. For example, instead of:

for v in graph[start]:
    heappush(unexplored, [v[1], v[0]])

write something like:

for neighbour, cost in graph[start]:
    heappush(unexplored, (cost, neighbour))

This makes the data structures easier for the reader to follow.
To pick an arbitrary vertex from graph, the code makes a list of all the vertices, which is then thrown away because only the first vertex in the list is needed:

start = list(graph)[0]

It would be better not to make the list at all:

start = next(iter(graph))   # Arbitrary starting vertex

Instead of keeping a list of costs and summing them at the end:

treeCosts = []
# ...
treeCosts.append(winner[0])
# ...
return sum(treeCosts)

it would be simpler to maintain a running total:

total = 0
# ...
total += winner[0]
# ...
return total

Every iteration, the code tests that all vertices have been explored:

while explored != set(graph):

This takes time proportional to the number of vertices in the graph. It would be better to test whether there are any unexplored edges remaining:

while unexplored:

which can be tested in constant time.
Once a winning vertex has been found and added to the tree, all other edges in the heap that end at that vertex are now invalid. The code tries to delete them from the heap by setting their cost to infinity, but this violates the heap invariant. I can see that you attempted to write some code for trying to restore the heap invariant, but this didn't work and you ended up calling heapify instead, but this takes linear time and so leads to unacceptable (quadratic) overall runtime complexity.

This is a problem that often arises when using a heap: how do you efficiently delete an item? Well, there is a way to do it, but it is somewhat complicated (see this answer on Stack Overflow for a description of the method).

However, there is a much simpler solution to this problem: leave the bad item in the heap and postpone dealing with it until it is popped. (See the fourth bullet under "Priority Queue Implementation Notes" in the heapq documentation.) In the minimum spanning tree algorithm this is easy because you can just check against the explored set, like this:

while unexplored:
    cost, winner = heappop(unexplored)
    if winner in explored:
        continue # Already found via a shorter path

You should check that leaving these items in the heap does not affect the runtime complexity (hint: \$O(\log {n^2}) = O(\log n)\$).
The heap is initialized with all the neighbours of the starting vertex:

unexplored = []
for v in graph[start]:
    heappush(unexplored, [v[1], v[0]])

But this duplicates the code for adding the neighbours of the winning vertex:

#adding the new crossing edges to heap
for v in graph[winner[1]]:
    if v[0] not in explored:
        heappush(unexplored, [v[1], v[0]])

It would be simpler to start with just the starting vertex in the heap (at zero cost), and the explored set empty, like this:

explored = set()
unexplored = [(0, start)]

2. Revised code

from heapq import heappush, heappop

def minimum_spanning_tree_cost(graph):
    """Return the sum of the costs of the edges in the minimum spanning
    tree for the given graph, which must be a mapping from nodes to an
    iterable of (neighbour, edge-cost) pairs.

    """
    total = 0                   # Total cost of edges in tree
    explored = set()            # Set of vertices in tree
    start = next(iter(graph))   # Arbitrary starting vertex
    unexplored = [(0, start)]   # Unexplored edges ordered by cost
    while unexplored:
        cost, winner = heappop(unexplored)
        if winner not in explored:
            explored.add(winner)
            total += cost
            for neighbour, cost in graph[winner]:
                if neighbour not in explored:
                    heappush(unexplored, (cost, neighbour))
    return total

3. What if vertices can't be compared?

The heap contains pairs (cost, vertex) which get compared by the heap algorithm to see which is smallest. If two cost values are the same then the heap algorithm will have to compare the vertices to break the tie. This is fine if vertices can be compared (for example if vertices are represented by numbers or strings) but if they cannot be compared then the code will fail with:

TypeError: unorderable types

This is a common problem: see the second bullet under "Priority Queue Implementation Notes" in the heapq documentation. Again, there is a general solution: add a tie-breaking value between the cost and the vertex. itertools.count is a good source of tie-breaking values.

from heapq import heappush, heappop
from itertools import count

def minimum_spanning_tree_cost(graph):
    """Return the sum of the costs of the edges in the minimum spanning
    tree for the given graph, which must be a mapping from nodes to an
    iterable of (neighbour, edge-cost) pairs.

    """
    tiebreak = count().__next__ # Factory for tie-breaking values
    total = 0                   # Total cost of edges in tree
    explored = set()            # Set of vertices in tree
    start = next(iter(graph))   # Arbitrary starting vertex
    unexplored = [(0, tiebreak(), start)] # Unexplored edges ordered by cost
    while unexplored:
        cost, _, winner = heappop(unexplored)
        if winner not in explored:
            explored.add(winner)
            total += cost
            for neighbour, cost in graph[winner]:
                if neighbour not in explored:
                    heappush(unexplored, (cost, tiebreak(), neighbour))
    return total


Using Choose and Apply Templates with Mode, vs Complexless Template Matches

It may not matter a lot for this case, but usually when dealing with XSLT our rule of thumb has been, always to handle different cases with different stylesheets rather than one huge complex XSLT.


Angular 2 window service that listens for 'click away'

Have you explore solutions with the HostListener decorator?

https://stackoverflow.com/questions/40107008/hostlistener-documentclick-angular-2-same-component

Subject and Observable imports are capitalized.

import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';

you can use const instead of let for $target and subject variables since they are not reassigned.

Use triple-equals.

if ($target.closest(sub.selector).length === 0) {
  sub.subject.next(event);
}

You can spot the previous points with the ng lint command.

Lifecycle hooks only work in components.

You can drop the JS convention of prefixing private members with _.

Members of the Subscription class can be marked as readonly. Moreover, Angular is a rxjs-everywhere-framework so Subscription is a confusing name since it's a common type of rxjs.

JQuery is a dependency of your service, maybe it can be treated like every other dependencies, with injection. You can also type the jQuery objects if you install the @types/jquery package.

import { Inject, Injectable, InjectionToken, ValueProvider } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';

import * as $ from 'jquery';

export const DOM_HELPER: InjectionToken<JQueryStatic> = new InjectionToken<JQueryStatic>('DomHelper');
// use the provider in your app.module
export const domHelperProvider: ValueProvider = {provide: DOM_HELPER, useValue: $};

class Subscription {
  constructor(public readonly selector: JQuery.Selector,
              public readonly subject: Subject<JQuery.Event>) {
  }
}

@Injectable()
export class WindowService {
  private subscriptions: Array<Subscription> = [];

  constructor(@Inject(DOM_HELPER) private $: JQueryStatic) {
    this.$(window).click((event: JQuery.Event): void => this.onWindowClick(event));
  }

  public clickAway(selector: JQuery.Selector): Observable<JQuery.Event> {
    const subject = new Subject();
    this.subscriptions.push(new Subscription(selector, subject));
    return subject.asObservable();
  }

  private onWindowClick(event: JQuery.Event): void {
    const $target = this.$(event.target);
    this.subscriptions.forEach((sub: Subscription): void => {
      if ($target.closest(sub.selector).length === 0) {
        sub.subject.next(event);
      }
    });
  }
}

Your code works but it's buggy. The subscriptions array will never stop growing and may cause performance issue. You can add an "unsubscribing" method in your service, components will call it in their ngOnDestroy method; but I think it's a bad design, consumers of your service will forget to call the method for sure because they will assume that they only have to unsubscribe from the observable you provide.

You have to get rid of this array. I suggest creating an Observable directly from the click events and then filtering it in clickAway:

import { Inject, Injectable, InjectionToken, ValueProvider } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/filter';

import * as $ from 'jquery';

export const DOM_HELPER: InjectionToken<JQueryStatic> = new InjectionToken<JQueryStatic>('DomHelper');
export const domHelperProvider: ValueProvider = {provide: DOM_HELPER, useValue: $};

@Injectable()
export class WindowService {
  private observable: Observable<Event>;

  constructor(@Inject(DOM_HELPER) private $: JQueryStatic) {
    this.observable = Observable.fromEvent(window, 'click');
  }

  public clickAway(selector: JQuery.Selector): Observable<Event> {
    return this.observable
      .filter((event: Event): boolean => this.$(event.target).closest(selector).length === 0);
  }
}

Finally you don't need jQuery to achieve the functionality and you can use Angular and native types in your API:

import { ElementRef, Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/filter';

@Injectable()
export class WindowService {
  private observable: Observable<Event>;

  constructor() {
    this.observable = Observable.fromEvent(window, 'click');
  }

  public clickAway(el: ElementRef): Observable<Event> {
    return this.observable.filter((event: Event): boolean => !el.nativeElement.contains(event.target));
  }
}

Example of a component using the service:

import { Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { WindowService } from '../window.service';
import { Subscription } from 'rxjs/Subscription';

@Component({
  selector: 'app-closable',
  templateUrl: './closable.component.html',
  styleUrls: ['./closable.component.css']
})
export class ClosableComponent implements OnInit, OnDestroy {

  @ViewChild('outside')
  private outside: ElementRef;

  private subscription: Subscription;

  constructor(private window: WindowService) {
  }

  ngOnInit() {
    this.subscription = this.window.clickAway(this.outside).subscribe(() => console.log('clicked away!'));
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

and its template:

<div>
  closable works!
  <div #outside>
    <button>click outside of me</button>
  </div>
</div>


C++ Circular buffer through Circular iterator

High level overview:

The idea is solid, but creating an iterator adapter to make the container behave differently just sounds weird. It would be better to have container adapters, as std::stack<> and std::queue<> do.

Implementation overview:

The code has a serious issues. Mainly the following:

It has a chance to break on some algorithms:

auto second = ++first;

where first is circularIterator<> will make second to be baseIter.  The most dangerous ones are sorting algorithms, especially those that use divide and conquer. The template type parameter is usually only one, e.g. only one type of iterators are allowed, as a result the compiler will issue substitution failure error.

Will not work on idiomatic while (*first++ != last) or similar.

The postfix increment is deleted, thus it disables probably most of the standard library.

The class pretends to be an iterator, but is a range.

Usually iterator should know about its own internal state only. Knowing end iterator should be last resort. Actually, the reason for storing the range is because the code doesn't provide a function to create a pair of circularIterators. If such function would be provided, the operator==() of parent iterator would still work, as they mostly take it by reference.

Cosmetics:

Not really important, but here they are:

Usually people name types (and classes, as a result) in CamelCase or snake_case. camelCase starting from regular letter are used for variable names.
Template type parameters are named using CamelCase, since in the future they will probably become Concepts.
Indentation and brace placing is very weird.

Misc:

using namespace std; is bad. It causes name clashes and in general confuses other mechanisms of C++.
std::endl is a performance drainer. If done in a tight loop, can cause serious issues. Bjarne Stroustrup himself didn't use it for a decade.


Forecasts for construction equipment dealers

Took some work but got a 25-30% speedup (down from roughly 5.2 to 3.8 seconds) on the sample data you provided along with cleaner code. I'm hoping that when you scale it across the full data the gains will be larger but tbd
So what are the changes?

Move whatever possible outside loops. Your future value never changes but you recreate it (relatively inefficiently) and do other DataFrame manipulation every loop which would be 1,200 times total. Not the biggest drain but it's there.

List comprehension can be a bit faster than going through regular loops and multiple assignments. Everything I could pull into a single function like pd.read_csv or pd.date_range or list comprehension I did

Slightly faster Dataframe filtering by setting df.index = "dealer" and using df.loc[np.in1d(df.index, dealer)][['ds', 'y']]. If you really want to squeeze out performance that's the fastest way I can find but probably not worth the hit to readability in normal code. Still, I left it in.

Are those three improvements? Sure. They'll add up over enough data but they're still shaving fractions of a second off. The real resource killer is Prophet doing the modeling/forecasting itself which leads to

Parallelizating Prophet with multiprocessing.Pool.imap. Instead of a loop creating the future range and then the filtering and then modeling and forecasting the data for each unique dealer now it's going to utilize multiple processors to work on each forcast more-or-less simultaneously. Probably not all 1,200 at once but more than 1. That's what accounts for most of the speedup and why hopefully you'll get even larger gains like maybe 2-4x (that's very loose guess, no promises) on the full data.

Rewrite:
from fbprophet import Prophet
import pandas as pd
import numpy as np
from multiprocessing import Pool, cpu_count

def forecast_data(args):
    (df, dealer, dates) = args

    model = Prophet()
    model.fit(df.loc[np.in1d(df.index, dealer)][['ds', 'y']])

    return model.predict(dates)

if __name__ == "__main__":
    df = pd.read_csv('X.csv', header=0, names=['ds', 'dealer', 'y'],
                     parse_dates=['y'], index_col="dealer")

    date_range = pd.date_range('2020-11', '2024-12', freq='MS')
    date_range = pd.DataFrame(date_range, columns=['ds'])

    p = Pool(cpu_count())

    results = pd.concat(
        [result for result in p.imap(
            forecast_data,
            [(df, dealer, date_range) for dealer in df.index.unique()]
        )])

    results.to_csv('X2.csv')

P.S. If you wonder why forecast_data takes a tuple and unpacks it it's because I tried to write a memoized factory function that took df and dates are arguments and returned forecast(dealer) but that caused multiprocessing to have a pickle about using a local pickle.


I can see two issues with your code:

It doesn't work. Because the local variables filterTimeStart and filterTimeEnd are put in the closure, and the Where() lambdas are executed only when you iterate the resulting enumerables, all of your schedules will be the same as AfterTomorrowGroupedSchedules, because the last value assigned to the locals will be used. You can fix this by using ToArray().
It's not DRY. The whole LINQ expression is always exactly the same and the interval is always one day. You should extract that into another method.

The modified code:

private IEnumerable<IGrouping<string, EventSchedule>> GroupedSchedulesForADay(
    DateTime filterTimeStart)
{
    return EventScheduleList.Where(
        s => s.RecurrenceStart >= filterTimeStart &&
            s.RecurrenceStart < filterTimeStart.AddDays(1))
        .GroupBy(p => p.BasePlace)
        .ToArray();
}

private void FillSchedulesByFilter()
{
    var filterTimeStart = DateTime.Today.AddHours(6);

    TodayGroupedSchedules = GroupedSchedulesForADay(filterTimeStart);

    filterTimeStart = filterTimeStart.AddDays(1);

    TomorrowGroupedSchedules = GroupedSchedulesForADay(filterTimeStart);

    filterTimeStart = filterTimeStart.AddDays(1);

    AfterTomorrowGroupedSchedules = GroupedSchedulesForADay(filterTimeStart);
}

Technically, the ToArray() is not necessary anymore, because each invocation of the GroupedSchedulesForADay() method has its own local variable, but I think it's still a good idea.

Also, I was worried that AddHours(6) wouldn't work correctly in the days where daylight saving time changes, but it seems it does work.

If the collection was big, it could make sense to iterate it just once, instead of three times, and build the three collections manually item by item, but it seems that's not necessary here.


Getting all public constants from the main and nested classes

How about this:

private static IEnumerable<FieldInfo> GetPublicConstants(Type type)
{
    return GetPublicClassConstants(type)
        .Concat(type.GetNestedTypes(BindingFlags.Public).SelectMany(GetPublicConstants));
}

private static IEnumerable<FieldInfo> GetPublicClassConstants(Type type)
{
    return type
        .GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
        .Where(fi => fi.IsLiteral && !fi.IsInitOnly);
}

OR, as I do enjoy playing PGA Pro Code Golf:

private static IEnumerable<FieldInfo> GetPublicConstants(Type type)
{
    return type
        .GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
        .Where(fi => fi.IsLiteral && !fi.IsInitOnly)
        .Concat(type.GetNestedTypes(BindingFlags.Public).SelectMany(GetPublicConstants));
}


Checking for a condition, even if it's always true

Don't use a comment. Use code. Specifically, assert builder.length() >= 2 and assert builder.charAt(builder.length() -2) == ' '. Assertions will clearly indicate the preconditions, and they can be excluded by the compiler or jvm so they don't impact the deployed code.


Generally speaking, the schema looks good and well organized, however a few columns could use some refactoring. Here is what I can point to.

Users table

  'username' VARCHAR(25) NOT NULL,

This seems a bit small for a user name. While I'm pretty sure most users will choose names below 25 characters, I would expand it a bit just for the sake of safety. I think 50 or so will do.

  'password' VARCHAR(255) NOT NULL,

This smells at first sight. Maybe I'm wrong, but this sounds as a plain-text password, which is utterly wrong. Column size should match the output size of the used hash function, plus the size of the salt and hash parameters (or split those into separate columns). And don't even think of SHA1 or MD5 :P Use PBKDF2, bcrypt or scrypt for this. Look here for a more detailed discussion of password hashing.

  'first_name' VARCHAR(255) NOT NULL,
  'last_name' VARCHAR(255) NOT NULL,

This design is very specific for most occidental names of people, but wrong in the general case. People's names in many part of the world don't fit into first/last name, and for the most part a single, longer column will do. Read this article for more details about this.

Additionally, do you really need the real name of the user? Doesn't the username suffices? Or the real name is to be displayed somewhere?
All in all, I would put it as

'real_name' VARCHAR(1000) NOT NULL,

  'gender' ENUM('M', 'F'),

In many case, and specially in a social network environment (and more if you will allow search by gender), that restriction is not enough, as human gender identity goes far beyond male/female. Just for the record, New York recognizes 31 and Facebook 71, so I think your DB should at least take that into consideration.

What I would do is separate the possible genders into its own table (that you can fill separately) and put a foreign key in users:

CREATE TABLE Genders (
'gender_id' INT(20) NOT NULL AUTO_INCREMENT,
'name' VARCHAR(100) NOT NULL,
PRIMARY KEY ('gender_id'),
UNIQUE KEY ('name')
);

And in users:

'gender_id' INT(20),
FOREIGN KEY ('gender_id') REFERENCES Genders('gender_id')

  'city' VARCHAR(255),
  'state' VARCHAR(255),
  'country' VARCHAR(255),

Generally, this is a bad practice, as it would lead to repeated and inconsistent data, and difficult searches by city/country (as anyone can write it the way he wants). A better way is to normalize this into separate tables for cities/states/countries, and leave a reference to the city in the users table (and in turn, a city implies a state and a country):

CREATE TABLE Countries (
'country_id' INT(20) NOT NULL AUTO_INCREMENT,
'name' VARCHAR(100) NOT NULL,
PRIMARY KEY ('country_id'),
UNIQUE KEY ('name')
);

CREATE TABLE States (
'state_id' INT(20) NOT NULL AUTO_INCREMENT,
'name' VARCHAR(100) NOT NULL,
'country_id' INT(20) NOT NULL,
PRIMARY KEY ('state_id'),
UNIQUE KEY ('name','country_id')
);

CREATE TABLE Cities (
'city_id' INT(20) NOT NULL AUTO_INCREMENT,
'name' VARCHAR(100) NOT NULL,
'state_id' INT(20) NOT NULL,
PRIMARY KEY ('city_id'),
UNIQUE KEY ('name','state_id')
);

Those should be populated by you, then the users just select one of the options, and that allows proper searches. In users you only have a reference to city:

'city_id' INT(20) NOT NULL,
FOREIGN KEY ('city_id') REFERENCES Cities('city_id')

  'birth_date' VARCHAR(255),

As stated in the comments, this should be of type DATE.

  'active' ENUM('yes','no') NOT NULL DEFAULT 'no',

An enum is not the most optimal data type here. It's better to use BIT instead.

Table Posts

Generally, the layout looks good, I would not split it into images/videos, at least for now. This is due both storing basically the very same data, with only the file type differing. Only consider such a split if each type requires different columns. Other than that, I have this few tips about this table:

First of all, I would add a comment column so that users can write a bit about the photo/video they just posted (in addition to the simple caption).

'comment' TEXT NULL

  'post_url' VARCHAR(255) NOT NULL,

Is this really necessary? Why store the full URL when you can deduce it from other columns? Specifically, the id, or better, the caption, can be used to build unique URLs for each post without needing to generate a new piece of data.

Table Followings

  PRIMARY KEY ('user_id', 'following_id'),
  UNIQUE INDEX ('following_id', 'user_id')

This is redundant. The primary key is, by definition, unique. The unique key is therefore unnecessary and can be removed.

General comments

One thing I would do is to be explicit about nullability of each column, even if the default favors your particular case. Being explicit doesn't hurts, and it better helps readability, so I would suggest always stating each column as NULL/NOT NULL.

You might consider the posibility of allowing users like comments too, in addition to the main posts (as the likes table handles).

You can also consider the option of adding some history tables for registering each edition of posts (pretty much like StackOverflow does), in addition to the date_updated column, if you may need additional audits or rollback capability.


Iterative version of a permutations algorithm

As often, the recursive algorithm is readable and beautiful, but not very efficient: stack consumption can be overwhelming, memory allocations are plentiful, and you're forced to compute the whole set of permutations at once.

When you mechanically translate the recursive algorithm into its iterative form, you often lose most of its beauty and readability, without gaining much on the front of performance: you just emulate with a data structure what the compiler would have done. It might be useful sometimes but you can generally assume that the compiler will do a better job than yourself.

Hence I would recommend looking into two alternative approaches:

the first is to do it the standard library way, and provide a std::next_permutation function which return the next permutation in the lexicographical order (see for instance my answer to this question). It can be improved upon though, with the SJT algorithm, and that would be an exercise of choice;
the second is to keep the general, incremental reasoning of the recursive algorithm, but use the additional knowledge you get in the iterative form: indeed, on the contrary to the recursive form, you know upfront how many permutations you'll return in the end, and thus can avoid all but one allocation.

For instance:

#include <vector>

std::vector<std::vector<int>> permutations_set(const std::vector<int>& set) {

    if (set.empty()) return {};

    auto current = std::begin(set);

    // the unique memory allocation
    std::vector<std::vector<int>> permutations(factorial(set.size()), {*current});

    for (++current; current != std::end(set); ++current) {
        std::size_t offset = 0; // offset plays the central role here; you could say it replaces the stack
        for (auto& permutation : permutations) {
            const auto initial_size = permutation.size();
            permutation.insert(std::next(std::begin(permutation), offset), *current);
            if (offset++ == initial_size) offset = 0;
        }
    }

    return permutations;
}


I have a couple of thoughts on this in terms of coding style,
but not really regarding robustness.
I hope you'll get more in-depth reviews in terms of robustness too!

Simplifying the complex if-else chain of loginElement

In this code:

var loginElement = null;
if (buttonElements != null){
    loginElement = getSubmitElement(buttonElements);
}
if (loginElement != null){
    console.log(loginElement);
    loginElement.click();
}
else{
    // ...
}

Notice that if buttonElements is null, then loginElement will still be null after the first if statement, in which case the second if will be pointless.
This is equivalent to the above but without the wasted step:

var loginElement = null;
if (buttonElements != null){
    loginElement = getSubmitElement(buttonElements);
    if (loginElement != null){
        console.log(loginElement);
        loginElement.click();
    }
}
else{
    // ...
}

On closer look, the entire if-else chain can be simplified to this:

var loginElement = null;

if (buttonElements != null) {
    loginElement = getSubmitElement(buttonElements);
} else if (inputElements != null) {
    loginElement = getSubmitElement(inputElements);
} else if (linkElements != null) {
    loginElement = getLinkElement(linkElements);
}

if (loginElement != null) {
    console.log(loginElement);
    loginElement.click();
}

Cache duplicated operations in a local variable

In this statement,
in the worst case,
the type variable will be lowercased twice:

if (type.toLowerCase() == 'submit' || type.toLowerCase() == 'image'){

It would be better to lowercase only once and store in a local variable:

var normalizedType = type.toLowerCase();
if (normalizedType == 'submit' || normalizedType == 'image') {

Simplify else-if chains using early returns

When you return in the if-else-if branches like this:

if (isLoginElement(elements[i],'id')){
    return elements[i];
}
else if(isLoginElement(elements[i], 'name')){
    return elements[i];
}
else if(isLoginElement(elements[i],'class')){
    return elements[i];
}

You can drop the else, which makes it slightly simpler:

if (isLoginElement(elements[i],'id')) {
    return elements[i];
}
if (isLoginElement(elements[i], 'name')) {
    return elements[i];
}
if (isLoginElement(elements[i],'class')) {
    return elements[i];
}

Other simplification

This code:

if (attr != null){
    if (hasLogin(attr)){
        return true;
    }
}
return false;

Can be written simpler as:

return attr != null && hasLogin(attr);


Passing anonymous functions and getting variables from an outer scope

Something like this would get you most of the way there:

<?php
function h($val) {
    echo $val;
}

function template_function($template_body) {
    return function(array $template_output_variables = null) use ($template_body) {
        if ($template_output_variables !== null) {
            extract($template_output_variables);
        }
        $contents = eval('?>'.$template_body.'<?php');
        echo $contents;
    };
}

$contact_us = template_function('
    <body>
    Hello World Body Text, Hello <?php h($name);?>.
    </body>'
);

$contact_us(array('name' => 'Johnny Boy'));

But it's evil, and you will likely end up with very odd, very hard-to-debug errors once your templates are of reasonable size/complexity. It's an interesting idea though -- if you pursue it, make sure you have a thorough set of test cases ;)

The easiest way to clean it up, IMO, would be to do away with allowing raw php in the templates. I'm pretty partial to Twig, you may be able to find some inspiration there.


One loop to rule all animation.
For almost all realtime animations the whole thing is handled from one timed loop running at as close to a constant rate as is possible.
Having many different timers call many different functions quickly gets complicated and very hard to follow.
For the browser requestAnimationFrame should be used for any content animations. It calls a special functions that holds any changes made to the DOM in a back buffer until the next display vertical refresh (60 times a second)
This ensures that the animation is in sync with the display and any other DOM rendered content.
You use that function as the main loop to control all the associated animation content.
Simulating the typist
You have over complicated the typer. All that is needed is the current character position and a way to move and clear lines when a newline char is found.
The function called by requestAnimationFrame is given the current time since the page loaded. You can use that time to calculate the character position and then iterate over the characters needing to be added, checking for new lines.
A variable is kept currentLine that holds the current typing line and you just append text to that as you go.
To reduce the load you can reuse existing elements, removing it from the top, and appending it to the bottom. See newLine function in example below
Example
Rather than change your code, I have started from scratch. There is one main loop function called typer and a function to setup a new line. The character position is calculated by dividing the time since start by the speed.
If you want to speed up the rate of characters just subtract from the start time. I have added an example that randomly speeds up every 1/20 character. To slow down just add to the start time.

requestAnimationFrame(typer);

const words = `
 Testing type writer.
 And now some more text.
 You can remove some<<<<<<<<<<<delete text as well.
 Displays a typing effect on the home page.
 If you want to speed up the rate of characters just subtract from the start time.
 I have added an example that randomly speeds up every 1/20 character.
 To slow down just add to the start time.`;

const leftChar = ":>";
const textContainer = document.getElementById('typingText');
const speed = 100;
var startTime;
var lastCharPos;
var currentLine;

for (let i = 0; i < 2; i++) {
  textContainer.appendChild(Object.assign(document.createElement("div"), {
    className: "typed--typed-text",
    textContent: ""
  }));
}
// removes top line, clears it and adds to bottom of container
function newLine() {
  currentLine = textContainer.querySelector(".typed--typed-text");
  textContainer.removeChild(currentLine);
  textContainer.appendChild(currentLine);
  currentLine.textContent = leftChar;
}

function typer(time) {
  var str = "";
  if (startTime === undefined) {
    newLine();
    startTime = time;
    lastCharPos = 0;
  }

  // 1 in 20 characters are 50ms faster
  if (Math.random() < 0.05) { startTime -= 50 }

  const charPos = (time - startTime) / speed | 0;
  while (lastCharPos <= charPos) {
    const char = words[(lastCharPos++) % words.length];
    if (char === "\n") {
      currentLine.textContent += str;
      str = "";
      newLine();
    } else if (char === "<") {
      const text = currentLine.textContent;
      currentLine.textContent = text.substring(0,text.length-1);
    } else {
      str += char;
    }
  }
  currentLine.textContent += str;
  requestAnimationFrame(typer);
}
.typed {}

.typed--typed-text {}
<div id="typingText" class="typed">
</div>


No need of TokenType: data Token = Identifier String | RealNumberLiteral String | PlusSign ...
No need of nested let statements, see http://learnyouahaskell.com/syntax-in-functions#let-it-be
camelCase naming is preferred everywhere.
generally it is more efficient to aggregate lists using cons (: operator), and reverse at the end, if needed. It is about tokens ++ [next_token] fragment.
read_token could return a tuple of token and the rest string, no need to drop (length next_token_lexeme) source_code after that.

Note, I didn't inspect code logic at all.


Compute Manhattan distance from origin given a set of left-right-step directions

Your code looks more complicated than necessary for this task.

The first thing I noticed was the directions N, E, S, W. There is no need to explicitly name them. It is simpler to just define a direction as a 2-dimensional tuple:

struct Direction {
    dx: i32,
    dy: i32
}

That's the essence of a direction. As the next step, I remembered that rotating such a direction by 90 degrees is quite simple. It just involves swapping the coordinates and reversing one of them. To get these right, I manually checked all the combinations after writing this code:

impl Direction {
    fn left(&self) -> Direction { Direction { dx: self.dy, dy: -self.dx } }
    fn right(&self) -> Direction { Direction { dx: -self.dy, dy: self.dx } }
}

By these simple definitions, I avoided dealing with N, E, S, W at all.

When I tested the program using the example you provided, my IDE added a trailing newline to the file, as is usual for text files. Then the program crashed because it could not parse an empty string. Therefore I changed split_dir(&s) into split_dir(s.trim()), and it worked.

To understand the main program, I separated it into the part that deals with input and output, and the processing part in between. To do this, I defined this function:

fn manhattan_distance(s: &str) -> i32 {
    ...
}

I inlined the split_dir, update_x, update_y and get_manhattan_dist functions, and in the end my code became:

use std::fs;

struct Pos {
    x: i32,
    y: i32,
    dir: Direction,
}

struct Direction {
    dx: i32,
    dy: i32,
}

impl Direction {
    fn left(&self) -> Direction {
        Direction {
            dx: self.dy,
            dy: -self.dx,
        }
    }

    fn right(&self) -> Direction {
        Direction {
            dx: -self.dy,
            dy: self.dx,
        }
    }
}

fn manhattan_distance(s: &str) -> i32 {
    let steps = s.trim().split(", ");

    let mut pos = Pos {
        x: 0,
        y: 0,
        dir: Direction { dx: 0, dy: -1 },
    };

    for step in steps {
        let (turn, dist) = step.split_at(1);

        // Update direction
        pos.dir = match turn {
            "L" => pos.dir.left(),
            "R" => pos.dir.right(),
            _ => panic!("invalid turn {} in step {}", turn, step),
        };

        // Update position
        let dist = dist.parse::<i32>().unwrap();
        pos.x += pos.dir.dx * dist;
        pos.y += pos.dir.dy * dist;
    }

    pos.x.abs() + pos.y.abs()
}

fn main() {
    let s = fs::read_to_string("2016-1.txt").expect("Failed to read file.");

    println!("{}", manhattan_distance(&s));
}

What's left now are some automatic tests. The function manhattan_distance is well-prepared for that since it has no side-effects, does not need any input or output, gets its parameter as a simple string and just returns its result.

And here are some example tests. You should add some more to explore other interesting cases, like crossing the x or y axis. The current tests might also pass if you omit the calls to abs.

#[cfg(test)]
mod tests {
    use crate::manhattan_distance;

    #[test]
    fn manhattan_distance_example() {
        assert_eq!(11, manhattan_distance("R5, L2, L1, R1, R3, R3, L3, R3, R4, L2, R4, L4, R4"))
    }

    #[test]
    fn manhattan_distance_empty() {
        assert_eq!(0, manhattan_distance(" \t\n"))
    }

    #[test]
    fn manhattan_distance_simple() {
        assert_eq!(13, manhattan_distance("R8, L5"))
    }

    #[test]
    fn manhattan_distance_rectangle() {
        assert_eq!(0, manhattan_distance("R8, L5, L8, L5"))
    }
}

Your code is a good working base, it was just longer than necessary. I also changed most of the variable names to be a little more precise and easier to grasp for a casual reader of the code. For example, since the task talks about "steps", it's only natural to name the corresponding variables in the code also "steps" and "step".

Since this is my first real program in Rust as well, I don't know what the really idiomatic Rust code looks like, I hope I could improve the code nevertheless.

To check whether I made any typical beginner's mistakes, I ran cargo-clippy, and I didn't get any complaints.


Your code is fine. Nevertheless, removing unnecessary braces can increase readability:

def traverse(dir: File, proc: File => Unit): Unit =
  dir.listFiles foreach { f => if (f.isDirectory) traverse(f, proc) else proc(f) }


Using goto with DataReader to get sproc return value

Is my use of goto then justified?

First of all, let me push back on the question. A goto does not require a justification any more than any other language feature requires a justification.

That said, a goto is widely considered to be a sign that the code is inelegant, confusing or hard to maintain.  It is definitely a sign that you should be thinking hard about how the control flow of the code works, and whether there is a refactoring that would make it more clear.

You are doing that, and that's excellent.  The problem is that you've only identified two alternatives to a goto: refactoring into nested "if" statements, which as you note may be harder to read than the goto version, and using "throw" to simulate a goto. That's a bad practice; throw should be used to indicate an unexpected error condition, not as a very expensive way to simulate a goto.

You missed the preferred way to remove a goto: turn it into a return.

void DoTheFirstThing()
{
  using( DbDataReader rdr = cmd.ExecuteReader() )
  {
    if( !rdr.Read() ) return;
    ret.Foo  = ReadFoo( rdr );
    if( !rdr.NextResult() ) return;
    List<Bar> bars = new List<Bar>();
    while( rdr.Read() ) bars.Add( ReadBar( rdr ) );
    ret.Bars = bars.ToArray();
    if( !rdr.NextResult() ) return;
    ret.Qux = ReadQux( rdr );
    if( !rdr.NextResult() ) return;
    List<Blargh> blarghs = new List<Blargh>();
    while( rdr.Read() ) blarghs.Add( ReadBlargh( rdr, ) );
    ret.Blarghs = blarghs.ToArray();
    ...
   }
}

void DoTheSecondThing()
{
  Int32 returnValue = (Int32)returnParameter.Value;
  switch( returnValue ) {
    case 0: // do stuff
    case 1: // do other stuff
    case ...
  }
  ...
}

void DoTheThings()
{
  DoTheFirstThing();
  DoTheSecondThing();
}

There, no gotos required, and your program is now refactored into smaller methods that each do one task well, rather than one god method that tries to create the whole universe in one go.

While we are criticizing your code, I note that this also looks a bit dodgy:

    if( !rdr.NextResult() ) return;
    List<Blargh> blarghs = new List<Blargh>();
    while( rdr.Read() ) blarghs.Add( ReadBlargh( rdr, ) );
    ret.Blarghs = blarghs.ToArray();

Suppose NextResult is false, and so we take the return. What now is the value of the blarghs field of object ret?  Is it null?  Is it intended to be null?  Is the user of this field supposed to understand that it can and will be null if the reader ran out of results, and that if it is not null, then it is a non-empty array?  This is a lousy contract. It is much better to say "blarghs will be a non-null array that might be empty", and not "blarghs is either null or a non-empty array".  I would be inclined to re-think your deserialization strategy here so that more of the deserialized object is in a good state:

IEnumerable<Bar> ReadBars(Reader rdr)
{
    if( !rdr.NextResult() ) yield break;
    while( rdr.Read() )
      yield return ReadBar( rdr );
}

IEnumerable<Blargh> ReadBlarghs(Reader rdr)
{
    if( !rdr.NextResult() ) yield break;
    while( rdr.Read() )
      yield return ReadBlargh( rdr );
}

void DoTheFirstThing()
{
  using( DbDataReader rdr = cmd.ExecuteReader() )
  {
    // Move the check for the goodness of the reader into ReadFoo,
    // readQux, etc.

    ret.Foo  = ReadFoo( rdr );
    ret.Bars = ReadBars( rdr ).ToArray();
    ret.Qux = ReadQux( rdr );
    ret.Blarghs = ReadBlarghs ( rdr ).ToArray();
   }
}

OMG look at how much better that code reads now.

BUT WAIT THERE'S MORE. Let's make this an extension method and parameterize it with a function:

static class Extensions
{

  public static IEnumerable<T> ReadThings<T>(this Reader rdr, Func<Reader, T> f)
  {
    if( !rdr.NextResult() ) yield break;
    while( rdr.Read() )
      yield return f( rdr );
  }
  public static Foo ReadFoo(this Reader rdr)
  {
     if (!rdr.Read) return DefaultFoo;
     ...
  }
  // Similarly for ReadQux ...
}
...
void DoTheFirstThing()
{
  using( DbDataReader rdr = cmd.ExecuteReader() )
  {
    ret.Foo  = rdr.ReadFoo();
    ret.Bars = rdr.ReadThings(ReadBar).ToArray();
    ret.Qux = rdr.ReadQux();
    ret.Blarghs = rdr.ReadThings(ReadBlargh).ToArray();
  }
}

Isn't that about a million times nicer to read than what you wrote?  Look at how in this code the meaning shines through. In your code it looks like the most important thing is the reader and managing whether it is done or not. In this code it looks like the most important thing is that we are reading a Foo, some Bars, a Qux and some Blarghs.  Which way do you think will be easier to understand and maintain?

We've used higher level functions and extension methods for the win. You could be making this code tiny and super easy to read, compared to its present enormous sprawling repetitive goto-laden spaghetti.

Think about where this refactoring gets you. Now if you want to someday in the future say hey, you know, I actually only want to deserialize the frobby bars:

    ret.Bars = rdr.ReadThings(ReadBar).Where(bar => IsFrobby(bar)).ToArray();

DONE.

Or, you know what, we serialized out a bunch of bars, but what we need in memory is actually a bunch of fubars:

    ret.Fubars = rdr.ReadThings(ReadBar).Select(bar => MakeFubar(bar)).ToArray();

Nice. You want to make a change like that, you make it in one place with clear, self-documenting code.

And now you see the true power of thinking "is this goto a bad idea?"  By thinking it through carefully you can take the intuition that the goto is inelegant and manage to refactor your program into something that is small, powerful, and cheap to change when requirements change. So by all means, keep on thinking about whether those gotos are inelegant -- just think the problem all the way through, rather than stopping on some not-actually-better solution like using a throw or a break or a continue to simulate a goto.


A few observations:

s_t = np.zeros(n) and r_t = np.zeros(n) are more than you need. Since you don't actually use the array values but solely overwrite them, you can use np.empty here.

You're doing quite a bit of redundant work in the for loop.

When calculating s_t[i], numpy basically has to repeat all the computations it has already done for s_t[i-1]. If you have a look at the definition of np.std, you can see that the mean plays a role here. Since you have already come up with a nice solution for the mean value, you could reuse it here:

s_t = np.empty(n)

for i in range(n):
    s_t[i] = np.mean((sig[:i+1] - mean_t[i])**2)
    ...
s_t = np.sqrt(s_t)

I validated this against the original code with np.allclose.

r_t also has some extra work that you can get rid of. At the moment your code does the following:

x_t = y - t * mean_t[i]
r_t[i] = np.ptp(x_t[:i + 1])

All the values of x_t at [i+1:n] are computed, but never used, so you can do

r_t[i] = np.ptp(y[:i+1] - t[:i+1] * mean_t[i])

instead, without changing the outcome. You could also write this as two list comprehensions:

s_t = np.sqrt(
    np.array([np.mean((sig[:i+1] - mean_t[i])**2) for i in range(n)])
)
r_t = np.array([np.ptp(y[:i+1] - t[:i+1] * mean_t[i]) for i in range(n)])

Or even a single one if you'd like to get a little bit creative:

rs_t = np.array([
    [
        np.mean((sig[:i + 1] - mean_t[i])**2),
        np.ptp(y[:i + 1] - t[:i + 1] * mean_t[i])
    ] for i in range(n)
])
rs_t[:, 0] = np.sqrt(rs_t[:, 0])

A fully vectorized computation of x_t I have come up with, starting from

x_t = y.reshape(1, -1) - mean_t.reshape(-1, 1) @ t.reshape(1, -1)

is considerably slower than the looped version.

I'm actually not quite sure about the rest of the code from this point on at the moment. I will have to take a closer look to give a meaningful review performancewise. As a first non-functional feedback I would like to invite you to think about more meaningful variable names in the future. Especially there at the end of the code around the least-squares optimization, they are quite hard to understand.

I did some timing of different versions of this algorithm. The full benchmark code can be found in this gist. This is what I got so far (for n=15360):

base:              3.748915s
better_loop:       2.605374s
double_lc:         2.430255s
single_lc:         2.445943s
-----------------------
base_numba:        0.866583s
better_loop_numba: 0.813630s
double_lc_numba:   0.776361s
single_lc_numba*:  N/A

The lower group of results uses numba, a just-in-time compiler for Python code, that can sometimes help to speed up loops. Unfortunately, numba does not support all types of array operations in its fast nonpython mode, e.g. I could not get the single list comprehension version to properly work with numba.

The results are actually a little bit worse than I had originally expected, especially without numba, but there is still a good amount profiling work to be done here.


Labeled loops

You say

                        break inner;

But that's not necessary.  The inner loop is already the innermost loop.  You could just say break;.

And frankly, you could have just said

                for (int j = i-1; j >= 0 && arr[j] > arr[hole]; j--)

No break or internal if needed.

But that's not the question you really wanted answered.

Insertion sort?

It's similar to an insertion sort.  Your insertion method is a bit odd though.  Normally insertion sort would find the insertion point and then move the elements after that.  You're bubbling the current value forward.

Consider

int j = i - 1;
while (j >= 0 && numbers[j] < numbers[i]) {
    j--;
}

int temp = numbers[i];
for (int k = i; k > j; k--) {
    numbers[k] = numbers[k - 1];
}

numbers[j] = temp;

That does about half as many array assignments as your method.

Naming

I prefer a descriptive name like numbers to a generic abbreviation like arr.  At minimum, it should be array.  But I prefer numbers.

    static void sorter(int arr[])

As a general rule, we name classes and objects with noun names.  Methods get verb names.  So

    static void sort(int[] numbers) {

In Java, we also normally write arrays as int[] name not int name[].

You could name the class

class InsertionSorter {

Although in this case InsertionSort can be used as a noun.

Wildcard imports

import java.util.*;

The general policy is to import one class at a time, not a wildcard group.  That's especially true here, since it's not clear that you are using any java.util classes.

Mixing logic and display

It's generally agreed that it is better to return the data and display it separately.  Since you are sorting in place, that could just look like

InsertionSort.sort(numbers);
System.out.println(Arrays.toString(numbers));

Declare at initialization

You have

                hole = i;

You could do

                int hole = i;

It's generally considered best practice to declare variables as late as possible.  You don't use hole outside the loop or across iterations, so there's no need to declare it outside the loop.

Redundant logic

        if(n>=2)
        {
            for(int i = 1; i<n ; i++)

If n is 1 or less then 1 < n will be false and it won't enter the loop.

And you don't need n.  You can just say numbers.length whenever you need that value.

Standard methods

You could also replace these two loops with Java standard methods.

        int insertionPoint = Arrays.binarySearch(numbers, 0, i, numbers[i]);
        if (insertionPoint < 0) {
            insertionPoint = -insertionPoint - 1;
        }

        int temp = numbers[i];
        System.arraycopy(numbers, insertionPoint, numbers, insertionPoint + 1, i - insertionPoint);
        numbers[insertionPoint] = temp;

Of course, it's possible that you were trying to avoid standard methods.  After all, Arrays.sort would solve this problem without additional coding.


Regarding the vectorized code:

permute can be considered a "Zero-cost operation".
Logical operations are performed fastest using bsxfun.
Arithmetic operations are fastest using bsxfun.

Therefore, it's close to impossible to improve the performance of the vectorized code you've posted.

Now, the question is: Is it correct?

It's hard to tell without knowing the exact data, but just by reading the code and your comments, I would think it is.

The reason why I think it is correct, even though the if conditions didn't return the same result:

You're comparing floating point values using ==. Check out Is floating point math broken?

When checking for equality, you should always use some tolerance. Have a look at the example below, where we are comparing 0.3 with 0.1 + 0.2:

x = 0.1;
y = 0.2;
z = 0.3;
the_same = (z == (x + y))
the_same =
     0
the_same = abs(z - (x + y)) < eps
the_same =
     1


Overall, it looks great. The code is clear and easy to follow, you leveraged the standard library well, and performance should be decent decent. There are however, a few things that could be improved.

It might be worth templating the comparison. All that you would have to change is passing an extra argument to make_heap, pop_head and push_heap. There's really not much of a reason to not template the comparator unless I'm missing something.

top() should return a const reference. No reason to make the user copy it unless they want.

You've allowed for move semantics by taking a value rather than const reference in push, but you haven't taken advantage of it the whole way through. Your assignments should be move assignments since you know you're done with the values. That lets you avoid a potentially expensive copy assignment.

Speaking of movement.... You are correct that can't meaningfully implement an emplace with an std::array. Since the elements are default constructed, there's no blank slot to construct in place in to. The best you could do would be a move assignment into an already constructed element which is the same performance as using push with move semantics.

What you could do, however, is use std::aligned_storage and emplace into that. It's basically a tool for getting unitialized memory that's ripe for having something constructed into it. From there, you can implement emplace just like you would in a non-stack allocated situation.

Unfortunately your other logic would get a bit more complicated, but not much. Only construction and destruction (i.e. push and pop) would change, and they would only need placement new and manual-destruction.

There's a pretty good example of what I'm talking about at on cppreference's std::aligned_storage page, though it unfortunately does not have an emplace example.

One last, highly subjective thing: I would probably name it BoundedPriorityQueue instead of LimitedPriorityQueue. Limited sounds like limited functionality to me, whereas bounded sounds like having a maximum size (like bounded buffer).

Also, it might be worth throwing in a bit of documentation. It's pretty obvious from the name and the template params, but someone could wonder what happens when it's full (example thrown, or chucking out the lowest element).


Interface for server requests and responses

You have to keep in mind that the earlier version of the .NET framework suffered in applying the interface segregation principle. In this case, the HTTP context includes methods associated with the request (ex. URL), the response (ex. HTTP status) and server utility functions (ex. map path).

With that in mind, the interface looks OK and familiar in terms of usage in comparison to the original HttpContext (System.Web) and HttpContextBase (System.Web.Mvc) and should be fine.

One aspect in regards to MVC that is hard to manage is the multiple data sources (query parameters, URL parameters, HTTP post Form values, routing parameters, session and the per request key/value store (HttpContext.Current.Items)) - perhaps it would be worthwhile to create an intermediary to manage these.


Mobile webpage for a refugee organization

This question is difficult to answer because art is subjective but if this was my site, I would limit the gutters between the images to be slightly closer together (perhaps 2 maybe 3 ems) and being sure to keep them extending out to the width of the boxed layout.

If I was a user viewing this site, I would be so confused because there is no indication of actions to use.  For example, the website doesn't tell the user anything about what actions to take.  I would add some content to the top, maybe some rollover or pop-overs on my images to encourage user interactions.

Last thing, if this site is a non profit, it is pretty common to re-enforce the mission and/or vision statement on the homepage for the user to understand the commitment of the nonprofit.  Foundations are typically trying to raise money for a cause and without the user knowing or understanding the cause, they will likely not take action. My college professors all said that the user should be able to find information immediately, if they have to look they are going to leave.

Without seeing the actual site, I am going off of my design knowledge so I hope this helps. If you want to share your HTML to show how you are placing your code and what is actually happening on the site, I will try my best to help you clean up the CSS.


How to determine the order of letters by regex?

There is no shorter solution. Because you are enforcing order, you must list every single entity in desired order. And because you are allowing zero to many instances of each entity, you must provide the * operator. And because you want to match the entire string, you must provide the anchors on both ends.

Could you write one that runs faster? Possibly. But shorter? I don't see how.


Correct implementation of encryption function

You can add annotations in function parameters, like password: str and so on.


What do you think about error handling? I think that's good idea to provide some log messages for main operation with db (CRUD).

As example for Delete function:

func DeletePet(pet *Pet) {
    num, err := orm.NewOrm().Delete(pet)

    if err != nil {
        log.Println("DELETE", err)
    } else {
        fmt.Println(num)
    }
}


Converting a JSON object to XML to be passed to an ASMX webservice

Use camelCase to name local variables instead of words separated by underscores. Although there are no guidelines for them it is common practice among C# programmers.

You should always call XmlWriter.Create to get XmlWriter instead of creating XmlTextWriter.

StringWriter, XmlWriter and any other writer implement IDisposable and thus should be used within using section:

using (var stringWriter = new StringWriter())
using (var xmlTextWriter = XmlWriter.Create(stringWriter))
{
    // ... do your stuff that requires stringWriter and xmlTextWriter
}

You should try to avoid .Result for async operation. Try to mark your method with async and use await for client.PostAsync.

Creation of XML looks awful... I suggest to extract your request XML template into XML document with kind of placeholders like:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/"
               xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance"
               xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
    <soap:Body>
        <FUNC_NAME xmlns="http://tempurl.org">
            XML_PARAMETERS
        </FUNC_NAME>
    </soap:Body>
</soap:Envelope>

Then in your code just read this file to string with File.ReadAllText and replace FUNC_NAME and XML_PARAMETERS with string.Replace with real values.


Calculate questions per day on CodeGolf.SE

Your seconds_since_epoch function has a built-in Python equivalent, datetime.timestamp.

Your namespaces would be cleaner if you did from datetime import datetime, timezone.

You use a base_url variable, but do not use urllib.parse.urljoin. Either use a hardcoded URL, or properly join the base URL with the fragment.

results is better named as questions.

In sum([q["answer_count"] for q in results]) the [] is superfluous and inefficient.

Instead of printing 3 times in a row create a multiline format string and print once.

You never create a function that returns the questions, and do not define a main function. I suggest printing in the main function, that calls a function that gets and returns the question information.

This is how I would program it:

import requests
import time
from datetime import datetime, timezone, timedelta

def get_question_info(site, start, stop):
    API_URL = "https://api.stackexchange.com/2.2/questions"
    req_params = {
        "site": site,
        "fromdate": int(start.timestamp()),
        "todate": int(stop.timestamp()),
        "pagesize": 100,
        "page": 1
    }

    questions = []
    while True:
        req = requests.get(API_URL, params=req_params)
        contents = req.json()
        questions.extend(contents["items"])

        if not contents["has_more"]:
            break
        req_params["page"] += 1

        if "backoff" in contents:
            time.sleep(contents["backoff"])

    return questions

def get_area51_estimate(site):
    now = datetime.now(timezone.utc)
    fortnight_ago = now - timedelta(days=14)
    questions = get_question_info(site, fortnight_ago, now)
    avg_questions = len(questions) / 14
    avg_answers = sum(q["answer_count"] for q in questions) / len(questions)
    return avg_questions, avg_answers

if __name__ == "__main__":
    msg = """Over the past 2 weeks, PPCG has had...
{:.1f} questions per day
{:.1f} answers per question"""
    print(msg.format(*get_area51_estimate("codegolf")))