Ungrouping of values into multiple lists

Played a bit with it... how do you like the following?

fun <T> ungroupDuplicateValues(values: List<T>): List<List<T>> {
  val countPerValue = values.groupingBy { it }.eachCount()
  val maxCount = countPerValue.map { it.value }.max() ?: 0
  return (1..maxCount).map { index ->
    countPerValue.filterValues { it >= index }
        .map { it.key }
  }
}

Complexity (in regards to O-notation) should be similar to yours...

Or the following variant using tailrec:

fun <T> ungroupDuplicateValues(values: List<T>) = ungroupDuplicateValues(values.toMutableList())

private tailrec fun <T> ungroupDuplicateValues(remainingValues : MutableList<T>, newValues : MutableList<List<T>> = mutableListOf()) : List<List<T>> {
  val values = remainingValues.distinct()
  newValues.add(values)
  values.forEach { remainingValues.remove(it) }
  return if (remainingValues.isEmpty()) newValues
         else ungroupDuplicateValues(remainingValues, newValues)
}

But don't ask me about the O-notation here. tailrec should be optimized, but as I still use a forEach { remove } it will probably still be O(n²).

If you rather prefer a direct assigned function (of the first shown solution), maybe the following is also ok for you:

fun <T> ungroupDuplicateValues(values: List<T>) =
  values.groupingBy { it }.eachCount().let { countPerValue ->
    (countPerValue.map { it.value }.max() ?: 0).let { maxCount ->
      (1..maxCount).map { index ->
        countPerValue.filterValues { it >= index }
            .map { it.key }
      }
    }
  }


You are correct. There is a better way. Starting in .NET 3.5, there is a JavaScriptSerializer class that can be used for simplifying JSON responses. It can be found in the System.Web.Script.Serialization namespace (System.Web.Extensions assembly)

First, you'd need to make a model to represent your response:

public class SimpleResponse {
    public string responseDateTime { get; set; }

    public SimpleResponse() {
          responseDateTime = "hello hello there!";
    }
}

...Then in your handler:

 public void ProcessRequest(HttpContext context)
 {
     context.Response.ContentType = "application/json";
     var json = new JavaScriptSerializer();

     context.Response.Write(
         json.Serialize(new SimpleResponse())
     );
 }

Here is the result:

{"responseDateTime":"hello hello there!"}

In an ASP.NET MVC application this is more trivial. Just return a JsonResult from your controller:

public JsonResult Index()
{
    return Json(new SimpleResponse());
}


Some things that just pop out when seeing your code:

1) Classes/POCOs definition

They do not seem properly written, probably reproduced from memory. A better version would be:

class Student
{
    int StudentId { get; set; }
    List<Book> Books { get; set; }
    bool IsPassed { get; set; }
}

class Book
{
    int BookId { get; set; }
    List<int> Pages { get; set; }
}

I have used properties, a more generic list type (IList<>) and put a more C#ish capitalization (Pascal case).

2) Proper disposal of disposable objects

SqlConnection implements IDisposable and should also included in a using block (as its close friends SqlCommand and SqlDataReader). Also, in order to shorten things a bit, C# allows usage of var to replace the actual data type:

private static List<Student> GetStudents()
{
    string connStr = ConfigurationManager.AppSettings["Conn"];

    var students = new List<Student>();
    using (var conn = new SqlConnection(connStr))
    {
        conn.Open();
        var command = new SqlCommand("Select * from Students", conn);

        using (var reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                var StudentId = Convert.ToInt32(reader["StudentId"]);
                var BookId = Convert.ToInt32(reader["BookId"]);
                var IsPassed = Convert.ToBoolean(reader["IsPassed"]);
                var PageNUmbers = reader["PageNumber"].ToString()
                    .Split(',')
                    .Select(t => Convert.ToInt32(t))
                    .ToList();

                var books = new List<Book>();
                books.Add(new Book() { BookId = BookId, PageNumber = PageNUmbers });
                students.Add(new Student()
                {
                    StudentId = StudentId,
                    Books = books,
                    IsPassed = IsPassed
                });
            }
        }
    }

    return students;
}

2) * usage in SQL scripts

It is recommended to avoid * usage in SQL scripts and provide the actual columns. If columns are added to the table and your code does not need them, their selection is useless.

3) Unhandled exceptions

Your code does not handle any of the numerous exceptions that might arise from the operations (I will not go into the actual exception types, but illustrate in natural words possible problems)

conn.Open(); --> connection might failed due to incorrect connection string or server not available
var IsPassed = Convert.ToBoolean(reader["IsPassed"]); --> conversion failure if IsPassed is not convertible to boolean
.Select(t => Convert.ToInt32(t)) --> fails if at least one split token is not an integer

[later edit]

It is recommended to catch exception and also log the detailed information somewhere. Ideally, end user should receive a friendly message and context details should be logged in a file, database etc. Context details may include username, IP, hostname, call stack.

For .NET, one of the most used libraries is NLog, which is quite easy to setup and use.

e.g. conn.Open() may have the fail for two main reasons that have different exception types:

try
{
    conn.Open();
}
catch (InvalidOperationException exc)
{
    logger.Log(LogLevel.Error, exc, "Failed to open connection to get students");
    // rethrow because there is nothing else to do without connection. All call stack should remain intact
    // caller must be able to handle InvalidOperationException exception type
    throw;
}
catch (SqlException exc)
{
    logger.Log(LogLevel.Error, exc, "Failed to open connections to get students due to authentication problems");
}

4) Separation of concerns

It is better to separate data connection setup from your data fetch, as setup can also be used for other operations in the future. Also, methods should have meaningful names (e.g. GetStudents -> GetAllStudentData)

// greatly simplified - usually, a connection could be reused to avoid reopening it
class DataAccess
{
    private string connStr = ConfigurationManager.AppSettings["Conn"];

    public SqlConnection GetConnection()
    {
        var conn = new SqlConnection(connStr));
        conn.Open();
        return connection;
    }
}

class StudentService
{
    DataAccess dataAccess { get; private set; }

    public StudentService()
    {
        dataAccess = new DataAccess();
    }

    // this may be put private, if its exposure does not make sense
    public List<Student> GetAllStudentData()
    {
        using (var conn = dataAccess.GetConnection())
        {
            // data fetch comes here
        }
    }

    public IList<Student> GetStudentsGroupedByPassed()
    {
        var students = GetAllStudentData();

        groupedStudents = students.GroupBy(r => new { r.StudentId, r.IsPassed })
            .Select(c =>
                new Student()
                {
                    IsPassed = c.Key.IsPassed,
                    StudentId = c.Key.StudentId,
                    Books = c.SelectMany(t=>t.Books).ToList()
                }).ToList();
        }

        return groupedStudents;
    }
}

5) Try to use mainstream frameworks such as EntityFramework to handle data fetch dirty work. Fetch would look like this:

var students = DataContext.Student.Select(s =>
    new Student()
        {
            StudentId = s.StudentId,
            Books = new List<Book>()
                {
                    new Book()
                        {
                            BookId = s.BookId,
                            PageNumber = s.PageNumber.ToString().Split(',')
                                .Select(t => Convert.ToInt32(t))
                                .ToList(),
                            IsPassed = s.IsPassed
                        }
                }
        }.ToList();


Regex to match phone numbers, with comments

Whatever you do, don't append strings like that!  If you look at the generated bytecode, you'll see that the compiler does exactly what you told it to do:

$ javap -c Main
Compiled from "Main.java"
public class Main {
  public Main();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: ldc           #2                  // String
       2: astore_1
       3: new           #3                  // class java/lang/StringBuilder
       6: dup
       7: invokespecial #4                  // Method java/lang/StringBuilder."<init>":()V
      10: aload_1
      11: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
      14: ldc           #6                  // String \b
      16: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
      19: invokevirtual #7                  // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
      22: astore_1
      23: new           #3                  // class java/lang/StringBuilder
      26: dup
      27: invokespecial #4                  // Method java/lang/StringBuilder."<init>":()V
      30: aload_1
      31: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
      34: ldc           #8                  // String \d{3}
      36: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
      39: invokevirtual #7                  // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
      42: astore_1
      43: new           #3                  // class java/lang/StringBuilder
      46: dup
      47: invokespecial #4                  // Method java/lang/StringBuilder."<init>":()V
      50: aload_1
      51: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
      54: ldc           #9                  // String [-.]?
      56: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
      59: invokevirtual #7                  // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
      62: astore_1
      63: new           #3                  // class java/lang/StringBuilder
      66: dup
      67: invokespecial #4                  // Method java/lang/StringBuilder."<init>":()V
      70: aload_1
      71: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
      74: ldc           #8                  // String \d{3}
      76: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
      79: invokevirtual #7                  // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
      82: astore_1
      83: new           #3                  // class java/lang/StringBuilder
      86: dup
      87: invokespecial #4                  // Method java/lang/StringBuilder."<init>":()V
      90: aload_1
      91: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
      94: ldc           #9                  // String [-.]?
      96: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
      99: invokevirtual #7                  // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
     102: astore_1
     103: new           #3                  // class java/lang/StringBuilder
     106: dup
     107: invokespecial #4                  // Method java/lang/StringBuilder."<init>":()V
     110: aload_1
     111: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
     114: ldc           #10                 // String \d{4}
     116: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
     119: invokevirtual #7                  // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
     122: astore_1
     123: new           #3                  // class java/lang/StringBuilder
     126: dup
     127: invokespecial #4                  // Method java/lang/StringBuilder."<init>":()V
     130: aload_1
     131: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
     134: ldc           #6                  // String \b
     136: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
     139: invokevirtual #7                  // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
     142: astore_1
     143: aload_0
     144: iconst_0
     145: aaload
     146: aload_1
     147: invokevirtual #11                 // Method java/lang/String.matches:(Ljava/lang/String;)Z
     150: ifeq          164
     153: getstatic     #12                 // Field java/lang/System.out:Ljava/io/PrintStream;
     156: ldc           #13                 // String Match!
     158: invokevirtual #14                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
     161: goto          172
     164: getstatic     #12                 // Field java/lang/System.out:Ljava/io/PrintStream;
     167: ldc           #15                 // String No match.
     169: invokevirtual #14                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
     172: return
}

If you change it to concatenate all the string literals in one statement…

public class Main {
    public static void main(String[] args) {
        String regexStr =
            "\\b" +      //Begin match at the word boundary(whitespace boundary)
            "\\d{3}" +   //Match three digits
            "[-.]?" +    //Optional - Match dash or dot
            "\\d{3}" +   //Match three digits
            "[-.]?" +    //Optional - Match dash or dot
            "\\d{4}" +   //Match four digits
            "\\b";       //End match at the word boundary(whitespace boundary)

        if (args[0].matches(regexStr)) {
            System.out.println("Match!");
        } else {
            System.out.println("No match.");
        }
    }
}

Then the bytecode is much saner (one literal string at offset 0):

$ javap -c Main
Compiled from "Main.java"
public class Main {
  public Main();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: ldc           #2                  // String \b\d{3}[-.]?\d{3}[-.]?\d{4}\b
       2: astore_1
       3: aload_0
       4: iconst_0
       5: aaload
       6: aload_1
       7: invokevirtual #3                  // Method java/lang/String.matches:(Ljava/lang/String;)Z
      10: ifeq          24
      13: getstatic     #4                  // Field java/lang/System.out:Ljava/io/PrintStream;
      16: ldc           #5                  // String Match!
      18: invokevirtual #6                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      21: goto          32
      24: getstatic     #4                  // Field java/lang/System.out:Ljava/io/PrintStream;
      27: ldc           #7                  // String No match.
      29: invokevirtual #6                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      32: return
}


C program to generate Seed programs from statically defined Befunge code

[Is] there was a better way to do this that would lead to the same or better optimisation.

Yes: don't hardcode stuff the compiler can't do any optimizations about and that makes your program a pain to use. (And an eye-sore because of all those ALL_CAPS_MACROS everywhere.)

Hardcoding the Befunge program gives the compiler next to no useful information. All you're doing with it is comparing it with random data that the compiler can't reason about. (And you're doing that after modifying the string at runtime anyway - the compiler might see through this, but you're adding a tough layer there.)

The hardcoded length could potentially be used to control the amount of loop unrolling in the main loop that the compiler will attempt/choose, but I won't believe that has a significant impact until I see an actual benchmark.

Using char for the loop variables rather than the plain old int won't buy you anything, except the obfuscation you got through that macro - not desirable. Smaller doesn't always mean faster - you might actually incur a performance loss here compared to using a plain int.

What might give the compiler an advantage is having the RNG functions bodies visible when it compiles your main loop - that's the only "computationally expensive" step in your code. But you've put them in a different translation unit, so you've prevented inlining unless you use some form of whole-program optimization/link-time optimization.

So, if I were you, I would first keep this program as it is, and measure its performance on known input(s).

Then start a new one without any of those macros:

read the parameters from command line arguments
move the actual processing code to a function that takes those arguments and returns a seed if found

At this step, again, measure the performance. If there's a measurable difference either way, try to figure out why. Once you have the why, you can look further at what needs to be done to take advantage (or reject) that difference.

Then you can try again after move the relevant RNG functions into the main file.

Then you can check out your compiler's profile-guided optimization mode if it has it, and see if that changes things.

Measure, rinse, repeat.


I'm not quite skilled enough at Factor yet to review your code in full, but I would just like to note as a response to

  I don't know the math well enough to test the edge cases, but I did check with this code

Factor has really slick builtin unit-testing. Here are the docs; I'll pull an example from my factor/work directory:

USING: tools.test mk-initialism ;
IN: mk-initialism.tests

{ "LASER" } [ "Light Ablah by S of Ed Radiof" >initialism ] unit-test
{ "USA"   } [ "United S OF Americaof" >initialism ]         unit-test
{ "USA"   } [ "united states and america" >initialism ]     unit-test
{ "JTW"   } [ "Jordan Of the World" >initialism ]           unit-test

To create the test file, open the listener and do:

USE: tools.scaffold
"q.physics.gravitational-attraction" scaffold-tests

To run the tests, just run "q.physics.gravitational-attraction" test.


I'm no expert on SHA1, and I see mostly small things, but one big thing that gave me pause. As an overall observation, you seem to value readability over memory usage. Since hashes are often used for large files, this seems to be a risky tradeoff, and python does provide good ways to handle this as well. More of this in the third observation below. On to the observations:

pBits being represented as a series of characters for each bit seems unusual for such low level work. I would typically expect to see this as a hexadecimal string, or even a number. Yet except for possible difficulties comparing it to other implementations that favor less space usage, this seems to make things easy to read.
Filling out pBits to lengths congruent to 448 mod 512 could be done in a single step by figuring out how many bits of padding are necessary and doing a single pBits += "0" * padding; there's no need for a while loop.
This one's important: chunks() should probably be a generator so that you don't have three copies of your data around (one original, one expanded a bit to a byte, and one in chunked strings); correspondingly this could serve out the trailing zero and length bits. Let's examine what this would look like, as 3 copies of large data is really large. Let's remove the sliced copies, creating only one chunk at a time:

def iterchunks(bits, chunkbits=512):
    for i in range(0, len(bits), chunkbits):
        yield bits[i:i + chunkbits]

Note that if the pBits generation was here, checking i + chunkbits against len(bits) and the bytes to bits conversion, you could process a file-like stream instead of a string, taking you further down, from the original 3 copies (with two of them 8 times larger than usual) to not even a full copy of your data in memory at one time.
Back to small ideas. Your bit string could be more literally a bit string, storing \0 and \1 characters. This would let you simplify setting up w into w = map(ord, words). (Of course with the appropriate helper, you could do that with the 0 and 1 characters of your current string.)
I'm not a big fan of the for i in range(0, 80): if 0 <= i <= 19: ... section. It feels like it might read better with a series of for loops that do their different thing then call a helper:

for i in range(0, 19):
    f = (b & c) | ((~b) & d)
    k = 0x5A827999
    a, b, c, d, e = update(a, b, c, d, e, f, k, w[i])
for i in range(20, 39):
    f = b ^ c ^ d
    k = 0x6ED9EBA1
    a, b, c, d, e = update(a, b, c, d, e, f, k, w[i])
...

but that seems pretty ridiculous, and would probably hurt performance to boot. After looking more closely at the obvious alternative, I'm going to withdraw this complaint.


I can't see any issues in terms of making your code idiomatic; it looks very Rust-like! I did however notice a problem with your code's logic.
Integer overflow
I tried inputting 31/12/2019 and obtained a panic when I ran it today (07/11/2020). This was because Utc::now().month() is a u32 equal to 11, and the code attempts to subtract 12:
let months = Utc::now().month() - date.month();

This leads to an overflow because we're using unsigned integers. The same story applies for the day, which is also a u32, but not the year, which is an i32 and so functions fine.
Even if we convert the relevant types to signed integers, the following isn't what you mean:
let years = Utc::now().year() - date.year();

This would tell you that 31/12/2019 and 1/1/2020 are a year apart, when in fact this isn't true. Even dividing the number of days by 365 isn't quite right because of leap years.
Making the date logic work correctly is a lot more frustrating than it sounds: the number of months passed depends on the length of each month as well as the Duration instance. That's why Duration doesn't implement anything beyond num_weeks(): it's simply a difference between two dates, so it doesn't know how to account for the varying month lengths.


Message class, with constructors for data from user and from database

First, let's address your primary concern: the two constructors.

If the code to generate the UUID is not overly complicated, we can extract it and use it in our constructor as a default value (I don't like this because it adds code redundancy but I guess this is the only way to consolidate both constructors).
The same applies to the timestamp.
Thus we can use a primary constructor with the more specific super-constructor.

open class Message(
    id: String = UUID.randomUUID().toString(),
    val contents: String,
    val timestamp: Long = System.currentTimeMillis()
) : Unique(id) {

Here we combined both constructors and kept the order of the parameters.
Now we can use the init-block as well to validate the contents of the message:

init {
    validateMessageContents(contents)
}

That's the majority of things one can do to slim the class down.

Keep in mind that you need to specify a named parameter contents now because the first positional parameter id has a default value.

Message(contents = "test")

Another thing to do is to annotate your functions according to their behavior, so annotate validateMessageContents with @Throws.
I've also taken this opportunity to convert the two if-statements to a when-block. It's functionally the same (a string can't be empty and 1024 characters long at the same time).

@Throws(IllegalArgumentException::class)
    private fun validateMessageContents(contents: String) {
        when {
            contents.isEmpty() -> {
                throw IllegalArgumentException("Contents cannot be blank/empty")
            }
            contents.length > MAX_MESSAGE_LENGTH -> {
                throw IllegalArgumentException("Message too long - please limit to $MAX_MESSAGE_LENGTH characters.")
            }
        }
    }


Here is my list of improvements:

Encapsulate all the logic in a custom textwatcher. This gives you the benefit to make the EnableViewTextWatcher reusable in other parts of your project (if you extract it from the Activity).
Programming against TextView vs EditText and View vs Button will make the code more flexible.
Limit visibility by using private keyword (class members, parameters and local variables)
Make class members, params and local variables final is possible
Follow the general Android coding guidelines regarding naming.
Use meaningful names when naming class, class members, params, and local variables
Use annotations in your code to improve code quality
Use constants instead of Magic Numbers.

public class RoomSelectActivity extends Activity {

    @Override
    protected void onCreate(@Nullable final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_room);

        final TextView roomNumberText = (TextView) findViewById(R.id.tv_room_number);
        final View enabledView = findViewById(R.id.btn_go_to_room);

        final TextWatcher watcher = new EnableViewTextWatcher(roomNumberText, enabledView);
        roomNumberText.addTextChangedListener(watcher);
    }

    private static class EnableViewTextWatcher implements TextWatcher {

        private static final int LENGTH_TO_ENABLE_VIEW = 8;
        private static final int ENABLED_TEXT_COLOR  = 0xFFFFFFFF;
        private static final int DISABLED_TEXT_COLOR = 0xBBFFFFFF;

        private final TextView mWatchedTextView;
        private final View     mEnableView;

        public EnableViewTextWatcher(@NonNull final TextView textViewToWatch, @NonNull final View viewToEnable) {
            mWatchedTextView = textViewToWatch;
            mEnableView = viewToEnable;
            updateEnabledViewState();
        }

        public void afterTextChanged(@NonNull final Editable s) {
            updateEnabledViewState();
        }

        public void beforeTextChanged(@NonNull final CharSequence s, final int start, final int count, final int after) {
        }

        public void onTextChanged(@NonNull final CharSequence s, final int start, final int before, final int count) {
        }

        private boolean checkTextView(@NonNull final TextView textView) {
            return ((textView.getText().toString()).length() == LENGTH_TO_ENABLE_VIEW);
        }

        private void updateEnabledViewState() {
            final boolean enabled = checkTextView(mWatchedTextView);
            mEnableView.setBackgroundColor(enabled ? ENABLED_TEXT_COLOR : DISABLED_TEXT_COLOR);
            mEnableView.setEnabled(enabled);
        }
    }
}


By PEP 8, Python's official style guide, function names should generally be lower_case_with_underscores.  Also, the final semicolon should be omitted.

The function would typically be written more elegantly using the sum() builtin function, with a generator expression.  (It's not any faster than your original code, though.  Actually, a tiny bit slower.)

I don't recommend using arr as a variable name, since it's neither descriptive (what does the array represent?) nor accurate (it's actually a string).

For the printout, I recommend using str.format() or one of the other formatting mechanisms.

import sys

def is_armstrong(number):
    digits = str(number)
    length = len(digits)
    return number == sum(int(digit) ** length for digit in digits)

if len(sys.argv) > 1:
    arg = int(sys.argv[1])
    print('{} is an Armstrong number? {}'.format(arg, is_armstrong(arg)))
else:
    print("No arguments passed! :-(")


I agree with the other feedback given here so far; I have two three suggestions of my own, two minor and one more significant.

Minor point (1)

Initial assignation to a variable can be done in one line, so instead of:

DECLARE @TimeWindowInSeconds INT

SET @TimeWindowInSeconds = 10

you could just write:

DECLARE @TimeWindowInSeconds INT = 10

Minor point (2)

I am not a fan of selecting columns in intermediate rowsets that are never used subsequently. They add clutter and unnecessarily make the reader spend time understanding or visualising them.

CTE1 selects just three columns, all of which are necessary for the join in CTE2: this is good.

However, CTE2 then selects seven columns, of which only A.Class, A.DT and the expression aliased as z are required by CTE3 or presented in the final output.

I suspect that you put these columns in whilst writing CTE2, because the others are all used in the join within that CTE. This is fine for work-in-progress, but these columns should be removed from the finished query. They don't need to be in the SELECT list just because they're used in the JOIN.

The bigger one

Your code uses both common table expressions (CTEs) and subqueries. For me, this is quite a painful inconsistency. CTEs were effectively an evolution of subqueries in the ANSI SQL standard; mixing both in one query feels to me like designing an aeroplane that has both propellers and a jet engine.

Aside: please don't read too far into that analogy: this answer is not about their relative performance, nor am I claiming that one is made redundant by the other. People still use prop planes, after all.

Unless performance is particularly important, and you know for certain that subqueries perform measurably better on your server, with your data, I recommend sticking with CTEs alone:

The syntax is easier to follow
They mimic step-by-step problem solving, walking your reader through the solution steadily
Well-chosen CTE names are tantamount to good comments, explaining your rationale
They can make code shorter because you can re-use them

In your particular case, I think the SubGroup subquery will need to become a separate CTE between CTE2 and CTE3 (you'd then join to that CTE in the current CTE3, using c.DT <= CTE2.DT AND c.Class = cte2.Class as the joining conditions).

Having done that, if I've understood your intentions correctly, the correlated subquery right at the end (WHERE...IN ( subquery )) could be removed entirely, and replaced with a partitioned COUNT() function in the current CTE3 (because Subgroup will be available as a regular column in CTE3 now).

In other words, in order to work out which combinations of Class and Subgroup occur more than once, you'd add a column to your refactored CTE3 something like:

COUNT(*) OVER ( PARTITION BY Class, Subgroup ) as CountBy_Cls_Sgp

and then your final query outside the CTEs would simply restrict where  CountBy_Cls_Sgp > 1.

This also removes altogether the need to CAST and concatenate Class and Subgroup, since you're not including that concatenation in your result set.

Even if you didn't want to change the WHERE...IN ( subquery ) part, you could simplify things by adding an extra, final CTE in which you do the casting and concatenation of Class and Subgroup just once, give it an alias, and then do

WHERE alias IN ( SELECT alias FROM cte3 GROUP BY ... )


The main issues, with your code, are that:

you do not factorize part of your code that are similar by correctly parametrizing your functions; and
you do not manage any common state between entities that are related.

But first, let's talk a bit about multi and __name__.

First, you can remove the need for a lambda by having multi return a callable that you will be able to provide to the command parameter. Writting something allong the lines of ..., command=multi(step_forward, step_forward_2)):

def combine(*callables):
    def runner():
        for function in callables:
            function()
    return runner

I also changed names, I feel these are more explicit.

Second, you should wrap your top-level code under an if __name__ == '__main__': clause. That way, if I want to use the building blocks you provide, I can import your file and build around it without having your UI pop up.

Now onto simplifying your code.

There is at least 3 things you are trying to achieve all at once:

Build logical blocks such as a button and a label in a frame;
Interact with such blocks from "the outside"; I believe the show/hide should be more generic than the "next step" one, but not knowing what you want to achieve with such UI, I can be misleading;
Manage states and control flow to have all your parts work together.

The first part is pretty straightforward: if you want several elements that behave like a single entity, you build a class to hold these elements together. Having done that, the second one comes naturally: you provide methods on your class so that "the outside" can interact with it. Managing states are thus nearly done: combine fed by instance method is very helpful. You only need to set it as a command on UI elements once each of them has been built.

In the following improvements, you’ll see that I provide several level of customization to be able to interact with the group of item both from the inside and the outside. Depending on your needs, you can merge some or detail even more:

import tkinter as tk
import random

class ButtonWithStatus:
    def __init__(self, root, pack_side, frame_config=None, button_config=None, label_config=None):
        if frame_config is None:
            frame_config = {}
        self._status_config = {} if label_config is None else label_config
        self._button_config = {} if button_config is None else button_config
        self._button_config['command'] = self.on_click
        self.hidden = True

        frame = tk.Frame(root, **frame_config)
        frame.pack(side=pack_side)
        self._hidden_background_color = frame.cget('bg')
        # Build hidden button
        parameters = self.hidden_parameters(self._button_config)
        self.button = tk.Button(frame, **parameters)
        self.button.grid(row=0, column=0)
        # Build label with hidden text
        parameters = self.hidden_parameters(self._status_config, False)
        self.label = tk.Label(frame, **parameters)
        self.label.grid(row=1, column=0)

    def hidden_parameters(self, configuration, is_button=True):
        parameters = configuration.copy()
        parameters.update(text='', bg=self._hidden_background_color)
        if is_button:
            parameters['command'] = None
        return parameters

    def on_click(self):
        raise NotImplementedError

    def show_hide(self):
        if self.hidden:
            self.button.configure(**self._button_config)
            self.label.configure(**self._status_config)
        else:
            parameters = self.hidden_parameters(self._button_config)
            self.button.configure(**parameters)
            parameters = self.hidden_parameters(self._status_config, False)
            self.label.configure(**parameters)
        self.hidden = not self.hidden

class ActivableButton(ButtonWithStatus):
    STATUS = 'Status: {}'

    def __init__(self, root, button_text, inactive_status, active_status):
        super().__init__(root, 'left', {'padx': 10},
                         {'text': button_text, 'font': 'courier 20', 'bd': 0},
                         {'text': self.STATUS.format(inactive_status), 'font': 'courier 14'})
        self.activated = False
        self._active = active_status
        self._inactive = inactive_status

    def on_click(self):
        self.activated = not self.activated
        if self.activated:
            self._status_config.update(text=self.STATUS.format(self._active), fg='blue')
        else:
            self._status_config.update(text=self.STATUS.format(self._inactive), fg='black')
        self.label.configure(**self._status_config)

class ValidableActivableButton(ActivableButton):
    def __init__(self, root, button_text):
        super().__init__(root, button_text, 'Can be done', 'To be done')
        self._done = False

    def step_forward(self):
        if self._done:
            return

        if self.activated:
            self._button_config.update(text='', bd=0, bg='#F0F0F0', state='disabled')
            if random.randint(0, 1):
                self._status_config.update(text='Accomplished', fg='green')
            else:
                self._status_config.update(text='Failed', fg='red')
            self._done = True
        self.button.configure(**self._button_config)
        self.label.configure(**self._status_config)

def combine(*callables):
    def runner():
        for function in callables:
            function()
    return runner

if __name__ == '__main__':
    root = tk.Tk()
    main = tk.Button(root, text="Show/Hide", bg="white", font="courier 30")
    main.pack()

    frame = tk.Frame(root, pady=10)
    frame.pack()

    button1 = ValidableActivableButton(frame, 'Perform action #1')
    button2 = ValidableActivableButton(frame, 'Perform action #2')

    main['command'] = combine(button1.show_hide, button2.show_hide)

    next_day = tk.Button(root, text="Next day", bg="white", font="courier 30",
                         command=combine(button1.step_forward, button2.step_forward))
    next_day.pack()

    root.mainloop()

Several other improvements:

usage of booleans instead of text to determine toggable state;
usage of the "default" background color of the container to determine the background color of the hidden state;
usage of dictionaries to store/restore widget configuration.

Depending on your needs, you may want to add/remove some of the parameter of the constructors. Or even combine ValidableActivableButton and ActivableButton into a single class.

You also don't really need to manage the hidden state yourself by removing text (and optionnally changing background color) as your can hide widgets pretty easily. This allows you to manipulate your widgets directly or using configure without worying about storing their state for future hide/show:

import tkinter as tk
import random

class ButtonWithStatus:
    def __init__(self, root, pack_side, frame_config=None, button_config=None, label_config=None):
        if frame_config is None:
            frame_config = {}
        if button_config is None:
            button_config = {}
        if label_config is None:
            label_config = {}
        button_config['command'] = self.on_click

        frame = tk.Frame(root, **frame_config)
        frame.pack(side=pack_side)
        self.button = tk.Button(frame, **button_config)
        self.button.grid(row=0, column=0)
        self.label = tk.Label(frame, **label_config)
        self.label.grid(row=1, column=0)

        # Hide label and button
        self.button.grid_remove()
        self.label.grid_remove()
        self.hidden = True

    def on_click(self):
        raise NotImplementedError

    def show_hide(self):
        if self.hidden:
            self.button.grid()
            self.label.grid()
        else:
            self.button.grid_remove()
            self.label.grid_remove()
        self.hidden = not self.hidden

class ActivableButton(ButtonWithStatus):
    STATUS = 'Status: {}'

    def __init__(self, root, button_text, inactive_status, active_status):
        super().__init__(root, 'left', {'padx': 10},
                         {'text': button_text, 'font': 'courier 20', 'bd': 0},
                         {'text': self.STATUS.format(inactive_status), 'font': 'courier 14'})
        self.activated = False
        self._done = False
        self._active = active_status
        self._inactive = inactive_status

    def on_click(self):
        self.activated = not self.activated
        if self.activated:
            self.label['text'] = self.STATUS.format(self._active)
            self.label['fg'] = 'blue'
        else:
            self.label['text'] = self.STATUS.format(self._inactive)
            self.label['fg'] = 'black'

    def step_forward(self):
        if self._done:
            return

        if self.activated:
            self.button['text'] = ''
            self.button['bd'] = 0
            self.button['bg'] = '#F0F0F0'
            self.button['state'] = 'disabled'
            if random.randint(0, 1):
                self.label['text'] = 'Accomplished'
                self.label['fg'] = 'green'
            else:
                self.label['text'] = 'Failed'
                self.label['fg'] = 'red'
            self._done = True

def combine(*callables):
    def runner():
        for function in callables:
            function()
    return runner

if __name__ == '__main__':
    root = tk.Tk()
    main = tk.Button(root, text="Show/Hide", bg="white", font="courier 30")
    main.pack()

    frame = tk.Frame(root, pady=10)
    frame.pack()

    button1 = ActivableButton(frame, 'Perform action #1', 'Can be done', 'To be done')
    button2 = ActivableButton(frame, 'Perform action #2', 'Can be done', 'To be done')

    main['command'] = combine(button1.show_hide, button2.show_hide)

    next_day = tk.Button(root, text="Next day", bg="white", font="courier 30",
                         command=combine(button1.step_forward, button2.step_forward))
    next_day.pack()

    root.mainloop()


Please see comment above about thinking about broader review. My guess is that you might have a flawed approach to how you are modelling real-world items in your application. For example, a particle/matter/explosive doesn't really "doDamage" right? It "attacks" or "fires" or whatever you might want to call it.

"Damage" as a concept results from what the properties of the attack and the properties of the thing attacked are right?   So why would you model "damage" as a method on the different attacker entities, when it truly is something that needs to be determined based on the properties of both the attack and the target. Putting the actual calculation in the attacker class would not seem to make sense when you think about it.

You might look through another review I gave where the poster was having a similar problem in modelling application entities to match real world behavior. I hope this may give some insight into how you should be thinking about writing your code.

That being said, if you aren't looking to potentially refactor your application, your problem should actually be easy to solve.  Just break that "variable" area of code out into it's own function:

So base class might look like:

function doDamage($fire) {
    // all your code common to every class in hierarchy

    // call method (overridden with specific logic in each inheriting class
    // possibly this method returns your Damage object
    $dmg = $this->calculateDamage($someParam, $someOtherParam, ...);

    // other code common to all classes in hierarchy
}

And you only override such code in inheriting classes if logic totally varies from that execution path.

Why does this method always return true? Is it really even meaningful to have a return from a method is the value is always the same?


Ways to differentiate comments in source code (PyCharm)

I think the major problem with this current system is this: Imagine you come back 6 month after having written these comments and have not used this commenting system elsewhere since then. What category does a comment like (4) ... belong to? Without looking it up! Now imagine someone else looks at your code and needs to figure out which comments are meant for them.

In other words, the system is not self explanatory.

(Ab)using multi-line strings as comments is also discouraged. You are not even using them as multi-line string anyway.

It would already help if you used words instead of numbers. Maybe this is already enough to cover all your cases:

# TODO NAME note to name or # FIXME important bugfix
# TODO TEAM note to team members,
# just plain comments for business rules
# CONSTANT description
# NOTE idea for improvement
# just plain comments on the flow of the code

At least in my editor, TODO, FIXME and NOTE all get the same special highlight.

Your code itself you should re-organize a bit. Ideally you define all your classes and functions first and put code calling it afterwards. Don't intersperse the two.

The definition of df can also be simplified a bit using extended indexing of pandas dataframes and pandas.DataFrame.rename:

df = SXRX_df[['Last Name', 'First Name', 'Student Id', 'School DBN', 'Cls', 'Section',
 'Score.1']]
df = df.rename(columns={'Cls': 'Ofc Cls', 'Score.1': 'Final Score'})
df['Exam'] = 'SXRX'
df['Reason Incomplete'] = reason_incomplete(SXRX_df['Follow Up'],
                                            SXRX_df['Follow Up.1'],
                                            SXRX_df['Errors'])

Note that the columns are in the order in which they appeared in the list, so you might not even need the reindex.

The np.vectorize can also already be used as a decorator at the time of function definition and save some real estate in the block above:

@np.vectorize
def reason_incomplete(school_follow_up, site_follow_up, errors):
    ...


Suggestions

You check all words in all documents. Try iterate only over docs (without unnecessary checks)
instead of create empty inv_indx = {i:[] for i in corpus_dict} you can use defaultdict

Code

from collections import defaultdict

inv_indx = defaultdict(list)
for idx, text in enumerate(docs):
    for word in text:
        inv_indx[word].append(idx)


LSD radix sort (force avoid div or idiv compiler instruction) in C++

Avoid macros
There is no need to make modpow2 a macro. Make it a  function instead:
static constexpr size_t modpow2(size_t num, size_t div_pow2, size_t mod_pow2) {
    return (num >> div_pow2) - (num >> (mod_pow2 + div_pow2) << mod_pow2);
}

Avoid forward declarations
You should not need to write forward declarations, unless you have circular dependencies between functions. Otherwise, they are unnecessary code duplication, and there is a potential for mistakes that is better avoided.
Be consistent with the template type
You made your functions templates, so I assume you want to be able to run radix sort on arrays of various types. However, I see code like this:
unsigned int aux = arr[0];

What if I have an array of unsigned long instead? Or float? When you make a template, you want to avoid making assumptions about the type of the variables. So either use the template type name:
obj_arr aux = arr[0];

Or better yet, just use auto when possible:
auto aux = arr[0];

Also use this for the return type. So:
template<class obj_arr>
auto getmax(obj_arr*& arr, size_t& size) {
    auto aux = arr[0];
    ...
    return aux;
}

When to pass by reference
You should only pass large objects by reference. Small objects, like pointers and primitive types like int and size_t should be passed by value if possible. So:
template<class obj_arr>
auto getmax(obj_arr* arr, size_t size) {
    ...
}

If you always use references, you risk adding unnecessary pointer indirection to your code.
Use const where appropriate
You should mark pointers and references as const when possible, since that might allow the compiler to generate better code, and it will also give a compiler error if you accidentily do modify a value that should be constant. So:
template<class obj_arr>
auto getmax(const obj_arr* arr, size_t size) {
    ...
}

You can even be more strict and also make the parameter size_t size const, and even local variables like max_mod inside countrad().
Use size_t consistenly for counts and indices
Don't use unsigned int for counts, unless you are absolutely sure you will never have to deal with arrays with more elements than can be counted in whatever an unsigned int might be on all the platforms you want to support.
Use idiomatic for-loops
Why have you moved the initializer statement out of all your for-loops? In most cases this does not seem necessary at all. Just write for-loops like you normally do:
auto aux = arr[0];

for (i = modpow2(size, 0, 1); i < size; i += 2) {
    aux = arr[i] * (aux < arr[i]) + aux * (aux >= arr[i]);
    aux = arr[i + 1] * (aux < arr[i + 1]) + aux * (aux >= arr[i + 1]);
}

Avoid premature optimization
Your implementation of getmax() seems to be written to avoid conditional jumps. However, many architectures have conditional move instructions that will be able to perform a maximum operation without needing conditional jumps. And this is much cheaper than two multiplication operations. Instead of calling getmax(), I would just use std::max_element() like so:
auto max = *std::max_element(arr, arr + size) + 1;

Let the compiler worry about optimizing this. If you really want to be sure, measure the speed of your radix sorting function when using your getmax() vs. when using std::max_element().
Also, in general the compiler will be able to optimize multiplication and division by constants for you, and will convert them to shifts if it sees they are powers of two. However, there are a few places where you call modpow2() with variable divisors, so it does make sense to explicitly use shifts here.
Use std::unique_ptr to manage allocated memory
It's best to avoid calling new and delete manually, and use smart pointers that do this for you. This avoids potential mistakes such as leaking memory or deleting something twice. If you can use C++14, then use std::make_unique() to create an array for you, like so:
auto aux_arr = std::make_unique<obj_arr[]>(size);
auto count = std::make_unique<size_t[])(1 << mod_pow2 + 1);

If you are stuck with an older version, you still need to use new:
std::unqiue_ptr<obj_arr> aux_arr = new obj_arr[size];
std::unique_ptr<size_t> count = new size_t[1 << mod_pow2 + 1];

But at least you don't have to call delete anymore. You could also use std::vector for even cleaner looking code, but then you lose a bit of performance due to the initialization of the elements.
Naming things
The names of your variables and functions are inconsistent and sometimes misleading. For example, choose whether you want to use underscores to separate words (which I recommend) or not, and stick with that choice.
The name obj_arr suggests that the type is an array, but actually it's the type of the array elements. In any case, I would use the more idiomatic T for this:
template<typename T>
auto getmax(const T* arr, size_t size) {
    ...
}

The word count suggests it is a single value, but actually it is an array. I recommend you use the plural form of a noun for arrays, or append _arr like you do with aux_arr for example.


Validating username fields and showing CAPTCHA

Why not use the built-in PHP e-mail validation?

filter_var($email, FILTER_VALIDATE_EMAIL)

Why do

if (lol())
  return true;
else
  return false;

when you can do

return lol();

Same goes for lol() ? true : false which you do too.

Furthermore the signup_error stuff is ugly. I'd suggest exceptions. At least make signup_error into an array instead, and just add new elements when you get an error. You can join() the array when outputting.

Also, you risk $count not being defined if $stmt fails.


Interesting idea, much better than having status codes / messages / magic strings wandering everywhere. This is also a good starting point for making messages loclaziable - if they are centralized, the can also be taken from resources in centralized manner.

Regarding possible improvements:

I would consider changing AddErrors(List<StatusCodes> codes) to AddErrors(params StatusCodes[] codes) - it will be easier to add just one error (what I suppose is most probable scenrio) or many with sam emethod without need to construct the List object.
It might be interesting to add some events to the Manager class - this way some important Listeneres might be configured, i.e. when status Unauthorized appears some listener just cancels all current responses and redirects user to error / login page. Or DatabaseNotResponding might have listener attached that counts occurences per minute and when there is more than one or two (what can happen in heavilly trafficked network) reports this immediatelly to the Admin. These two examples might not be a best design anyway - but I just point the purpose.
Probably you are thought about this already, but I would definitelly divide StatusCodes into specialized classes for ease of use like SystemStatusCodes, UserStatusCodes, OrderStatusCodes etc...
I think there is some error in your code in class MessageStatusHandler: protected List<MessageStatusHandler> _errorList;. I don't see a point in creating collection of handlers inside on of the exact handler type, perhaps you thought about gathering more results in one object - but I think this part needs more designing that just that simple exmaple.


I apologize that this answer became a "stream of consciousness"-type answer. I found it difficult to properly categorize what I wanted to say.

There's a fair amount to be said in add_players. The way you have things set up is quite confusing. You have fairly deep nesting, and multiple returns at multiple different levels of nesting.

if pla not in (a for i in players for a in i) is also confusing. Think about for i in players. You're referring to each player as i? Also, your intent with that generator expression seems to be to flatten players so you can check if a name already exists. Flattening doesn't seem necessary though since each "player" is a name and score. Why check if a name is equal to a score?

You also have a while len(players) < 4 inside of a while True. I can't really see the point of the while True though.

I would also use much more descriptive names. Once you reduce the nesting, you'll have a lot more room to work with.

Finally, add_players really shouldn't be adding to a global players. players should be returned from add_players and assigned at the call site.

Altogether, I'd write this closer too:

def add_players():
    players = []

    while len(players) < 4:
        new_name = input("Enter Player Names (can have up to 4) >>> ")

        if new_name:
            if new_name not in (name for name, _ in players):
                players.append([new_name, 0])
                print("Player {} added".format(new_name))

            else:
                print("Name already in players' list")

        else:
            break

    return players

Notice now there's a single return, and it's returning the players for the caller to use.

Please don't take this the wrong way, but the design of the rest of the program doesn't make much sense:

Why is everything inside of main? Ideally, the main function should be a small function at the end of your program that just calls a few other functions.
Why is a Score class inside of the home function?
Score also doesn't seem like it should even be a class. All of the methods of the class are static, and it seems like you're only using Score to score a word by calling the Score constructor. If you never use an instance of a class, it shouldn't be a class. Just make Score into a score_word function. I'd also pass a word into the function instead of asking inside of the function. Functions are harder to test when they produce their own data.
You're catching a NameError in undo. I'm guessing this is in case Score() hadn't been called yet? Don't do this. I can't think of a time when it's ever appropriate to catch a NameError. Any time a NameError happens, it means you have flawed logic in your program. You should fix the issue instead of putting an try/except band-aid over it. If the function requires temp_p and temp_v (which need better names), you need to ensure that that data is available. Either pass it in, or ensure that they're properly initialized ahead of time.

There's more that can be dug out here, but I need to start getting ready for work. I'll just make a few broad suggestions:

Please take much more care when writing code. A lot of this code seems like it was written quickly without much second-thought. I would focus on the intent of the code before it's written.

Ask yourself, "What exactly should this code do?", and "What are the appropriate tools to do what I'm trying to do?". Doing things like using classes as normal functions and writing code like (a for i in players for a in i) that technically works (but doesn't really do exactly what you want) makes your code hard to understand, and will make it difficult to add to later.
Don't nest everything. Really, all of these functions should be "top-level", outside of everything else. If you nest thing A inside of thing B, that suggests that A is deeply connected to B and wouldn't have a valid meaning outside of B. Really though, that's not the case here. Score would have the same meaning even if it were outside of home, and all the functions would have the same meaning even if they were outside of main.

Nesting conveys a certain association meaning, and if used improperly, gives the reader the wrong initial idea about how the code works. Nesting also forces you to use more indentation, which generally makes code harder to read.

With the above criticisms out of the way, I'll note what is good here:

You're following proper naming guidelines. You have functions starting with lowercase, classes starting with uppercase, and _ to separate "words" in names.
You're using idiomatic shortcuts like if pla: to check if a collection is empty or not.
You tried to have all the functionality start from a main instead of being loose in the script. This makes code easier to run and test.
letter_val is a good use of a dictionary.

I'll note though that it's a constant, so it should be in all uppercase.

Keep at it. There's a lot to be improved here, but there's promise too.


Rather than opening a resource and then remembering to close it with a .Dispose() call,
I think it's good to use the using (...) { ... } idiom as much as possible.
Some questions (and again) on Stack Overflow suggest some issues with releasing image resources when opened with Image.FromFile.

I propose this alternative:

public static void Main()
{
    string[] files = Directory.GetFiles("C:\\Users", "*.png", SearchOption.AllDirectories);

    foreach (string file in files)
    {
        using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
        using (Image img = Image.FromStream(fs))
        {
            if (img.Width > 1100)
            {
                Console.WriteLine(file);
                Console.WriteLine(img.Width);
            }
        }
    }
}


Longest Common Substring solution for a string and a list

No docstrings! What do your functions do and how do I call them?
Your lcss function has a name that suggests it might return the longest common subsequence. But in fact it returns all common subsequences of length 3 or more (except for ones that appear inside other common subsequences in s1). Is this really what you want the function to return? If so, you probably want to rethink the name.
Python's in operator already implements your _contains operation for strings:

>>> [w.strip() for w in open('/usr/share/dict/words') if 'abc' in w]
['crabcatcher', 'dabchick']

It's also much faster.
I guess you didn't use in because you want your subsequence operation to work on all kinds of sequence (not just strings). But in that case you should prefer to use one of the Boyer–Moore search algorithms, for example Boyer–Moore–Horspool, so that the complexity is more like \$O(n)\$ (on average on random inputs) than \$O(mn)\$.

See this answer for a Boyer–Moore–Horspool implementation in Python.
Your algorithm has complexity \$O(m^3n)\$ (where \$m\$ and \$n\$ are the lengths of the two sequences). But the longest common subsequence problem for two sequences has a well known \$O(mn)\$ algorithm, described in detail in the Wikipedia article.


Memory over-runs

readheap is non-size-aware, so it's wide open to an overrun error (or even a deliberate overrun attack). Pass in a size, or use a sized data structure like a vector.

Indentation

You should fix it up for this line:

for (int k = 1; k < size; ++k) {

Order-of-operations

Neither of these expressions need parentheses:

index = (2 * j + 1);

index < (k - 1)

Deleting a null?

x = nullptr;
delete x;

Does that actually run without crashing?

Const arguments

void heapPrint(int* theheap, int size) {

should be

void heapPrint(const int *theheap, int size) {


Nice.  I only have three comments.

In draw_polygon() use a for loop rather than an explicit counter:

def draw_polygon(a_turtle, length, sides):
    for counter in range(sides):
        a_turtle.forward(length)
        a_turtle.right(360 / sides)

Add comments and/or docstrings.  These will help you when you look at the code in the future.

For these kinds of tasks I usually add a top level docstring with a description of the task.  Include a url to the problem if applicable.  For example at the top of the file:

'''Recursive implementation of Sierpinski Triangle

Assignment from Programming Fundamentals with Python on Udacity.
'''

For any function/method etc. that has an algorithm that isn't immediately obvious from the code, add a comment or docstring explaining what/how it's doing it.  For example, I would add a docstring to draw_recursive_triangle() to explain what the function is doing, any assumptions (does it matter which way the turtle is pointing?, are there min or max limits on length? are the triangles always equilateral?, etc.).
The functions might be useful in another program/assignment.  Rather than rewriting them, you could import this file as a library if you use a if __name__ == "__main__": guard like so:

if __name__ == "__main__":
    draw()

That way it runs the program if you execute the file, but not if you import it as a library


Longest word in dictionary that is a subsequence of a given string

How about using a regex for S, where all characters are optional by appending a ? to each character:

import re

D = ["able","ale", "apple", "bale", "kangaroo"]
S = "abppplee"

regex = '^' + '?'.join(list(S)) + '?' + '$'

words = sorted(D, key=lambda word: len(word), reverse=True)

for word in words:
    if re.match(regex, word):
        print(word)
        break


JSON.parse must always be wrapped in a try catch, because you cannot guarantee that the body will be in proper format.  This will crash your server on failure.

You should add a test case to confirm this, just by responding with an empty string.


Your first solution's time complexity is non-trivial to determine, and it won't work for long lists because it'll run out of stack, while your second solution obviously needs linear time (optimal) and is unlikely to run out of memory, so I would scrap the first one right away.

The first solution is also inferior because of the _mem member. There is no reason to create this in Rob, and there is no reason to make it a member. Making it a member means:
 - this code can't be called concurrently
 - it leaves memory hanging around once the method exists
 - it is susceptible to interference by other members
 - it is hard to reason about than a variable because it is removed from the method that use it

One nice solution would be to make _mem a local variable, and Helper a local function in Rob: that way you don't have to pass nums and _mem around, and there is no way to mis-use the code. Then you can make all these methods static.

Naming

The naming could be better:

_mem and memo are both cryptic (_mem is providing memoisation, and memo is arguably not)
Rob and Rob2 convey almost nothing
Helper says nothing at all (what is it helping? what does it do?)

Documentation

Please take the time to add documentation. It doesn't matter if you are practising for an interview: real code needs documentation (so that it can be consumed and maintained), writing it is a skill worth practising, and doing so helps you to better reason about your code and solidify edge-case behaviour.

Tests

The tests are limited and not very good. They do not test the case where you need to 'skip' a pair (e.g. 9, 1, 1, 9) and do not cover any edge cases.

Both methods will throw on a NullReferenceException on null input, when they should probably throw a nice ArgumentException so that the caller knows immediately what they did wrong: ideally this would be tested.


A pythonic way of de-interleaving a list (i.e. data from a generator), into multiple lists

from datetime import datetime

def unpack_data(data):
    l = len(data)
    p = 0

I'd avoid such small variable names, it makes your code harder to follow

    while p < l:
        # convert 'char' or byte to (signed) int8
        i1 = (((ord(data[p]) + 128) % 256) - 128)
        p += 1
        if i1 & 0x01:
            # read next 'char' as an (unsigned) uint8
            #
            # due to the nature of the protocol,
            # we will always have sufficient data
            # available to avoid reading past the end
            i2 = ord(data[p])
            p += 1
            yield (i1 >> 1 << 8) + i2
        else:
            yield i1 >> 1

# generate some test data ...
test_data = ''
for n in range(500 * 12 * 2 - 1):
    test_data += chr(n % 256)

It usually better to put all the pieces of a string in a list and then join them. Python doesn't have good performance for added strings.

t0 = datetime.utcnow()

# in this example we have 6000 samples, 8 channels, 750 samples/channel
# data received is interleaved: A1, B1, C1, ..., A2, B2, C2, ... F750, G750, H750
channels = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H')

samples = { channel : [] for channel in channels}

# call unpack_data(), receive a generator
gen = unpack_data(test_data)

t1 = datetime.utcnow()

print 'time to create generator: %s' % (t1-t0)

All you've done is created the generator, that won't do any actual work. So you aren't measuring much of anything here. You are still spending much of the time inside the function you've defined after this point.

try:
    while True:
        for channel in channels:
            samples[channel].append(gen.next())
except StopIteration:
    pass

It's best to avoid dealing with StopIteration directly if you can. In this case you can do:

for sample, channel in zip(gen, itertools.cycle(channels)):
     samples[channel].append(sample)

itertools.cycle() will give you a generator that goes repeatedly through all the channels in order.

print 'time to de-interleave data: %s' % (datetime.utcnow()-t1)

print 'length of channel A is 750: %s' % (len(samples['A']) == 750)

You can use numpy, I've done that for you. Basically, numpy lets you do operations over a whole array and that's faster then doing them in your loops. See below:

from datetime import datetime
import numpy

def unpack_data(data):
    # reads the string in as a sequence of uint8
    data = numpy.fromstring(data, numpy.uint8)
    # figure out if the most significant bit is set
    # for everything
    odds = numpy.logical_not(data & 0x01)

    # calculate the interpretation of each number
    # both possible ways
    singles = data.astype(numpy.int8) >> 1
    doubles = singles << 8 + numpy.roll(data, -1)

    # I couldn't vectorize this, it fills up the
    # result array with True for every actual starting value
    result = numpy.empty(data.shape, bool)
    current = True
    for index, byte in enumerate(odds):
        # the next bit is a starting bit if
        # if this isn't a starting bit, or the 1 bit wasn't set
        current = not current or byte
        result[index] = current

    # where chooses from the single and doubles
    # based on the lsb, and result filters those we actually want
    return numpy.where(odds, singles, doubles)[result]

# generate some test data ...
test_data = ''
for n in range(500 * 12 * 2 - 1):
    test_data += chr(n % 256)

t0 = datetime.utcnow()

# in this example we have 6000 samples, 8 channels, 750 samples/channel
# data received is interleaved: A1, B1, C1, ..., A2, B2, C2, ... F750, G750, H750
channels = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H')

samples = { channel : [] for channel in channels}

# call unpack_data(), receive a generator
data = unpack_data(test_data)

t1 = datetime.utcnow()
print 'time to create generator: %s' % (t1-t0)

# reshape converts 1 dimensional array
# into two dimensional array
data = data.reshape(-1, len(channels))
for index, channel in enumerate(channels):
    samples[channel] = data[:,index]

print 'time to de-interleave data: %s' % (datetime.utcnow()-t1)

print 'length of channel A is 750: %s' % (len(samples['A']) == 750)


I will only comment about the following not-fully-implemented part.

 for (auto& kv : tagMap) {
     if (kv.first == "id") {
     std::string var = eb.second.child_value(kv.second.c_str());
     // Do work on returned value of id tag in the future (I.e validation)
     std::cout << var << endl;
     }
     if (kv.first == "description") {
     std::string var = eb.second.child_value(kv.second.c_str());
     // Do work on returned value of content tag in the future
     std::cout << var << endl;
     }
     if (kv.first == "url") {
     std::string var = eb.second.child_value(kv.second.c_str());
     // Do work on returned value of web_address tag in the future
     std::cout << var << endl;
     }
 }

Even without much code filling the blanks, it seems that you want to have some associative tag => function data. In which case, you could create an std::unordered_map with strings as keys and associating function pointers to them, generated from captureless lambdas. A small example:

std::unordered_map<std::string, void(*)(const std::string&)> tasks = {
    { "id", [](const std::string& val) {
        // Do work on returned value of id tag
    }},
    { "description", [](const std::string& val) {
        // Do work on returned value of content tag
    }},
    { "url", [](const std::string& val) {
        // Do work on returned value of web_address tag
    }}
};

for (auto& kv: tagMap) {
    auto it = tasks.find(kv.first);
    if (it != tasks.end()) {
        it->second(eb.second.child_value(kv.second.c_str()));
    }
}

That way, your code is easy to extend to other tags by representing tasks associated to tags as data and storing them into a map. Now, it will only work if you don't need captures, otherwise, you may have to use std::function or some more heavyweight mechanism instead of a big chain of if.


The short answer is:

Don't use vba, use a formula. In particular, a combination of IF and SEARCH.

=IF(SEARCH($A1,"Admin")>0,"Exploitation","")

But this is code review, so let's do that anyway.

Regex is slow. It seems that you're only using it for it's case insensitivity. Given that, you can directly compare cell values by using StrComp with the vbTextCompare option. (useful article on StrComp)
i and j are typically used for loop counters, but row and col make more sense in this case.

Here is what this could could look like:

Dim row As Integer
For row = 1 To 10 'let's say there is 10 rows
    Dim col As Integer
    For col = 1 To 2
        If StrComp("Admin",Cells(row, col).Value,vbTextCompare) Then
            Cells(row, col + 1).Value = "Exploitation"
        End If
    Next col
Next row


You can make GetMinDistance generic:

double GetMinDistance<T>(IList<T> objects, GeoCoordinate position)
  where T: IGeoObject
{
    // ...
}

You can use it like this:

List<User> user = ....;

GetMinDistance(user, position);


Getter and setter for a k-d nested list-of-lists

Some very nice code, overall. There's some minor points I think could be improved, but your general implementation is good.

Nitpicks

I'd like to point out some small 'issues' regarding best-practice and code style:

PEP8 recommends using 4 spaces for indentation. They're not too fond of tabs, but most editors will replace tabs with  spaces automatically.
Using assert is great for catching bugs, but it'd better to raise an exception instead when releasing your code. This allows us to specify a specific exception type (like ValueError or TypeError) and provides some additional stack trace information.
It's important to use good names for objects. You're almost there, but a name like cur_grid may as well just be called current_grid, for clarity.
Instead of manually comparing type, we can use isinstance which allows something like this: assert not isinstance(curr_grid, list).

Implementation

The code as is works just fine if you need to modify a matrix, but wouldn't it be useful to turn it into a separate object altogether? We can do this by creating a custom class:

import collections

class Matrix(collections.UserList):
    """A Matrix represents a collection of nested list objects.
    Methods:
    get -- Get a value from the matrix.
    put -- Put a value into the matrix.
    """
    def __init__(self, data):
        """Constructor.

        :param list data: a matrix (multi-dimensional list).
        :return: None
        """
        super(Matrix, self).__init__(data)

    def get(self, indices):
        """Get a value from the matrix.

        :param iterable indices: iterable containing indices.
                                 the last index must point to an object
                                 that is not a list.
        :return: matrix at indices[-1]
        :raises TypeError: if the last index points to a list
        """
        grid = self.data
        # As assigned by UserList
        for index in indices:
            grid = grid[index]
        if isinstance(grid, list):
            raise TypeError("last element is not 1-dimensional")
        return grid

    def put(self, indices, value):
        """Put value at matrix[indices].

        :param iterable indices: iterable containing indices.
                                 the last index must point to a list.
        :return: None
        :raises TypeError: if the last element is not a list
        :raises TypeError: if the last element contains a list
        """
        grid = self.data
        for index in indices[:-1]:
            grid = grid[index]
        if not isinstance(grid, list):
            error = "expected 'list' node, but got '{}'".format(type(grid))
            raise TypeError(error)
        if isinstance(grid[0], list):
            raise TypeError("last element is not 1-dimensional")
        grid[indices[-1]] = value

Note: the class as implemented must be initialized with a matrix and breaks if an empty iterable is passed for data.


Notes:

Your code looks pretty good, but I personally wouldn't have written it as a mixable module, this code seemps completely independent from ActiveRecord. I'd write a SpreadSheetReader class and just use it from wherever you want (this way the code is more modular).
Where is import_from called from? it seems some code is missing.
This vat_in conditional seems too verbose. Which are the possible values of row[:client]?

I'd write something like:

company = company_from_somewhere_i_dont_know
columns = [:name, :client, <other columns>...]

SpreadSheetReader.rows(:columns => columns).map do |row|
  invoice = company.invoices.find_or_initialize_by_name(row[:name].to_s)
  vat_in = row[:client].is_a?(String) ? row[:client] : row[:client].to_i.to_s
  client = company.clients.find_by_vat_in!(vat_in)
  invoice.update_attributes!({
    :pay_date => row[:pay_date],
    :full_amount => row[:full_amount].to_i,
    :paid_amount => row[:paid_amount].to_i,
  })
  invoice
end


Loading sub items of TreeView in background

I do not see your full UI then maybe you're using it (to display a busy indicator?) but, from what I have here, it seems that IsLoading is just a repetition for IsLoaded and as such it should be dropped. Any reason for EnsureChildrenAreLoaded() to be public and TreeItemViewModel not to be sealed?

EnsureChildrenAreLoaded() might be:

var children = LoadChildren().ToArray();
App.RunOnGuiThread(() =>
{
    foreach (var child in children)
        childrenToFill.Add(child);

    IsLoaded = true;
});

However we now have the problem to preload the children. My major concern here is that you're queuing an action in the pool each time you read the property. Not such big overhead but avoidable. Also I'd move this responsibilities to separate methods:

void LoadChildrenAndUpdateUi(ObservableCollection<TreeItemViewModel> childrenToFill)
{
    IsLoaded = true;

    var children = LoadChildren().ToArray();
    App.RunOnGuiThread(() =>
    {
        foreach (var child in children)
            childrenToFill.Add(child);
    });
}

And:

ObservableCollection<TreeItemViewModel> EnsureChildrenAreLoaded(
    ObservableCollection<TreeItemViewModel> childrenToFill, int depth)
{
    if (depth >= PRELOADING_DEPTH)
        return;

    if (!IsLoaded)
        ThreadPool.QueueUserWorkItem(_ => LoadChildrenAndUpdateUi(myChildren));

    foreach (var child in myChildren)
        child.EnsureChildrenAreLoaded(child.myChildren, depth + 1);

    return myChildren;
}

Our getter will then be:

public ObservableCollection<TreeItemViewModel> Children
    => EnsureChildrenAreLoaded(myChildren, 0);

Major difference is that we're going through the children to determine if they have to be loaded in the calling UI thread but we're queuing an action in the thread pool only when required. Note that we're using only one property to track the state (IsLoaded, which should be private). I set its value to true before effectively reading children to avoid multiple parallel requests, name is now somehow misleading and should be changed to something meaningful (_isVisited or something like that).

What next? If PRELOADING_DEPTH might ever be 0 or loading time may be really long then I'd add a dummy item to the child collection (to display the expand/collapse indicator), something like:

public TreeItemViewModel()
{
    Children.Add(new TreeItemViewModel { Name = "Loading..." });
}

Removed before you start adding new items:

children.Clear();
foreach (var child in children)
    childrenToFill.Add(child);

But, well, you already have a busy indicator then you don't need this at all!

Edit: if you're using IsLoading in your UI then, unfortunately, you can't drop it that easily. I think you have two options: replace IsLoading and IsLoaded with an enum like enum LoadingStatus { NotLoaded, Loading, Loaded } used in conjunction with a value converter to hide/show the busy indicator or use ordering (as you already doing) to avoid locks (because fortunately you have only one thread for writing):

var children = LoadChildren().ToArray();
App.RunOnGuiThread(() =>
{
    foreach (var child in children)
        childrenToFill.Add(child);

    IsLoaded = true;
    IsLoading = false;
});

Set IsLoading in the UI thread to avoid race conditions (both read and write will be then done in the same UI thread):

if (!IsLoaded && !IsLoading)
{
    IsLoading = true;
    ThreadPool.QueueUserWorkItem(_ => LoadChildrenAndUpdateUi(myChildren));
}

Final notes.

If your depth is limited to direct children then you  may simplify your implementation (just invoke the lazy load method when you populate the list). You may also want to try to use a LazyAsync<T> implementation (I saw a nice one somewhere...can't find/remember where).

WPF supports asynchronous binding with a simple IsAsync=true in the binding expression. You may want to experiment with that, see MSDN for details


So the first thing you can do is to use container loops

for (std::string &mystring : str) {
// do someting
}

The second thing would be to have a look at rbegin() and rend, which give you reverse_iterators.

You can find a very good reference here: http://www.cplusplus.com/reference/string/string/rend/

Together you would get something like that

for (std::string &mystring : str) {
    for (std::string::reverse_iterator rit=mystring.rbegin(); rit!=mystring.rend(); ++rit) {
        std::cout << *rit;
    }
}


The problem looks like it would have a solution of complexity \$O(n log n)\$. Yours has \$O(n^2)\$. google "number of increasing subsequences".
The site says input size can be \$10^5\$. A \$O(n^2)\$ algorithm with hash look-ups, hash inserts, and virtual function calls in the inner loop will not finish in a few minutes.
By replacing

int x=scn.nextInt();

with

int x = 100000;

and

    arr[i]=scn.nextInt();

with

 arr[i] = i + 1;

you can easily test how your program performs with large input.
A quick order of magnitude analysis: An increasing sequence of ~\$10^5\$ elements will have \$~(10^5)^3\$ increasing subsequences of length 3. Since \$10^3 ~= 2^10\$, \$10^15 ~= 2^50\$. \$2^50\$ >> \$2^31\$. So your triplets variable will overflow. It should be an long.


You're going to get false positives by comparing the output of ls -l.  In many locales, this command gives date stamps in different formats for newer files (day+time) and older files (year+day).  When any file transitions from "new" to "old" in this scheme, you'll get a spurious notification.  If you have the GNU implementation of ls, you can make it use a specific timestamp format (e.g. --time-style=full-iso) which might alleviate that problem.  Or just accept the false positives (make should be reasonably quick if nothing actually changed).
The usual problem of failing to quote arguments ($1 where you should have written "$1") will mess up arguments that contain whitespace or shell pattern characters.  Although that might be unlikely for your source directories, it's trivial to fix, and a good habit to have.
Testing that the string true is non-empty ([ true ]) is an unusual approach to making an infinite loop - most shell programmers would simply use the true command.  Actually, it's probably better to test the result of sleep, which returns non-zero if interrupted.
Instead of polling, you should be able to block on filesystem notification events.  Perhaps inotifywait meets your needs here?
If we use plain [ rather than [[, the code becomes portable (POSIX) shell, without needing Bash extensions, so is useful to more people.
Is it right that you want to run make in the current directory?  For some users, it might make more sense to make -C "$1".  You could be more flexible by allowing a command to be specified (here I've kept make as default):
monitor_and_build()
{
    local d=${1:-.}; shift
    test -d "$d" || return 1
    local sauce=$(ls -l --time-style=full-iso "$d")
    while sleep 1
    do
        local newsauce=$(ls -l --time-style=full-iso "$d")
        if [ "$sauce" != "$newsauce" ]
        then "${@:-make}"
        fi
        local sauce="$newsauce"
    done
}


Dephi: faster way to convert a "dirty" string to a number

Don't over use set. It is faster when the items are discrete, but slower when the items are continuous. Although, the difference is very small in your case.

The problem here is that you use delete repeatedly. Each call moves (copies) a potentially large chuck of characters. This is inefficient because many characters are moved multiple times. For example, 5 in string 1 2 3 4 5 is moved 4 times.

Given that string in Delphi is mutable, it is better to copy individual characters:

function CleanNumber(s: String): Int64;
Var
  z, l: Cardinal;
begin
  l := 1;
  for z := 1 to length(s) do
    if (s[z] >= '0') and (s[z] <= '9') then
    begin
      s[l] := s[z];
      inc(l);
    end;
  SetLength(s, l - 1);

  if s = '' then
    Result := 0 else
    Result := StrToInt64(s);
end;

It can be further improved:

function CleanNumber(s: String): Int64;
Var
  z, l: Cardinal;
begin
  l := 1;
  while (l <= length(s)) and (s[l] >= '0') and (s[l] <= '9') do
    inc(l);       // Scan for the first non-numeric char

  for z := l + 1 to length(s) do  // Start from l + 1
    if (s[z] >= '0') and (s[z] <= '9') then
    begin
      s[l] := s[z];
      inc(l);
    end;

  if l = 1 then Result := 0 else
  begin
    SetLength(s, l - 1);
    Result := StrToInt64(s);
  end;
end;

Note: code not tested.


Detecting if image taken by camera is too dark

Sampling: Don't process ALL pixels

The speed mainly depend on the number of operations, in our case, pixels. And a lot of pixels. This means that the larger the image is, the slower your code will run.

You probably don't need to process all pixels, just a representative subset of them.

Taking this subset is called sampling. You can for example only process every 100th pixel.

If you want to go more fancy, try Monte Carlo sampling.

If you really need all the pixels, check OpenCV, that is optimized for image processing.


UITableView, auto locate back at indexPath when user drags it

A couple of observations:

You are handling scrollViewDidEndDecelerating. But what if there was no deceleration? E.g. you’d generally want to call some common routine, e.g. didFinishUserScroll, either way:

func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    if !decelerate {
        didFinishUserScroll()
    }
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    didFinishUserScroll()
}

It looks like you are scrolling as soon as deceleration finishes. I would suggest that you only want to scroll at the end of the user gesture (whether decelerating or not) only if there is an update to the position in the lyrics in the intervening period of time.

E.g. you’re bopping along in a song, the drummer goes off into some lengthy, lyric-free solo, so the bored user starts scrolling through the lyrics themselves. When they let go, if the drum solo is still in progress, I’d suggest that you might not want to scroll back until the singing resumes. I wouldn’t necessarily scroll back immediately.

Now maybe you’ve got the sort of logic in the code you didn’t share with us, and if so, don’t worry about it. But, frankly, the fact that tracking is so ambiguous is code smell. (I.e., is it a boolean whether a touch gesture is in progress? is it indicating that we’re following along with lyrics at all? is it that there are updates to progress in the song that requires update of the position?) The fact that the intent of tracking is so ambiguous suggests you might consider a better name for it.
It looks like currentPath is an Int, a row number. So I wouldn’t call it currentPath, but rather currentRow.
When you have a boolean, you generally just check the value, not compare it to another boolean. So, for example, instead of:

if tracking == true {
    tracking = false
    scrollToRow(at: IndexPath(row: currentPath, section: 0), at: UITableView.ScrollPosition.middle, animated: true)
}

You would do:

if tracking {
    tracking = false
    scrollToRow(at: IndexPath(row: currentPath, section: 0), at: .middle, animated: true)
}

I also removed the redundant UITableView.ScrollPosition reference.
This is beyond the scope of this question, but the fact that you’re calling scrollToRow(at:at:animated:) without referencing the table view worries me, making me wonder whether you have all of this business logic buried inside your table view. We generally strive to isolate our UI from business logic of the app.


Well, you could do some refactoring with this code, the only issue I see is that the low level functinality is implemented at the top level of your code. It would be better to extract the logic to separate functions, something like this (I also improved your code formatting a little bit):

$((function() { // Deleted the "document).ready" part, that is not necessary.
    // Hide all content.
    $(".tab_content").hide();

    // If hash is present in the URL, show tab by hash. Otherwise, show the first tab.
    if(document.location.hash!='') {
        showTabByHash();
    }
    else {
        showFirstTab()
    }

    // On the click event of a tab.
    $("ul.tabs li").click(function (e) {
        e.preventDefault();
        showTab($this);
    });
});

function showTab(tab) {
    // Remove any "active" class.
    $("ul.tabs li").removeClass("active");

    // Add "active" class to selected tab.
    tab.addClass("active");

    // Hide all tab content
    $(".tab_content").hide();

    // Find the href attribute value to identify the active tab + content
    var activeTab = tab.find("a").attr("href");

    // Fade in the active ID content.
    $(activeTab).fadeIn();
}

function showTabByHash() {
    // Get the index from URL hash.
    var tabName = window.location.hash;
    // Shorten #tab2 to just last digit "2".
    var tabNumber = tabName.substr(4,1);

    // Why are these two lines needed? Don't they work with the same tab element?
    $(tabName).show(); //Show tab from url hash
    $("ul.tabs li:nth-child(tabNumber)").addClass("active").show();
}

function showFirstTab() {
    // Activate first tab.
    $("ul.tabs li:first").addClass("active").show();

    // Show first tab content.
    $(".tab_content:first").show();
}

I do not see any other problems with the code (of course, it could be generalized a little bit, but that is not your goal if I understand right), apart from your coding style, which was a little bit cluttered in my opinion (I had to read it more than one time to completely understand it).
And if you are developing in Visual Studio, and these functions are going to be used from somewhere else, then adding XML comments to them would generally be a good idea.


You could use a switch statement instead of the if elses to make it prettier.
Or, you could use a map<string, vector<string>>

Instead of using whole namespaces, restrict usage to single items.
In order to not pollute your own namespace with names, do single 'using' instead of 'using namespace'. The following will suffice for your code.
using namespace std;
using chrono::milliseconds;
using chrono::system_clock;
using this_thread::sleep_for;

Instead of float fuckingdummyvar; cin >> fuckingdummyvar;, do a single getchar() or use any other method described here.

Use consistent bracing.
This is a matter of opinion, but I prefer to always have braces around if and else statements, even when only one statement follows. I used to not put any braces, but then I ran into a nice bug that was seriously puzzling me when I added a return to an else and it would always return for some reason. That's because the return was the second statement after the else and there weren't brackets around it.

Use a map to avoid big 'n' dirty blocks of code..
#include <iostream>
#include <string>
#include <chrono>
#include <thread>
#include <map>
#include <vector>

using namespace std;
using chrono::milliseconds;
using chrono::system_clock;
using this_thread::sleep_for;

int main()
{
    map<string, vector<string>> quotes{
                                        {"Aquaman", {"What's this blue pants? What-- what's this blue pants?"}},
                                        {"California Games", { "SWOOD THIS! SWOOD THAT! What the FUCK does SWOOD mean?!?!?!", "I used to say it all the time in Cali! Grommet this, grommet that!" }},
                                        {"The Zoo Race", {"What'd they program this in, C--??"}}
                                      }; //In C++11 and up {"String1", "String2"} is a vector<string> = {"String1", "String2"}

    cout << "Choose a JonTron episode!" << endl;
    string JonTron;
    getline(cin, JonTron);

    if (quotes.count(JonTron)) { //Checks if there is a map key with the episode that the user inputted.
        for (auto &s : quotes[JonTron]) { //Iterates over every string in the vector<string> that's stored in quotes[JonTron].
            cout << s << endl;
            sleep_for(milliseconds(1000)); //If you want custom sleep times as well, do a map<string, customClass with vector of quotes and vector of milliseconds.
        }
    }
    else {
        cout << "Episode not found!.";
    }

    getchar();
}

Use a text file with all the quotes and episodes.
The best way would be to create a text file and retrieve the quotes from there.


Managing many exceptions in Erlang cowboy without deeply nested trees

My first attempt (without changing any of your functions nor the semantics of your handler) would be:

projects_from_json(Req=#{method := <<"POST">>}, State) ->
    try
        {ok, ReqBody, Req2} = cowboy_req:read_body(Req),
        Name = get_project_name(ReqBody),
        {ok, Conn} = moledb:connect_from_config(),
        Data = get_project_json(Conn, Name),
        molehill_respond:respond_status(Data, 201, Req2, State)
    catch
        error:{badkey, Key} ->
            molehill_respond:respond_error(
                <<"MissingKey">>,
                erlang:iolist_to_binary(
                    [<<"Key \"">>, Key, <<"\" does not exist in passed data">>]),
                400, Req2, State);
        error:{error, Label, Message, Status} ->
            molehill_respond:respond_error(Label, Message, Status, Req2, State)
    end.

get_project_name(ReqBody) ->
    Name = project_name(ReqBody),
    case validate_project_name(Name) of
        invalid ->
            erlang:error({
                error,
                <<"InvalidValue">>,
                <<"The project name can only consist of ASCII characters and numbers, "
                    "and dash in the middle of the word.">>,
                400
            });
        ok ->
            Name
    end.

get_project_json(Conn, Name) ->
    try
        moledb:create_project(Conn, Name),
        prepare_project_json(Name)
    catch
        error:duplicate_element ->
            erlang:error({
                error,
                <<"DuplicateValue">>,
                erlang:iolist_to_binary(
                    [<<"A project with name \"">>, Name, <<"\" already exists">>]),
                409
            })
    end.

I basically moved pieces of your code from projects_to_json/2 into its own functions so you can keep your main one tidier.

But you might have noticed that my new functions still have a lot of code for encapsulating the errors. If you can get validate_project_name/1 and prepare_project_json/1 to raise the errors in the proper format themselves instead of returning invalid | ok, this gets reduced to…

projects_from_json(Req=#{method := <<"POST">>}, State) ->
    try
        {ok, ReqBody, Req2} = cowboy_req:read_body(Req),
        Name = project_name(ReqBody),
        validate_project_name(Name),
        {ok, Conn} = moledb:connect_from_config(),
        moledb:create_project(Conn, Name),
        Data = prepare_project_json(Name)
        molehill_respond:respond_status(Data, 201, Req2, State)
    catch
        error:{badkey, Key} ->
            molehill_respond:respond_error(
                <<"MissingKey">>,
                erlang:iolist_to_binary(
                    [<<"Key \"">>, Key, <<"\" does not exist in passed data">>]),
                400, Req2, State);
        error:{error, Label, Message, Status} ->
            molehill_respond:respond_error(Label, Message, Status, Req2, State)
    end.

%% @doc this function may raise an error like {error, binary(), binary(), 400..499}
validate_project_name(Name) ->
    …

%% @doc this function may raise an error like {error, binary(), binary(), 400..499}
prepare_project_json(Name) ->
    …

Basically, the idea is to include as much information as you need on the error itself, so… instead of failing with duplicate_element, you fail with {error, …, …} so that the outer loop can catch that. If you can’t decide on how your functions will fail, just wrap them up in other functions that will translate the errors/results into the expected form.


Passing object back to Windows Form button event

public StatusKeeper Status = new StatusKeeper();

It's a very bad idea to return the result via a public field.

If anything bad happens you should throw an exception. By doing this you automatically will need to move the stylings to somewhere else but this is what we want - separate different responsibilities. Your class is doing too much right now. The ScriptStarter shouldn't know anything about the colors etc. Its only responsibility should be to start scripts. It could be much simpler like this:

class ScriptStarter
{
    public void RunScript()
    {
        var scriptFilePath = Properties.Settings.Default.MyStartCacheScriptPath;
        if (string.IsNullOrEmpty(scriptFilePath) || !File.Exists(scriptFilePath))
        {
            scriptFilePath = setNewScriptFile();
        }

        if (!File.Exists(scriptFilePath))
        {
            throw new FileNotFoundException("Script not found.", scriptFilePath);
        }

        runBatScript(scriptFilePath);
    }

    private void runBatScript(string scriptFilePath)
    {
        // do something and throw if it didn't work
        throw new ScriptStartException(); // create a new type of exception for this
    }

    private string setNewScriptFile()
    {
        // returns script path
    }
}

How do we run this now?

We write a new method that will use the ScriptStarter and handle the results:

private void RunScript()
{
    try
    {
        ScriptStarter.RunScript();
        UpdateScriptStatusLabel("Script started", Color.ForestGreen);
    }
    catch (FileNotFoundException)
    {
        UpdateScriptStatusLabel("Script not found.", Color.Crimson);
    }
    catch (ScriptStartException)
    {
        UpdateScriptStatusLabel("Script not started.", Color.Crimson);
    }
    catch (Exception ex)
    {
        UpdateScriptStatusLabel($"Something else happened: {ex.Message}", Color.Red);
    }
}

We also need another one that will take care of the status label:

private void UpdateScriptStatusLabel(string text, Color color)
{
    toolStripStatusLabel1.Text = text;
    toolStripStatusLabel1.ForeColor = color;
}

Now that we have separated all concerns we can finally update the event handler:

private void btnStartScript_Click(object sender, EventArgs e)
{
    RunScript();
}

What did we win? We won maintainability and reusability. If you decide to add a keyboard shortcut in a future version then you just call the RunScript() from there and that's it. No repetition of the formatting or the logic how to run the script.