Summing up students by the topics they studied and the marks they got

The main part of programming is writing code so that it makes sense to others, and the biggest part of that is slicing your code into functions (Single Responsibility) which do only one thing.
If I was changing your code, the first thing I would do is move everything under your entry point (if __name__... - good BTW, always have an entry point) into functions, and have the main communicate what the code is doing. For instance:

if __name__ == "__main__":
    load_student_files_into_data_frames()
    merge_test_marks()
    group_students()
    print_students_and_course_results()

Now I understand the purpose of your code without having to look for a README.txt or spending 5-10 minutes reading or stepping through your code. This is also a good technique for understanding program flow before you actually write code inside the functions (and lends itself to TDD, but that's another topic for another day).

Of course, doing that with your code as it currently is, breaks all operations.
Even if we update the load process to return each data frame, it starts to look messy:

def load_student_files_into_data_frames():
    students_df = pandas.read_csv("students.csv")
    marks_df = pandas.read_csv("marks.csv")
    tests_df = pandas.read_csv("tests.csv")
    courses_df = pandas.read_csv("courses.csv")
    return students_df, marks_df, tests_df, courses_df

if __name__ == "__main__":
    students_df, marks_df, tests_df, courses_df = load_student_files_into_data_frames()

Now we've encountered the DRY (Don't Repeat Yourself) code smell - performing the same operation multiple times. Let's extract out the CSV read into a separate function like this:

def read_csv(filename):
    return pandas.read_csv(filename)

def load_student_files_into_data_frames():
    file_names = ["students.csv", "marks.csv", "tests.csv", "courses.csv"]
    return map(read_csv, file_names)

However, now we violated the Open/Close Principle - which is that code should be closed for modification but open for enhancement. For example, if you need to add another CSV, you'd have to open the code up, edit it and put the new CSV in, correct? Or if the CSV comes from an external company, and they change its name (for whatever reason), you'd need to edit the code to make it work again, yes? This is true for magic numbers and anything else which can change.
So, the best method is to have the file names in an external .ini file, and use ConfigParser to load the names - but this is a small script, so we'll just define them in the __main__.

def load_student_files_into_data_frames(filename_list):
    return map(read_csv, filename_list)

if __name__ == "__main__":
    filename_list = ["students.csv", "marks.csv", "tests.csv", "courses.csv"]
    students_df, marks_df, tests_df, courses_df = load_student_files_into_data_frames(filename_list)

That's much cleaner, and now we're starting to write our functions in a functional programming style - which is we pass data in, get it modified, and get it passed out again. Nice and clean, and we know exactly what happens to the data where, making it very easy to narrow down bugs.

For instance, the merge_test_marks() function becomes:

def merge_test_marks(marks_df, tests_df):
    return pandas.merge(marks_df, tests_df, left_on="test_id", right_on="id")

and if there were any issues with the merging of those two data frames, you know exactly which function was responsible for the bug (rather than having to laboriously step through the code with a debugger to understand where the variable's data state changed wrongly).

So here would be the final version, and whilst I haven't done anything to clean up the print_students_and_course_results function - as we have two internal loops that should be shuffled off to a separate function - I'll leave that as an exercise for you to attempt. Hope this was helpful, here is the final code (PEP8 formatted except I removed the extra line between functions to make it visually shorter):

import pandas
from statistics import mean

def read_csv(filename):
    return pandas.read_csv(filename)

def load_student_files_into_data_frames(filename_list):
    return map(read_csv, filename_list)

def merge_test_marks(marks_df, tests_df):
    return pandas.merge(marks_df, tests_df, left_on="test_id", right_on="id")

def group_students(marks_tests, students_df, courses_df):
    student_courses = marks_tests.groupby(by="student_id")['course_id'].apply(set)
    students_dict = students_df.set_index("id").to_dict(orient="index")
    courses_dict = courses_df.set_index("id").to_dict(orient="index")
    return student_courses, students_dict, courses_dict

def print_students_and_course_results(student_courses, students_dict, marks_tests, courses_dict):
    for student_id, course_ids in student_courses.iteritems():
        print("Student id: {}, name: {name}".format(student_id, **students_dict[student_id]))
        final_grades = []
        for course_id in course_ids:
            marks = marks_tests.loc[(marks_tests['course_id'] == course_id) & (marks_tests['student_id'] == student_id)]
            final_grades.append(sum(marks['mark'] * (marks['weight'] / 100.0)))

        print("Total Average: {:.2f}%".format(mean(final_grades)))
        for course_id in course_ids:
            print("  Course: {name}, Teacher: {teacher}".format(**courses_dict[course_id]))
            marks = marks_tests.loc[(marks_tests['course_id'] == course_id) & (marks_tests['student_id'] == student_id)]
            final_grade = sum(marks['mark'] * (marks['weight'] / 100.0))
            print("  Final Grade: {:.2f}%".format(final_grade))

if __name__ == "__main__":
    filename_list = ["students.csv", "marks.csv", "tests.csv", "courses.csv"]
    students_df, marks_df, tests_df, courses_df = load_student_files_into_data_frames(filename_list)
    marks_tests = merge_test_marks(marks_df, tests_df)
    student_courses, students_dict, courses_dict = group_students(marks_tests, students_df, courses_df)
    print_students_and_course_results(student_courses, students_dict, marks_tests, courses_dict)

Keep up the coding and Good Luck!


Monitoring progress in Parallel.ForEach every minute

Instead of checking the time from each thread on each iteration, I would use a Timer:

int count = 0;

TimeSpan reportPeriod = TimeSpan.FromMinutes(0.1);

using (new Timer(
    _ => Console.WriteLine("{0}: Extracted {1} urls", DateTime.Now, count),
    null, reportPeriod, reportPeriod))
{
    Parallel.ForEach(
        list, tuple =>
        {
            //download urls ...

            Interlocked.Increment(ref count);
        });
}

Console.WriteLine("{0}: Done", DateTime.Now);

I have also renamed cnt to count, those two characters are not worth it to make your code less readable.


Interface Segregation Principle in constructor

No, this is all broken. The basic issue is the cast-to-D in the following line:

this.d = (D)new MyWaterFowl();

That gives the warning:

Type safety: Unchecked cast from MyWaterFowl to D

Ignoring Generics warnings normally means you are doing something wrong. In this case, you are.

You are doing a cast to a type where you have no certainty, in fact, you are certain that it will fail....

.... the solution here, is to not have a default constructor. It does not make sense for you. Why do you think you need one?

Also, why does MyAmericanEagle extend CanQuack ?


Program to shorten URL and decode it back to get original URL

Flawed approach

There are severals flaws in the current approach:

The program doesn't check if the generated key already exists for a different URL. And it might. And when it does, the new value will overwrite the old one. The old value will be no longer retrievable.
encode returns a different output for the same input, with very high probability. In fact you can make the program run out of memory by calling encode on the same string enough times.
The implementation wastes a lot of memory. There's no need to use the full tiny URL as the key of the cache, the unique part would be enough, and divide the storage size of the keys by 3.
It's unrealistic to expect a URL shortening service to run forever without server reboots. Since this implementation doesn't use any storage outside RAM, all previously stored URLs will be completely lost when the process is restarted.

Technical issues

There are many technical implementation flaws:

No need to create a new Random in every call of encode. Better use a shared instance.
Magic numbers and strings should be constants or class parameters: the target key length (6), the alphabet.
The names are not great. urlLen is not the length of a URL, but the length of the unique part only (6 letters). randChars are not "random chars", but an alphabet from which to pick a random character.
It's a bad practice to print to stdout from methods that are not particularly designed to print stuff.
Prefer to declare variables using interface types: Map instead of HashMap.
Using a StringBuilder is overkill, a simple concatenation with + would be better.


Checking if a list of coordinates defines a closed, exact rectangle

Proposed solution

Okay BoardPosition should be an immutable data structure like this:

public class BoardPosition {
        public final int x;
        public final int y;

        public BoardPosition(int pX, int pY) {
                y = pY;
                x = pX;
        }
}

You should never specify which specific implementation of List you want but rather that you want a "list" or even a "collection" of positions. See Liskov Substitution Principle.
This is better:

private boolean checkifIsRectangle(List<BoardPosition> lettersPosition) {

This can be done better:

        for (BoardPosition b : lettersPosition) {
            if (!cordsX.containsKey(b.getX())) cordsX.put(b.getX(), 1);
            else {
                cordsX.put(b.getX(), cordsX.get(b.getX()) + 1);
            }

            if (!cordsY.containsKey(b.getY())) cordsY.put(b.getY(), 1);
            else {
                cordsY.put(b.getY(), cordsY.get(b.getY()) + 1);
            }
        }

By avoiding repeated look ups in the tree map, like this:

        for (BoardPosition b : lettersPosition) {
            Integer x = cordsX.get(b.x);
            x = (x == null) ? 1 : x + 1;
            cordsX.put(b.x, x);

            Integer y = cordsY.get(b.y);
            y = (y == null) ? 1 : y + 1;
            cordsY.put(b.y, y);
        }

Around //1 you're creating many unnecessary copies of the values. Consider calling toArray() only once.

This:

        //2
        int xKeyTest = -1;
        for (Integer i : cordsX.keySet()) {
            if (xKeyTest == -1) {
                xKeyTest = i;
                continue;
            }
            if ((i - xKeyTest) != 1) {
                xIsValid = false;
                break;
            }
            xKeyTest = i;
        }

Should be:

        //2
        int xKeyTest = -1;
        for (Integer i : cordsX.keySet()) {
            if (xKeyTest != -1 && (i - xKeyTest) != 1) {
                xIsValid = false;
                break;
            }
            xKeyTest = i;
        }

And similar for Y.

And finally //3 is rather clumsy.

        //3
        ArrayList<Integer> xValueArray = new ArrayList<Integer>(cordsX.values());
        int xTestValue = -1;
        for (int i = 1; i < xValueArray.size() - 2; i++) {
            if (xTestValue == -1) {
                xTestValue = xValueArray.get(i);
                continue;
            }
            if (xTestValue != xValueArray.get(i)) {
                xIsValid = false;
                break;
            }
        }

        ArrayList<Integer> yValueArray = new ArrayList<Integer>(cordsY.values());
        int yTestValue = -1;
        for (int i = 1; i < yValueArray.size() - 2; i++) {
            if (yTestValue == -1) {
                yTestValue = yValueArray.get(i);
                continue;
            }
            if (yTestValue != yValueArray.get(i)) {
                yIsValid = false;
                break;
            }
        }

        return (xIsValid && yIsValid);
    }

If you want to make sure all list entries have the same value, do like this:

    boolean isSame(List<Integer> list){
        Integer first = list.get(0);
        for (int i = 1; i < list.size(); i++) {
            if (first != list.get(i)) {
                return false;
            }
        }
        return true;
    }

In the end your algorithm is \$\mathcal{O}(n\log n)\$ although there is a lot of iteration going on and I would say it's on the slow side of the spectrum.

A better solution

A faster way of doing this would be:

package test;

import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

public class CheckRectangle{

   public static class Point{
      final int x;
      final int y;

      Point(int aX, int aY){
         x = aX;
         y = aY;
      }
   }

   private static class ByX implements Comparator<Point>{
      @Override
      public int compare(Point o1, Point o2){
         int v = Integer.compare(o1.x, o2.x);
         if( v == 0 )
            return Integer.compare(o1.y, o2.y);
         return v;
      }
   }

   static boolean isRectangle(List<Point> aPoints){
      Collections.sort(aPoints, new ByX());

      int ymax = Integer.MIN_VALUE;
      int ymin = Integer.MAX_VALUE;

      {
         Iterator<Point> it = aPoints.iterator();
         Point prev = null;
         while( it.hasNext() ){
            Point next = it.next();
            if( prev != null && prev.x == next.x && prev.y == next.y )
               it.remove();
            prev = next;

            ymax = Math.max(ymax, prev.y);
            ymin = Math.min(ymin, prev.y);
         }
      }

      int xmax = aPoints.get(aPoints.size() - 1).x;
      int xmin = aPoints.get(0).x;

      if( xmax == xmin ){ // Special case the vertical stick
         return (ymax - ymin + 1) == aPoints.size();
      }

      if( ymax == ymin ){ // Special case the horizontal stick
         return (xmax - xmin + 1) == aPoints.size();
      }

      // Number of (non-overlapping) grids in either direction
      int w = (xmax - xmin + 1);
      int h = (ymax - ymin - 1);

      int numGrids = 2 * h + 2 * w;
      if( aPoints.size() != numGrids )
         return false; // Wrong number of points

      // For a rectangle, there must be exactly h+2 points with x == xmin
      if( aPoints.get(h + 1).x != xmin )
         return false;

      // And exactly h+2 points with x == xmax
      if( aPoints.get(numGrids - (h + 2)).x != xmax )
         return false;

      return true;
   }
}

This performs in \$\mathcal{O}(n\log n)\$ as well, but it has much less iteration and memory accesses.

The key here is to sort by 'x' coordinate (you can do it by 'y' too). Due to the sort the list structure is very specific for rectangles and you just need to check a few specific values in the list to be sure that you have a rectangle.

If you don't believe the correctness of my solution, you can execute the unit tests available here: https://gist.github.com/EmilyBjoerk/4f015a7e1b394a73e4cc .


Translate a day in year to month and day

This code is incomplete, so we'll have to guess there's a definition of namespace DayOfYear, or struct DayOfYear, somewhere.  In future, please provide more context for reviews - ideally, we'd be able to take your code and compile it ourselves.

There's a problem with the interface: to convert from Julian day number to month, we need to know whether the year is a leap year or not.  So convertDayOfYear() needs two arguments - as well as the day number, we need to provide either the year number or an indication (as a bool) whether it's a leap year.  From C++20, it's straightforward to convert, using std::chrono::year::is_leap().  We can then use that information like this:

if (!is_leap_year && num >= 59) { // day 59 is 1st of March
    num += 1;
}

We want to reduce that big chain of repeated if/else.  One thing we could do to simplify is to not repeat the previous test: if we're in the else block from if (num <= 31), we already know that num > 31:

if (num <= 31)
    return months[0] + " " + to_string(num);
else if (num <= 59)
    return months[1] + " " + to_string(num - 31);
else if (num <= 90)

What we'd really like is to be able to just look it up in a table.  We can do this using a list of months with their day counts:

const std::vector<std::pair<int, std::string>> day_to_month = {
    { 31, "January" },
    { 29, "February" },         // we'll correct non-leap years to fit
    { 31, "March" },
    { 30, "April" },
    { 31, "May" },
    { 30, "June" },
    { 31, "July" },
    { 31, "August" },
    { 30, "September" },
    { 31, "October" },
    { 30, "November" },
    { 31, "December" },
};

We can walk this list, and at each element look to see if that month contains the day - if it does, create the return value; if not, then subtract that month's amount of days and move on to the next entry:

for (auto const& entry: day_to_month) {
    auto& days_in_month = entry.first;
    auto& month_name = entry.second;
    if (num <= days_in_month) {
        return month_name + " " + std::to_string(num);
    } else {
        num -= days_in_month;
    }
}

I've named the elements of each entry to make it clearer; we could just use entry.first and entry.second instead, but I believe the clarity helps here.

Let's put it all together, with some reasonable range checking and a main() to demonstrate that it works.  Let's also change the vector to be an array, since we know its length in advance.

Then we get:

#include <array>
#include <stdexcept>
#include <string>
#include <utility>

std::string convertDayOfYear(int num, bool is_leap_year)
{
    if (num <= 0)
        throw std::range_error("before beginning of year");

    // correct non-leap years
    if (!is_leap_year && num > 59) { // day 59 is 28th of February
        num += 1;
    }

    static const std::array<std::pair<int, std::string>, 12> days_in_month = { {
        { 31, "January" },
        { 29, "February" },         //  we've adjusted non-leap years
        { 31, "March" },
        { 30, "April" },
        { 31, "May" },
        { 30, "June" },
        { 31, "July" },
        { 31, "August" },
        { 30, "September" },
        { 31, "October" },
        { 30, "November" },
        { 31, "December" },
    } };

    for (auto const& entry: days_in_month) {
        auto& days_in_month = entry.first;
        auto& month_name = entry.second;
        if (num <= days_in_month) {
            return month_name + " " + std::to_string(num);
        } else {
            num -= days_in_month;
        }
    }

    throw std::range_error("after end of year");
}

#include <iostream>
int main()
{
    std::cout << convertDayOfYear(1, false) << '\n'
              << convertDayOfYear(1, true) << '\n'
              << convertDayOfYear(59, false) << '\n'
              << convertDayOfYear(59, true) << '\n'
              << convertDayOfYear(60, false) << '\n'
              << convertDayOfYear(60, true) << '\n'
              << convertDayOfYear(365, false) << '\n'
              << convertDayOfYear(366, true) << '\n';
}

If performance is important, then consider using std::lower_bound to find the month from the list - you'd sacrifice some clarity there, as you'd need to return to using the cumulative day count for each month rather than days in that month (or write code to build the former from the latter).

It's a little bit tricky to get right (both the conversion to cumulative day count and the lookup) but with the help of the test cases, I get this implementation (C++14, because of the auto parameters in the lambda expression, but easily adapted to C++11):

#include <algorithm>
#include <array>
#include <cassert>
#include <stdexcept>
#include <string>
#include <utility>

std::string convertDayOfYear(int num, bool is_leap_year)
{
    if (num <= 0)
        throw std::range_error("before beginning of year");

    // correct non-leap years
    if (!is_leap_year && num > 59) { // day 59 is 28th of February
        num += 1;
    }

    if (num > 366)
        throw std::range_error("after end of year");

    static const auto start_day = []{
        std::array<std::pair<int, std::string>, 12> days_in_month = { {
                { 31, "January" },
                { 29, "February" },         // we've adjusted non-leap years
                { 31, "March" },
                { 30, "April" },
                { 31, "May" },
                { 30, "June" },
                { 31, "July" },
                { 31, "August" },
                { 30, "September" },
                { 31, "October" },
                { 30, "November" },
                { 31, "December" },
            } };
        int offset = 0;
        for (auto& month: days_in_month) {
            std::swap(offset, month.first);
            offset += month.first;
        }
        return days_in_month;
    }();
    // start_day now looks like { {0, "January"}, {31, "February"},
    // {60, "March"}, ... } - i.e. the number of days to subtract for
    // that month.

    // Now search backwards for the first month whose offset is less
    // than num
    auto it = std::lower_bound(start_day.rbegin(), start_day.rend(), num,
                               [](auto a, auto b){ return a.first >= b; });

    assert(it != start_day.rend());
    return it->second + " " + std::to_string(num - it->first);
}


I think the is* functions are a bad idea - Haskell has pattern matching for this.

Also you can 'unwrap' your World when necessary and get unwrapped data from it.

data Cell = Wall | Crate | Storage | Worker | Empty

cellContents coords world = bar where
    f x = S.member coords (x ^$ world)
    bar | f wCrates = Crate
        | f wWalls = Wall
        | f wStorage = Storage
        | coords == (wWorker ^$ world) = Worker
        | otherwise = Empty

With this approach toChar can be just

toChar :: World -> Coord -> Char

toChar2 coords world = case cellContents coords world of
      Wall      -> '#'
      Worker    -> '@'
      Crate     -> 'o'
      Storage   -> '.'
      _ -> ' '

If you have already unpacked current world, you can use

let char = toChar2 coords world

If you don't have world you can just do

char <- toChar2 coord <$> get

The only place where you use toChar is printWorld, so it becomes simpler (no need for evalState):

let out = [[ toChar2 (x,y) w | x <- [0 .. maxX]] | y <- [0 .. maxY]]

setMaxCoords can be rewritten as:

setMaxCoords :: StateT World IO ()
setMaxCoords = do
    w <- get
    wMax .= maxCoords w

maxCoords = foldr (app2 max) (0, 0) . allCoords where
    allCoords w = (wWorker ^$ w) : concatMap (\x -> S.toList $ x ^$ w) [ wWalls, wCrates, wStorage ] where
    app2 f (x1, y1) (x2, y2) = (f x1 x2, f y1 y2)

move can be rewritten the same way as toChar2:

move dir w = move2 (cellContents newCoord w) (cellContents newCoord' w) where
    oldCoord = wWorker ^$ w
    newCoord = moveCoord dir oldCoord
    newCoord' = moveCoord dir newCoord

    move2 Wall _ = return ()
    move2 Crate Wall = return ()
    move2 Crate _ = do
        wWorker .= newCoord
        wCrates %= delete newCoord
        wCrates %= insert newCoord'
    move2 _ _ = wWorker .= newCoord

It should be used in the loop as get >>= move dir.


I like that your code (read functions) follows Single Responsibility Principle.
And also that you've put the number comparison code in a separate function unlike

User guesses the number generated by computer
Computer tries to guess your inputted number

And also that you use static_cast. All are good coding practices!

I'd prefer if you do the text printing in the placement function itself and call it something like compare_with_guess. That way, you don't have to return values and use another if-else block in the caller. Also, the output messages can also be controlled all at one place.
Another way is to use struct like:
struct InputNum{
private:
    const int input;
public:
    InputNum(const int num):input(num){};

    int get() const{
        return input;
    }
    bool greater_than(const int target) const {
        return input > target;
    }
    bool less_than(const int target) const {
        return input < target;
    }
    bool equals(const int target) const {
        return input == target;
    }
}

Use const whenever possible.
const int winning_num{ generateRandomNumber() };// +1 for {} initialiser syntax.

void compare_with_guess(const int input, const int guess){ // After making the changes I suggested above.

bool validateInput(const int input){

Avoid  using namespace std; completely, let alone using it multiple times in the code.
https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice


PRNG - Algorithm: Performance vs Readability

There is no one answer.

Performance

How often is generate_normal called? Is it called on a program critical path or only during set up?

Could you cache a bunch of numbers before hand and only replenish the cache when you run out?

Readability

How many people will read this code over its lifetime? How often will you have to come back to the code?

Compromise

If you notice a substantial penalty using the private const construct, then do the following:

/**The Multiplier. Suggested 1993 by Park and Miller.*/
private const MULTIPLIER:int = 48271; // folded into code below

/**The Modulus. Suggested 1988 by Stephen K. Park and Keith W. Miller.*/
private const MODULUS:int = 2147483647; // folded into code below

...

public function generate_normal(total:int):int
{
    // Values folded from definitions ...
    // _seed = (_seed * MULTIPLIER) % MODULUS;
    _seed = (_seed * 48271) % 2147483647;
    // return (_seed * total / MODULUS);
    return (_seed * total / 2147483647);
}


Two small comments:

Naming:
The convention for variable names in Java is camelCase. Your animationframe should instead be animationFrame when going by that rule. Similar for your animaxspeed. You don't have to save characters in your code, write it out: animationMaxSpeed.
anispeed can also be written out: animationSpeed. This should make your code even more clear than it is ;)

Braces:
It's also convention to place all if-blocks in braces, disregarding whether they have to, or not. This is to decrease the possibility of bugs when changing such blocks and forgetting braces.

if (animationFrame == 3) {
    animationFrame = 0;
}

Also the Java-Coding-Standard is 4 spaces indentation. It might be, that the markup for SE broke yours, but either way, your first if-statement is too far in.


Representation of the formula P(n) = (n!)(6^n)


So there are multiple things. First of all I'll share the code refactoring related suggestions and then we can look at the performance improvements of code.

Refactoring

You don't really need to pass a block to Array.new to initialize the array with nil values.

def initialize(capacity:, weight:)
  @capacity = capacity
  @weight   = weight
  @contents = Array.new(@capacity) { nil }
end

can be refactored to:

def initialize(capacity:, weight:)
  @capacity = capacity
  @weight   = weight
  @contents = Array.new(@capacity)
end

def contents=(new_contents)
  raise KnapsackCapacityExceededError if self.exceeds_capacity? new_contents
  raise KnapsackWeightExceededError   if self.exceeds_weight? new_contents
  raise KnapsackContentError          unless new_contents.all? { |e| e.is_a? Item }

  @contents = new_contents
end

can be refactored to:

def contents=(new_contents)
  raise KnapsackCapacityExceededError if exceeds_capacity? new_contents
  raise KnapsackWeightExceededError   if exceeds_weight? new_contents
  raise KnapsackContentError          if has_non_items? new_contents

  @contents = new_contents
end

def has_non_items?(contents)
  contents.any? { |content| !content.is_a?(Item) }
end

-> Notice that usage of self keyword has been removed.

-> Moved the logic of checking any non-items in contents to a separate method. That makes the if conditions more readable and it replaces the unless with if to make it consistent with rest of the conditions.
Method fit? can be refactored to:

def fit?(contents)
  fits_weight?(contents) && fits_capacity?(contents)
end

Method fits_weight? can be refactored as well.

def fits_weight?(contents)
  contents.map(&:weight).sum <= weight
end

Performance Tuning

You don't need to initialize the @contents array with nil elements. You can just write @contents = [] to save some extra used memory.


php script to retrieve enum values from sql table

You can use describe queries in mysql to find column types

for example DESCRIBE courses returns the table information including column type


Tween is not a very good name. How about Snowflake? And why is it a struct and exposing all of its implementation details. I would personally place it in a class, initialize its values via constructor, and give it a public function like fall() or something to update it each frame.

class Snowflake
{
public:
    void fall();
private:
    sf::CircleShape snowflake;
    float begin;
    float change;
    float time{ 0 };
    float duration;
    float current() const
    {
        return begin + change * easeInOutQuad(time / duration);
    }
};

By putting the circle in the class you can update it internally. More on all that later.

float easeInOutQuad(float normalisedTime)
{
  auto & t = normalisedTime;
  return t < 0.5 ? 2*t*t : 2*t*(2 - t) - 1;
}

It seems a little unusual to assign a reference to the argument and then return the reference. I'm actually a little surprised this didn't boom. it's a trivially copied float. Just pass it by value.

auto const inverseFramerate = 1.f / 60;
window.setFramerateLimit(static_cast<unsigned>(1 / inverseFramerate));

That is an odd way to write

window.setFramerateLimit(60);

Now you could replace the magic number 60 that I just passed here with a named constant but I would actually argue that this is one of those rare cases when you shouldn't. This will be the only call to this function and the name won't be more readable here. Most readers are likely to immediately recognize that the 60 is setting 60 fps.

No cast. No equation. easily readable. less lines.

auto const numberOfSnowflakes = 200;
Tween tweens[numberOfSnowflakes];
float yPositions[numberOfSnowflakes];

This is a much more useful named constant. However. Don't use C array[]s. std::array or std::vector are better C++ containers. std::array is static sized like the C-style array[] and std::vector is dynamically sized. Don't forget to #include whichever you choose to use. You should keep the constant but switch to the more preferred constexpr

constexpr int number_of_snowflakes = 200;

auto generator = std::mt19937{};

A lot of your difficult to read code revolves around your use and misuse of this object. Allow me to show you a slightly easier to use way of handling PRNG. I'd wrap it all into its own named function and do away with the two harder to read and use lambdas. Then inside the function you seed the generator and declare it static so it doesn't get destroyed when it goes out of scope.

//we take unsigned and return float in order to work with SFML's window size which is unsigned
float generateRandom(unsigned min, unsigned max)
{
    float real_min = static_cast<float>(min);
    float real_max = static_cast<float>(max);
    std::random_device rd;
    static const std::mt19937 generator(rd());
    std::uniform_real_distribution<float> distribution(real_min, real_max);

    return distribution(generator);
}

Now when you want a value between 0 - width you do

start = generateRandom(0, window.getSize().x)

This is a weird reimplementation of uniform_real_distribution. You did it so you could work with negative ranges because you want your snowflakes to start off-screen. But all you need is an offset applied after the fact.

auto randomBetween = [&generator](float min, float max)
{
    return std::generate_canonical<float, 10>(generator)*(max - min) + min;
};

Now we get to initialization. In the future it is best to declare and initialize variables together. If you need helper functions have them defined beforehand and ready to use rather than defining them in between instantiation and initialization.

for (auto i = 0; i < numberOfSnowflakes; ++i)
{
    tweens[i].begin = randomBetween(0, window.getSize().x);
    tweens[i].change = randomChangeInX();
    tweens[i].duration = randomBetween(1, 5);
    yPositions[i] = randomBetween(-20, window.getSize().y);
}
auto const defaultRadius = 5.f;
auto circle = sf::CircleShape{};

Most of this can be eliminated by doing two things. Move the sf::Circle into our new Snowflake class and we use default initialization within the class. You can also be completely rid of the second yPositions array as the Snowflake class circle can maintain its own position. You will have to pass the starting coordinates to the constructor because the Snowflake class won't have full access to the sf::RenderWindow class. Our class is now starting to look like this:

class Snowflake
{
public:
    explicit Snowflake(sf::Vector2f start_position);

    void fall();
private:
    float change{ generateRandom(1, 10) };
    float duration{ generateRandom(1, 5) };
    float time{ 0 };
    sf::Vector2f position;
    sf::CircleShape snowflake{ default_radius / duration };
    float current() const
    {
        return position.x + change * easeInOutQuad(time / duration);
    }
};

You can do the initialization like so:

std::vector<Snowflake> snowflakes;
snowflakes.reserve(number_of_snowflakes);
for (int i = 0; i < number_of_snowflakes; ++i)
{
    float x = generate_random(0, window.getSize().x);
    float y = generate_random(-20, window.getSize().y);
    sf::Vector2f start_position(x, y);
    snowflakes.emplace_back(Snow(start_position));
}

This will give you a nice standard container of snowflakes at default initialized

So now we get to your animation loop. I see now why you did inverseFramerate now, but it was a complicated way of having your snow fall at varying rates. As you have moved everything into the Snowflake class you can have a much simpler animation loop.

while (window.isOpen())
{
    sf::Event event;
    while (window.pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
        {
            window.close();
        }
    }

    for (auto&& snow : snowflakes)
    {
        snow.fall(window.getSize());
    }

    window.clear();
    for (auto&& snow : snowflakes)
    {
        snow.draw(window);
    }
    window.display();
}

All that leaves us with is implementing the fall() and draw() methods from above. draw() is simple and would look something like this:

void draw(sf::RenderWindow& window) { window.draw(snowflake); }

and the fall() method I just copied over your implementation details using my new class member variables. It looks something like this:

Put it all together and it would look like this:

#include <random>
#include <vector>

#include <SFML/Graphics.hpp>

constexpr int number_of_snowflakes = 200;
constexpr float single_frame = 1.F / 60;
constexpr float default_radius = 5.F;

// Maps input in the range [0..1] to an output in the range [0..1].
// Represents the piecewise function:
// y(x) = 2*x^2             when x < 0.5
//      = -2*x^2 + 4*t - 1  when x >= 0.5
float ease_in_and_out(float normalised_time)
{
    float t = normalised_time;
    return t < 0.5 ? 2 * t*t : 2 * t*(2 - t) - 1;
}

//we take unsigned and return float in order to work with SFML's window size which is unsigned
float generate_random(unsigned min, unsigned max)
{
    float real_min = static_cast<float>(min);
    float real_max = static_cast<float>(max);
    static std::random_device rd;
    static std::mt19937 generator(rd());
    std::uniform_real_distribution<float> distribution(real_min, real_max);

    return distribution(generator);
}

class Snowflake
{
public:
    explicit Snowflake(sf::Vector2f start_position) : position{ start_position }
    {
        snowflake.setPosition(position);
        begin = start_position.x;
    }

    void fall(sf::Vector2u window_size)
    {
        time += single_frame;
        if (time > duration)
        {
            begin += change;
            change = generate_random(1, 10);
            time = 0.F;
        }

        position.y = snowflake.getPosition().y;
        position.y += 1 / duration;
        if (position.y > window_size.y)
        {
            position.y = -10.F;
            begin = generate_random(0, window_size.x);
            change = generate_random(1, 10);
            time = 0;
            snowflake.setRadius(default_radius / duration);
        }

        position.x = shift_x();
        snowflake.setPosition(position);
    }
    void draw(sf::RenderWindow& window) { window.draw(snowflake); }
private:
    sf::Vector2f position;
    float begin;
    float change{ generate_random(1, 10) };
    float duration{ generate_random(1, 5) };
    float time{ 0 };
    sf::CircleShape snowflake{ default_radius / duration };

    float shift_x() const
    {
        return begin + change * ease_in_and_out(time / duration);
    }
};

int main()
{
    sf::RenderWindow window{ sf::VideoMode{500, 500}, "Snow" };
    window.setFramerateLimit(60);

    std::vector<Snowflake> snowflakes;
    snowflakes.reserve(number_of_snowflakes);
    for (int i = 0; i < number_of_snowflakes; ++i)
    {
        float x = generate_random(0, window.getSize().x);
        float y = generate_random(0, window.getSize().y) - 20.F;
        sf::Vector2f start_position(x, y);
        snowflakes.emplace_back(Snowflake(start_position));
    }

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
            {
                window.close();
            }
        }

        for (auto&& snow : snowflakes)
        {
            snow.fall(window.getSize());
        }

        window.clear();
        for (auto&& snow : snowflakes)
        {
            snow.draw(window);
        }
        window.display();
    }
}

Could this still be improved? Sure. I left a few magic numbers behind, and we all know those are bad. The names are more descriptive and better describe what is happening but they could probably be improved. SFML allows for classes to inherit from sf::Drawable and you can fix the syntax so it can be called window.draw(Snowflake); instead of passing a reference to the window object to your class. I would also probably extract the fall() method to a couple private helpers. This would

hide the implementation details of the public method that don't need to be exposed.
allow you to simplify some of the functionality. (There's a lot of resetting values to default.)


Models in a Simple PyMongo-based Blogging Web App without ORM/ODM

For the route I'd probably use fewer temporary variables, not that it
hurts a lot, but it can be more compact.  Additionally if Post
implemented some sort of dict-like update function it could be even
more compact, but that's splitting hairs.

@posts.route('/<_id>/edit', methods=['GET', 'POST'])
def edit(_id):
    post = Post()
    post.get(_id)
    if request.method == 'POST':
        post.title = request.form.get('title')
        post.tags = [tag.strip()
                     for tag in request.form.get('tags').split(',')]
        post.body = request.form.get('body')
        post.update()
    return render_template('posts_edit.html', post=post)

With the latter point I mean something like this (implemention left as
an exercise for the reader):

@posts.route('/<_id>/edit', methods=['GET', 'POST'])
def edit(_id):
    post = Post()
    post.get(_id)
    if request.method == 'POST':
        post.update({
            "title": request.form.get('title'),
            "tags": [tag.strip()
                    for tag in request.form.get('tags').split(',')]
            "body": request.form.get('body')
        })
    return render_template('posts_edit.html', post=post)

For the other file I'd suggest looking at the usual 80 character limit,
meaning wrapping the longer lines a bit.

In save the date and _id attributes of the object aren't being
used - that looks inconsistent, either self.date and self._id
should be updated too, or neither, right?  That should probably also
be documented clearly.
With get and the __init__ call, AFAIK that's probably safe, but
coming from any background where constructors are, well, that, this
looks fishy.  Consider making that a class method too:

@classmethod
def get(cls, _id):
    return cls(**mongo.db.posts.find_one({'_id': ObjectId(_id)}))

get_all doesn't use it's argument, so it's actually more of a
staticmethod right now.  If you're no going to use inheritance make
it one then.  If you are, possibly make move mongo.db.posts into a
class variable so that you could override it for subclasses and the
methods would keep on working with the correct tables.


The cascaded_union function can take more than one object, so you should be able to do:

from shapely.geometry import Polygon, MultiPolygon
from shapely.ops import cascaded_union

def get_region(vertices, triangles):
    regions = MultiPolygon([Polygon([vertices[i] for i in triangle])
                            for triangle in triangles])
    return list(cascaded_union(regions).exterior.coords)

When deleting triangle[72] from your example, which is not really a triangle and the reason for your try...except ValueError, this gives the same area for this function and yours, 1060307.0.

If you cannot delete those zero-size triangles manually, you can do it programmatically as well:

def get_region(vertices, triangles):
    polygons = (Polygon([vertices[i] for i in triangle])
                for triangle in triangles)
    regions = MultiPolygon([p for p in polygons if p.area > 0])
    return list(cascaded_union(regions).exterior.coords)

I would leave getting the points of the exterior to the caller, or another function, but I left it here in order to not change the interface.

Note that cascaded_union may be superseded by unary_union, depending on the version you are using.

I am not sure why you use the datastructure you have. It would be easier to directly store the vertices for each triangle as a three-tuple, so that you could just do:

def get_region(triangles):
    polygons = (Polygon(triangle) for triangle in triangles)
    regions = MultiPolygon([p for p in polygons if p.area > 0])
    return list(cascaded_union(regions).exterior.coords)


I like your approach with mapping function, but sorting alphabetically the collection of javafx.scene.paint.Color objects can be done a little bit easier:

    final String[] colors = {"AQUA", "LAWNGREEN", "LIGHTBLUE", "CYAN", "CHOCOLATE", "GREEN",
            "RED", "YELLOW", "GAINSBORO", "YELLOWGREEN"};

    Stream.of(colors).sorted().map(color -> Color.web(color)).forEach(System.out::println);

as you can see the algorithm quite simple:

Sort the string array
Map string to Color object using API method


An alternative

   protected function haversineGreatCircleDistance($latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 3959)
    {
        // convert from degrees to radians
        $latFrom = deg2rad($latitudeFrom);
        $lonFrom = deg2rad($longitudeFrom);
        $latTo = deg2rad($latitudeTo);
        $lonTo = deg2rad($longitudeTo);

You can simplify this if you only call it from the one place.

    protected function haversineGreatCircleDistance($from, $to, $earthRadius = 3959)
    {
        // convert from degrees to radians
        $latFrom = deg2rad($from['latitude']);
        $lonFrom = deg2rad($from['longitude']);
        $latTo = deg2rad($to['latitude']);
        $lonTo = deg2rad($to['longitude']);

Not a big deal, but this is shorter.

Avoid unnecessary variables

                $validInputZips[$zip]['hits'] = 0;

You create this purely to use for a single iteration in a later loop.  Why bother?  Create a variable in the loop and let it die after.  Or in this case, just take action in the loop and skip the variable altogether.  More on that later.

Don't do many times what you can do once

If you do

          $diameter = 2 * $radius;

before the nested loops, you only have to do the multiplication once.

Keep it simple

            foreach ($maskedInputZips as $maskedZip => $maskedLatlon) {

                if ($zip != $maskedZip) {
                    $miles = $this->haversineGreatCircleDistance($latlon['latitude'], $latlon['longitude'], $maskedLatlon['latitude'], $maskedLatlon['longitude'], 3959);

                    if ($miles < ($radius * 2)) {
                        $validInputZips[$zip]['hits'] += 1;
                    }
                }
            }
            if ($validInputZips[$zip]['hits'] == 0){
                $outputArray[] = $zip;
            }

You can simplify this as

            foreach ($maskedInputZips as $maskedZip => $maskedLatlon) {

                if ($zip != $maskedZip) {
                    $miles = $this->haversineGreatCircleDistance($latlon, $maskedLatlon);

                    if ($miles < $diameter) {
                        continue 2;
                    }
                }
            }

            $outputArray[] = $zip;

You don't need to increment the variable, as you never use it except to check for 0.  A simple Boolean is plenty.  This skips to the next iteration of the outer loop as soon as it finds the zip that makes it unqualified.  If that never happens, we add the zip to the output.

Careful about calling a function and explicitly entering the default value of a parameter.  When you do that, it can make it confusing as to which value matters.  The same value appears in two places, but only one matters.  What if someone changes the wrong one?


HttpRequest class using AsyncTask for Android application

By default AsyncTask tasks execute sirially on the default executor and you should at least override the execute to make sure that all requests are run in parallel unless specified otherwise
Apache HTTP library is considered deprecated in Android and you should try to at least use HttpUrlConnection if not a library that can make this happen with zero boilerplate code sych as Volley, OkHttp or Retrofit
Using Thread.sleep on the main thread is the best way you have to cause these warnings.
The system has about 16.8 milliseconds to draw anything on the screen and you just took away 10 of them for nothing while blocking the system from using the thread.
please use the given onPreExecute and onPostExecute to show progress activity to the user in any way you see fit and never EVER sleep on the main thread


your tab label seems to exist within the content which it is tabbing .. kinda bad, don't you think.
there is no point in using $(document).ready(), just put your script file right before </body> , and it will already be executing, when the DOM is done.
instead of adding function for each .tab tag's onclick separately, you should read about event delegation and use that
use closures for storing the active tab, instead of DOM. DOM manipulations are slow
setting top and bottom values in CSS fails to do what you want on IE7
animation quality on IE9 is horrid


Performance

Your problem report baffles me.  You say that you can successfully produce inputv.dat, a 2.6 GB file, in 45 minutes.  Yet, filtering inputv.dat to produce output_veloc_max.dat fails after 30 hours?  The only possible bottleneck is if num in linenum — and that would only be inefficient if the number of nodes is huge.  To make it work efficiently for a large number of nodes, you could use a set instead of a list:

linenum = set(x[1] for x in maxima)

Multiprocessing would not help you much, since the task is not very parallelizable.  It is possible to analyze WSPL.dat in parallel with the VELOC.dat→inputv.dat conversion, but producing output_veloc_max.dat must wait.  Since these data files are line-oriented, you cannot easily skip to arbitrary points within them, so you must process VELOC.dat sequentially.  The only significant optimization would be to avoid writing out inputv.dat as an intermediate result and reading it back in.

Style

Drop imports that you not using, like import time and import re.  Since you have tagged this question as python-3.x, you also don't need from __future__ import print_function.

The initialization of c as c=[] is garbage.  The real assignment is c=get_num(line).  The get_num function is weird, in that it gathers up all digits that appear on a line, returning 24 even if the text is "2 cool 4 me".

I'm not a fan of your maxima two-dimensional array.  By storing pairs in a list, you end up with code that is obfuscated by subscripts, like if value > maximum[0] and [x[1] for x in maxima].  Ideally, lists should be used for homogeneous data of variable length.  This pair would be better written as a tuple or a namedtuple.  But since you don't care about the values as soon as you have obtained the line numbers, you might as well make two separate variables max_samples and max_indices.

The way you parse VELOC.dat is odd.  You indiscriminately attempt to interpret the first column of every line as a float, then ignore the line if that fails.  I would guess, looking at your excerpt of VELOC.dat, that a better approach would be to look for a line containing "TS", then take the following c lines, where c is the number of nodes — the same strategy that you use when parsing WSPL.dat.

This program is large enough that it should be split into functions, so that each chunk of code has a name that reflects its purpose, and so that each function has its own local variables.

from itertools import count

def n_lines_after_ts(n, f):
    """
    Filter the file, extracting the next n lines after each occurrence of "TS".
    Each result is a triple consisting of:

    * A sequential sample number (counting up from 0)
    * The node number for that sample (cycling 0, 1, ..., n-1)
    * The line from the file
    """
    line_counter = count()
    for line in f:
        if line.startswith('TS'):
            for node in range(n):
                yield next(line_counter), node, next(f)

def num_nodes(wspl_dat):
    """
    Parse the file to extract the first number that appears after "ND".
    """
    for line in wspl_dat:
        if line.startswith('ND'):
            return int(line.partition('ND')[-1])

def wspl_max_indices(num_nodes, wspl_dat):
    """
    Find the indices of the maximum sample for each node.
    """
    max_samples = [float('-inf')] * num_nodes
    max_indices = [None] * num_nodes
    for line_num, node, sample in n_lines_after_ts(num_nodes, wspl_dat):
        sample = float(sample)
        if sample > max_samples[node]:
            max_samples[node] = sample
            max_indices[node] = line_num
    return max_indices

def extract_veloc(num_nodes, veloc_dat, indices):
    """
    Extract the specified indices from the velocity data.
    """
    set_of_indices = set(indices)
    lines = {
        line_num: sample
        for line_num, _, sample in n_lines_after_ts(num_nodes, veloc_dat)
        if line_num in set_of_indices
    }
    return (lines[i] for i in indices)

with open('WSPL.dat') as wspl_dat_file, \
     open('VELOC.dat') as veloc_dat_file, \
     open('output_veloc_max.dat', 'w') as out:
    num_nodes = num_nodes(wspl_dat_file)
    print('Anzahl der Knoten: {0}'.format(num_nodes))
    max_wspl_indices = wspl_max_indices(num_nodes, wspl_dat_file)
    out.write('VECTOR\nND    {0:2d}\nST  0\nTS      0.00\n'.format(num_nodes))
    out.writelines(extract_veloc(num_nodes, veloc_dat_file, max_wspl_indices))
print('Programm ist beendet.')


A heap-allocated texture class for a console renderer

getHeight and getWidth should be const.

int getWidth() const { return width; }
int getHeight() const { return height; }

Your destructor does not properly delete the pixels pointer.  Since you allocate it with new[] you need to use delete[].

delete [] pixels;

You're storing your textures in column-major order.  Depending on how you access them, this can cause performance issues with caching.  For example, in the constructor, when you copy in the initial texture values you jump thru memory (one byte every width bytes) rather than reading it sequentially (where x would be the inner loop).

Then there's the inevitable question of why you're using manual memory management, rather than using vector.


I would consider your whole proposal for this schema to be a code smell. In SQL, if there are many data to be treated alike, they should be stored in one column, rather than in multiple columns.  If you store your data using this proposed schema, any code that tries to use the schema is likely to be nasty too. (What's the average time interval between name changes? Good luck writing that query!) You would also have an arbitrary limit of 10 name changes per company, and accommodating more names would necessitate another schema change!

Therefore, it would make more sense to have a CompanyNameChange table, with (companyId, changeDate) as the primary key, and additional attributes previousName as an additional attribute.  If, for some reason, you do need the data to be presented in that proposed tabular format, you could always perform some joins.


Todo List Application Code in Pure JavaScript

Ok so, your code is overall looking nice, but a few changes could be made:

It's important to make sure you leave whitespace around your operators, like:

addRecordForm.style.display="none";
                           ^^

Could use whitespace around the operators.

I try not to suggest ternaries very often, but I believe that triggerAddRecordForm could be simplified with the use of one.

function triggerAddRecordForm() {
    if(addRecordFormVisibility === false) {
        addRecordForm.style.display="block";
        addRecordFormVisibility = true;
    } else {
        addRecordForm.style.display="none";
        addRecordFormVisibility = false;
    }
}

into:

function triggerAddRecordForm() {
    addRecordForm.style.display = addRecordFormVisiblity ? "none" : "block";
    addRecordFormVisibility = !addRecordFormVisibility;
}

On the subject of triggerAddRecordForm(), in general you shouldn't compare to false, then else it. You should leave the check empty (checks if the variable is true) like so:

if(addRecordFormVisibility) {
    doStuff();
} else {
    doOtherStuff();
}

In submit(), you could improve errors.innerHTML = ''.
Why don't you just set errors to document.getElementById('errors').innerHTML instead, seeing as you don't use errors other than for that?

In submit() you should also improve your line spacing as well, as it seems a little strange.


Another option is to iterate over the array of values using Array.reduce.  For me this makes its purpose more apparent.  Also it naturally handles a zero length array.

function encode(values) {
  return values.reduce(_computeDiff, {
    encoded: []
  }).encoded;
}

Here the initial accumulator value is a state value that contains the encoded output.  It will also be used to hold the lastValue.  The _computeDiff function can then update the state for each value.

function _computeDiff(state, value) {
  // lastValue initially undefined will produce diff NaN
  let diff = value - state.lastValue;

  // insert escape code for large differences
  if (Math.abs(diff) > 127) {
    state.encoded.push(-128);
  }

  state.encoded.push(isNaN(diff) ? value : diff);
  state.lastValue = value;
  return state;
}

This does rely on the fact that a math operation on an undefined value is NaN. Also it uses Math.abs to more succinctly describe the escape threshold.


Averaging a set of percentages between certain important levels

As @200_success pointed out in his comment, averaging percentages is a suspicious mathematical technique.

Each task in the TODO list could have its own weight, or relative value - a number that represents a chunk of progress towards "done"; then you can calculate a percentage by adding up the relative weights of all completed tasks (or more accurately, of a value derived from that task's %completed and weight), and dividing by the sum of the weights of all tasks.

I haven't played much with google-sheets, but I know excel pretty well; the formula you've come up with is exactly the kind of formula I'd have used in Excel 2003, before SUMIFS and COUNTIFS were introduced in Excel 2007.

When I enter a formula in a spreadsheet, I want to be able to copy that formula over to the next cell, without having to modify it. This involves a number of principles:

Don't hard-code cell references. In Excel I would have used names and/or tables - not sure google-sheets supports that, but in any case if none of that is supported you can still, and should, use absolute cell references - refer to 'To Do'!$A:$A and 'To Do'!$E:$E. Not sure what A3:A refers to.
Don't hard-code your variables. If each column is going to use a different set of [Priority] values, "<2000" and "<=1000" shouldn't be hard-coded. You can insert two rows above row 1, and put 1000 in row 1 and 2000 in row 2, so instead of "<2000" you'll have "<" & A$2, and instead of "<=1000" you'll have "<=" & A$1.

Lastly, I find

MAX(COUNTIF('To Do'!A3:A, "<2000") - COUNTIF('To Do'!A3:A, "<=1000"), 1)

is easier to read as

MAX(1, COUNTIF('To Do'!A3:A, "<2000") - COUNTIF('To Do'!A3:A, "<=1000"))

But the reason you're taking the MAX here, is to avoid a division by zero; by dividing by 1 whenever that's the case, you're showing mathematically incorrect results.

In Excel I'd wrap the division with an IFERROR, and return a string such as "-" when I'm dividing by zero. This accurately reports "this category is irrelevant", rather than "this category is 100% done".

Another simple option would be to add a column in the TODO list, to identify the actual priority level (which you currently have as a wasted row between each group); then a simple SUMIF / COUNTIF can do the trick: you only account for rows with a given [PriorityCode] value.

That's actually a "smell": your [Priority] values currently encode two values: the priority group, and the priority level, within that group.


Two maximal value in array. Sorted and Array.Sort()

for (int j = i + 1; j < arrOne.Length; j++) if (arrOne[minIndex] > arrOne[j]) minIndex = j;

This is by far the worst line in your code. It took me a while to realize that there is actually an if behind the for while I was wondering why didn't you indent the three lines below it but wait, these lines are not part of the for, it's the if. You should always use curly brackets

for (int j = i + 1; j < arrOne.Length; j++)
{
    if (arrOne[minIndex] > arrOne[j])
    {
        minIndex = j;
    }
}

This is how it should look like.


Finding all the subsets in an array of integers that sum to a given target

Violations of general good practices

Using String.substring to extract single characters is odd. Use String.charAt instead next time
Parsing single character strings using Integer.parseInt is odd. Use String.charAt(index) - '0' instead
allSubsets should be declared as Set instead of HashSet (use interface types instead of implementations)
Method names should be camelCase
No need to write JavaDoc for private methods, simple comments are good enough, if needed at all

Strange way to collect integers

The way you collect integers in a String is strange in many ways:

The program will not work for numbers > 9
Appending digits to a string one by one, and then finally parsing them from the string one by one is strange.

You could use a Set instead. Sure, maybe it seems a bit strange and inefficient to clone the set in each recursive call, but I still think it would be better. It would also solve the problem you found, with the duplicate sequences in the results.
Probably there is an even better way, but I have no more time now.

Strange static and non-static variables

allSubsets is static, but input and target are not.
It would make more sense to either make all of these static, or none of them.

Not suggested implementation

I can't say I suggest this implementation, but it solves some issues with yours:

private void find(int[] input, int target, Set<Integer> ramp, int index) {
    if (index > input.length - 1) {
        if (getSum(ramp) == target) {
            allSubsets.add(toString(ramp));
        }
        return;
    }

    find(input, target, updatedSet(ramp, input[index]), index + 1);
    find(input, target, ramp, index + 1);
}

private Set<Integer> updatedSet(Set<Integer> ramp, int integer) {
    Set<Integer> updated = new HashSet<Integer>();
    updated.addAll(ramp);
    updated.add(integer);
    return updated;
}

private String toString(Set<Integer> ramp) {
    StringBuilder builder = new StringBuilder();
    for (Integer integer : ramp) {
        builder.append(integer);
    }
    return builder.toString();
}

private static int getSum(Set<Integer> integers) {
    int sum = 0;
    for (Integer integer : integers) {
        sum += integer;
    }
    return sum;
}


Variables

The line containing the JDK_ROOT_DIR=( … ) definition is so long that it's unreadable and unmaintainable.  In fact, you listed /usr/j2se/ twice.  It would help to put one entry on each line.

The switch in naming in for sub_dir in "${JDK_ROOT_DIR[@]}" is confusing.  Each "root dir" is suddenly being called a "sub dir"?

Your export JAVA_HOME=$jdk_dir statements are pointless, since you immediately exit after setting the variable.  For that matter, the initial JAVA_HOME="" and JDK_TEMP="" assignments are also useless.

I know that you don't expect any whitespace or special characters in these directory names, but I would still make it a habit to double-quote variables according to best practice.

Globbing

Your three cases (for OpenJDK, IBM, and Raspbian) are nearly identical and could be handled by a nested loop.

You should also shopt -s nullglob to avoid unnecessarily doing the -d test on failed glob expansions.

Suggested solution

In addition, I think that failure to find the JDK directory should result in a non-zero exit code, and the error message should probably be printed to standard error rather than to standard output.

#!/bin/bash

shopt -s extglob nullglob

JDK_ROOT_DIRS=(
    /usr/java
    /usr/java/jdk
    /usr/j2se
    /usr/j2sdk
    /usr/jdk
    /usr/lib/java
    /usr/lib/j2se
    /usr/lib/j2sdk
    /usr/lib/jdk
    /usr/lib/jvm/java
    /usr/lib/jvm/j2se
    /usr/lib/jvm/j2sdk
    /usr/lib/jvm/jdk
    /usr/local/java
    /usr/local/java/jdk
    /usr/local/jdk
    /opt/java
    /opt/j2se
    /opt/j2sdk
    /opt/jdki
    /usr/lib/jvm
)
SUBDIR_GLOBS=(
    'java-*6*-openjdk*!(common)'            # OpenJDK
    'java-1_6_0-ibm-!(common)'              # IBM Java
    'jdk-8-oracle-arm32-!(common)'          # Raspbian Java
)

for root_dir in "${JDK_ROOT_DIRS[@]}" ; do
    for subdir_glob in "${SUBDIR_GLOBS[@]}" ; do
        for jdk_dir in "$root_dir"/$subdir_glob ; do
            if [ -d "$jdk_dir" ]; then
                echo "$jdk_dir"
                exit 0
            fi
        done
    done
done

echo "JDK directory not found." >&2
exit 1


The main improvement that can be made in the algorithm is recognizing that you can reduce more expensive sorting (and make the algorithm a lot easier to understand at a glance) by arranging the data into a structure indexed by the parent ID first. This operation is O(n). (In contrast, sorting is O(n log n)) The data structure will look like:

// This is not runnable, I'm just using a snippet to hide this long code
const itemsByParentId = {
  // Key: parent ID
  "1": [
    // Value: Array of children which have that ID as a parent (parentPK)
  {
    "id": 4,
    "parentPK": 1,
    "orderPos": "100",
    "children": []
  }, {
    "id": 2,
    "parentPK": 1,
    "orderPos": "51",
    "children": []
  }],
  "2": [{
    "id": 3,
    "parentPK": 2,
    "orderPos": "1",
    "children": []
  }, {
    "id": 5,
    "parentPK": 2,
    "orderPos": "10",
    "children": []
  }],
  "-1": [{
    "id": 1,
    "parentPK": -1,
    "orderPos": "1",
    "children": []
  }]
}

Then:

For each subarray (where all elements with the same parent are grouped together), sort it by orderPos (there's no getting around the O(n log n) complexity here)

Make a function that, given a parent, finds child elements in the data structure with that parent ID (O(1)), pushes them to the output array (O(n)), and recursively iterates over its children, depth-first, as the algorithm requires.

function sort(arr: data[]) {
  const itemsByParentId: {
    [id: number]: Array<data>;
  } = {};
  // (1) Group by parent ID
  for (const item of arr) {
    if (!itemsByParentId[item.parentPK]) {
      itemsByParentId[item.parentPK] = [];
    }
    itemsByParentId[item.parentPK].push(item);
  }
  // (2) Sort each subarray
  for (const childrenArr of Object.values(itemsByParentId)) {
    childrenArr.sort((a, b) => Number(a.orderPos) - Number(b.orderPos));
  }
  // (3) Recursively add parents and their children, depth-first
  const sorted: data[] = [];
  const addParent = (parent: data) => {
    sorted.push(parent);
    if (!itemsByParentId[parent.id]) {
      return;
    }
    for (const child of itemsByParentId[parent.id]) {
      parent.children.push(child);
      addParent(child)
    }
  };
  addParent(itemsByParentId[-1][0]);
  return sorted;
}

Live snippet of the compiled code:

function sort(arr) {
    const itemsByParentId = {};
    for (const item of arr) {
        if (!itemsByParentId[item.parentPK]) {
            itemsByParentId[item.parentPK] = [];
        }
        itemsByParentId[item.parentPK].push(item);
    }
    for (const childrenArr of Object.values(itemsByParentId)) {
        childrenArr.sort((a, b) => Number(a.orderPos) - Number(b.orderPos));
    }
    const sorted = [];
    const addParent = (parent) => {
        sorted.push(parent);
        if (!itemsByParentId[parent.id]) {
            return;
        }
        for (const child of itemsByParentId[parent.id]) {
                parent.children.push(child);
            addParent(child);
        }
    };
    addParent(itemsByParentId[-1][0]);
    return sorted;
}
let array = [{ id: 4, parentPK: 1, orderPos: '100', children: [] }, { id: 1, parentPK: -1, orderPos: '1', children: [] }, { id: 2, parentPK: 1, orderPos: '51', children: [] }, { id: 3, parentPK: 2, orderPos: '1', children: [] }, { id: 5, parentPK: 2, orderPos: '10', children: [] }];
let sortedArray = sort(array);

console.log('sorted array : ',sortedArray.map(element => [element.id, element.parentPK,element.orderPos] ))

For a review of your existing code:
Put each statement on its own line, usually - this significantly improves readability and means that readers of the code don't have to scroll horizontally.
Indent when starting a new block, and indent when chaining methods off an expression above - for similar reasons to above, it makes it a lot easier to pick up on the logic at a glance. (Also use the same indentation across the same block.) There are many IDEs which will automatically format your code to adhere to some sort of standard like this. They're well worth using.
parentPK? Currently, an object's parentPK value links to another object's id value. I'm not sure what these objects represent in your wider script, but you might consider if it would be clearer if the parentPK property was named parentID or idOfParent instead, to make the link clearer.
Declare variables close to where they'll be used, to reduce cognitive overhead. For example, rather than:
let parent;
let i = 1;
// many lines of code that doesn't reference i
while (i < arr.length - 1) {

you'll usually want to do
let parent;
// many lines of code that doesn't reference i
let i = 1;
while (i < arr.length - 1) {

You could also consider a for loop, since you increment i at the end:
for (let i = 1; i < arr.length - 1; i++) {

Use strict equality with === and !== - avoid != and ==, since they have strange coercion rules a reader of the script should not have to have memorized in order to understand the logic.
return does nothing in a forEach callback except terminate the current callback. It doesn't stop further callbacks from running. If you want to find the index of an element with a particular property in an array, use findIndex:
const rootIndex = arr.findIndex(item => item.parentPK === 1);
sorted.push(arr[rootIndex]);
arr.splice(rootIndex, 1);

Unnecessary comparison? I think parent will always exist, so the .filter(x => x.parentPK === (parent && parent.id)) check of parent first is superfluous. (If it might not exist, then you could simplify with optional chaining: x.parentPK === parent?.id)


The verbosity in your code actually come from a number of different sources.

Error handling

There is a lot of calls to .unwrap in your code.

This is because rust is a low-level language and thus you need to be able to predictably be able to handle all errors your code might run into. Traditionally this have been done using exceptions (as one might in c++) or error values (as in c), but since these often come with their own set of problems, rust have chosen to do it differently. This has the disadvantage of having slightly more verbosity (in some cases), but more often giving rise to the desired solution without bugs.

Your way of handling it by calling .unwrap on every Option or Result you encounter. This is not a particularly smart solution, as it will simply cause the thread to fail on error, but if that is your desired outcome, then I guess it is okay.

The typically used ways of handling these errors are as far as I know either to use the try! macro or pattern matching.

str/String

Again, since rust is a low-level language without forced garbage collection, it needs to keep track of where its values are actually placed and how they are freed. In this case, this is apparent because of your need to do .as_slice in a lot of places.

This is because rust has at least two different types of strings. The first is String, which is a wrapper around a growable heap-vector of bytes. If you have such a value, you own it and is responsible for freeing it.

The second is a &str, which is just a pointer into a string. A function cannot free or alter this string. This is the type of string that most libraries take as arguments (to prevent cloning values all the time).

The extra verbosity comes from the fact that you need to convert the first kind into the second kind. It might be an idea to do this coercion automatically, but I have not heard about this being in the pipeline.

Extra cloning

Finally you needed to add a few calls to .clone. In this case, you send the values to a thread, which would make it unavailable in the original thread.

This is because you cannot easily access the same value from multiple places at the same time as you can in ruby. This is again because rust is a low-level language without forced garbage collection with the need to control error handling and memory allocations.

There are multiple ways of handling this problem, but the easiest (though not necessarily the best) is to simply call .clone before sending the value to a different thread.

Conclusion

While it is possible to make improvements, most of the verbosity actually comes from rusts increased need for control, and this is not going away in the future.


I've written this in python2 because the question is posed in python2. It is advised that users switch over to python3, as it is reaching end-of-life at the end of 2019.

The algorithm

I don't see anything really glaring as far as the algorithm is concerned. The major edge case I can see is with lists/strings of length 1, but you handle that case fine

Pre-allocating your matrix

Without trying to use something like numpy, your pre-allocation step can be simplified a bit. You iterate twice over the whole list, once to fill it with zeros, and once over your respective ranges n and m. The n loop can be done with a simple slice assignment:

# use xrange for initialization here
# that way you aren't allocating a list into memory
L = [[0] * (n + 1) for i in xrange(m + 1)]

# Use a slice to assign the first row
# with a range, since that assigns a list to slice
L[0][:] = range(n + 1)

# then you only have one other for loop to do
# again, just use xrange here
for i in xrange(m + 1):
    L[i][0] = i

i and j

I'm not sure the following step really does anything and is necessary:

i = m
j = n

Furthermore, the while loop is more pythonic if you rely on the truthiness of nonzero integers:

while m and n:
    # do things

while loop

There are continuous index lookups. While lookups by index are fast, doing them over and over impairs readability, even if the penalty incurred is minor

while m and n:
     current, back_y, back_x, back_both = L[m][n], L[m][n-1], L[m-1][n], L[m-1][n-1]
     back = min(back_y, back_x, back_both)
     # rest of loop

Now you can use these as your placeholders for your if logic

while m and n:
    current, back_y, back_x, back_both = L[m][n], L[m][n-1], L[m-1][n], L[m-1][n-1]
    back = min(back_y, back_x, back_both)

    if back == back_both:
        if back == current:
            edits.append('NOOP')
        elif back == current - 1:
            edits.append('SUBST')
        m -= 1
        n -= 1

    elif back == back_y:
        edits.append('INSERT')
        n -= 1

    elif back == back_x:
        edits.append('DELETE')
        m -= 1

Timing

Looking at the timing differences between the two:

original

python -m timeit -s 'from otherfile import edit_distance, revised_edit; x = range(4); y = range(3,7)' 'edit_distance(x, y)'
10000 loops, best of 3: 29.3 usec per loop

revised

python -m timeit -s 'from otherfile import edit_distance, revised_edit; x = range(4); y = range(3,7)' 'revised_edit(x, y)'
100000 loops, best of 3: 10.1 usec per loop

A 65% speedup for small lists. Let's see about (relatively) larger ones

original

python -m timeit -s 'from otherfile import edit_distance, revised_edit; x = range(400); y = range(300,700)' 'edit_distance(x, y)'
10 loops, best of 3: 152 msec per loop

revised

python -m timeit -s 'from otherfile import edit_distance, revised_edit; x = range(400); y = range(300,700)' 'revised_edit(x, y)'
1000 loops, best of 3: 1.31 msec per loop

The difference is starting to diverge, two entire orders of magnitude here. Whether or not you would use this on large lists is I suppose an implementation detail, but worth a look. Not to imply that a 400 element list is big, but it's an improvement for sure.

The timing does not include the time required to reverse edits using a edits[::-1] because that is going to be a constant, and looking at slicing a 400 element list in this way, the time is insignificant compared to the rest of the algorithm (1000000 loops, best of 3: 0.967 usec per loop for range(400), if you were curious).

return edit

You never return edits! print does not return. It's also advisable to change print val to print(val), as the latter is portable across python 2 and 3, and it's recommended you be on python3 already anyways. So at the end of your function, be sure to include:

    return edits[::-1]


Fastest C++ code to get common prefix length

The C++ way would be to call std::mismatch and be done with it

#include <algorithm>    // mismatch
#include <cassert>      // assert
#include <cstddef>      // ptrdiff_t
#include <cstring>      // strlen
#include <iostream>     // cout
#include <iterator>     // distance

std::ptrdiff_t len_common_prefix_base(char const a[], char const b[])
{
    assert(std::strlen(b) <= std::strlen(a));
    return std::distance(b, std::mismatch(b, b + std::strlen(b), a).first);
}

If you absolutely have to improve on the base line performance, you can rewrite your second solution as two successive calls to std::mismatch. First, by reinterpreting the char* as long long int* and calling std::mismatch at the block level. Secondly, after finding the first char in the first mismatching block (which could be the final partial block containing the remaining chars) and doing another std::mismatch over the remaining chars.

std::ptrdiff_t len_common_prefix_10x(char const a[], char const b[])
{
    assert(std::strlen(b) <= std::strlen(a));
    using block_type = long long int;

    auto p = reinterpret_cast<block_type const*>(a);
    auto q = reinterpret_cast<block_type const*>(b);

    auto const n = std::strlen(b);
    auto const num_blocks = n / sizeof(block_type);

    auto block_mismatch = std::mismatch(q, q + num_blocks, p);
    auto b2 = reinterpret_cast<char const*>(block_mismatch.first);
    auto a2 = reinterpret_cast<char const*>(block_mismatch.second);

    return std::distance(b, std::mismatch(b2, b + n, a2).first);
}

int main()
{
    char const a[] = "hello world is a trivial exercise";
    char const b[] = "hello world is a trivial example";

    std::cout << len_common_prefix_base(a, b) << '\n';
    std::cout << len_common_prefix_10x(a, b) << '\n';
}

Live Example that prints 27 (the same as your two implementations).

What you are doing with your pointer cast to long int is very fragile, at the very least it's implementation-defined at possibly undefined behavior (for which no warning is required, and that includes the case that your code runs 10x faster on your system but crashes after you turn on compiler optimizations or port it to another system).

Some issues that you have to be very careful about when doing pointer casting:

alignment, if your char[] is part of a struct, you need to be sure it is aligned at 8-byte boundaries to avoid unaligned memory access from your long long int pointers.
endianness, you need to make sure that the bytes within a long long int are in the same order as the char[] array

I'd like to see a reproducible benchmark before being able to comment on whether a 10x improvement is really possible on std::mismatch.


There are several problems with this code, starting from the fact that it is syntactically invalid. Getting past that, you have no access to your data, which makes it somewhat pointless, and the only way to construct a MessageEntry is to preconstruct a T, then copy it into the MessageEntry constructor, then copy it again into data. That can be unnecessarily expensive, and then you're not actually timestamping when you constructed the original object - you're timestamping two copies later.

You definitely want to be able to support in-place construction and you definitely want easy access to the data. Fortunately, you can solve both problems in one go with just simple inheritance:

template <typename T, typename Clock=std::chrono::system_clock>
struct MessageEntry : T
{
    using T::T;
    decltype(Clock::now()) creation_time = Clock::now();
};

That's... it. I added a second template argument in case your users want a different clock (e.g. std::chrono::steady_clock). I intentionally left creation_time non-const so as to make the class copyable. If you don't need this to be copyable, then I would write it as:

template <typename T, typename Clock=std::chrono::system_clock>
struct MessageEntry : T
{
    using T::T;
    const decltype(Clock::now()) creation_time = Clock::now();

    MessageEntry(MessageEntry const& ) = delete;
    MessageEntry& operator=(MessageEntry const& ) = delete;
};

It might be worth renaming the class to something that adds clarity to its intent. Perhaps WithCreationTime.

Lastly, I would prefer #pragma once just to be able to write less code for include guards, and you are missing your #include for <chrono>.

Full solution:

#pragma once

#include <chrono>

template <typename T,
          typename Clock = std::chrono::system_clock>
struct WithCreationTime : T
{
    using T::T;
    decltype(Clock::now()) creation_time = Clock::now();
};

Example usage:

WithCreationTime<std::vector<int>> v{1, 2, 3, 4};
std::cout << v.size() << '\n'; // 4
std::cout << v.creation_time << '\n'; // whatever now() is


Security

Curl Set POST

I don't think that there is a problem with passing user input to curl_setopt as post field (something like http header splitting is not possible, and it doesn't even seem possibly to add additional post fields, or to overwrite existing ones).

Important information via GET

It's not a good idea to send anything confidential via GET. GET requests can be cached, they can be stored in the browser history, they show up in server logs, and so on. Use POST instead.

SQL injection

$accountInfo isn't controlled by you, so you shouldn't trust it, the same probably goes for $data. Never put variable data directly into an SQL query, use prepared statements instead.

CURLOPT_SSL_VERIFYPEER

If you disable this setting, you weaken the security of SSL. Yes, you still encrypt even if CURLOPT_SSL_VERIFYPEER is false, but you would also accept the key of a man in the middle instead of the key from the server, so an attacker could still read the communication.

Here is the warning from the documentation:

  WARNING: disabling verification of the certificate allows bad guys to
  man-in-the-middle the communication without you knowing it. Disabling
  verification makes the communication insecure. Just having encryption
  on a transfer is not enough as you cannot be sure that you are
  communicating with the correct end-point.


php function for gathering includes...is there a better way than this?

Don't make your directory structure so vague. Coming into this with no knowledge of your system how am I supposed to know what the "i" directory is? Just call it includes. Also, it is usually a good idea to separate your files based on their types so that they are easier to find. There are many common project directory structures out there. For instance I'm using something similar to Zend's. It looks similar to this.

/root
    /application
        /configs
        /models
        /views
        /controllers
    /data
        /cache
        /logs
    /public
        /js
        /css
        /images

I hope those file names don't indicate that you are actually using globals... There are much better ways to get "global" scope variables without ever using global. Sessions for instance. Globals, in my opinion, should eventually be deprecated. They are an old feature that has been proven faulty and replaced.

array_push() is another old function. Though there is nothing wrong with it, the preferred way to do it now is like so.

$includes[] = $file;

What you are trying to do is usually done with templates rather than PHP. For instance, you'd have a single HTML file with these includes in it already then dynamically change the contents with PHP. For those files that use the $topic variable, you would just perform a check to make sure it exists before including it via PHP. So a very basic template might look like this.

<html>
<head>
<title></title>
<script type="text/javascript" src="i/globals.js"></script>
<link rel="stylesheet" type="text/css" href="i/globals.css" />

<!-- SPECIFIC INCLUDES -->

<?php if( is_file( "i/$topic.js" ) : ?>
<script type="text/javascript" src="i/<?php echo $topic.js; ?>"></script>
<?php endif; ?>

<?php if( is_file( "i/$topic.css" ) : ?>
<link rel="stylesheet" type="text/css" href="i/<?php echo $topic.css; ?>" />
<?php endif; ?>

<!-- SPECIFIC INCLUDES -->

</head>
<body>
<?php if( is_file( "i/$topic.php" ) ) { include "i/$topic.php"; } ?>
</body>
</html>


I am not sure there is a way to reduce the number of if-statements and nesting. What is possible though is to improve the performance of the conditions you have that check those conditions.

The count(*) is inefficient. Consider adding a 'ROWNUM = 1' condition to your where clause in a way that makes the following conditions possible:

        SELECT COUNT(REQ_ID) INTO requestFound
        FROM FIRSTTABLE
        WHERE FIRSTTABLE.REQ_ID = REQUESTID
          AND (REQ_STATUS = 'D' OR REQ_STATUS = 'A')
          AND ROWNUM = 1;

This will be optimized by Oracle to exit the condition on the first matching result, ending up with a requestFound value that will be either 0, or 1. A value of 1 means there is some data, and does not indicate how much data.

Reading up on ROWNUM is useful. Ask Tom!


Admin method in CakePHP to add a venue to the database

Why do you have the following lines repeating:

    if ($this->Venue->save($this->request->data)) {
        if ($this->Venue->save($this->request->data)) {

I think you may try to merge them to one and the associated logic too.


Well, Rubberduck only indicates one issue.

  Rubberduck Code Inspections - 3/8/2015 12:56:11 PM
  1 issue found.
  Suggestion: Member 'CIV_draw' is implicitly Public - VBAProject.Module1, line 3

Implicit Public Member documentation

So, you're off to a good start. You can correct this by explicitly declaring the Subroutine's scope.

Public Sub CIV_draw()

Personally, I would also ditch the prefix and just call this routine Draw(). The underscore holds a special place in VBA. It typically denotes either an Event procedure or an Interface implementation, so I would avoid using underscores in procedure names elsewhere.

The next thing I notice is that you're calling the Range() and Cells() methods without specifying a worksheet. This means you're implicitly calling these methods on the ActiveSheet. This should be avoided because it leaves a small chance that the user will change the worksheet while the code is executing. You should instead create a worksheet variable that gets set at the very beginning, then work with that instead.

Dim ws As Worksheet
Set ws = ThisWorkbook.ActiveSheet

ws.Range("K2:M50").ClearContents
' ...

There are also a lot of magic numbers in your code, but I'll get back to that. First, let's talk about extracting some well named methods. The random number logic is a good one to extract out. When reading this method, we don't care really how the random number is generated, only that we are getting one.

RandNum = CInt(Int(43 * Rnd())) + 1

Private Function GetRandomNum() As Integer
    GetRandomNum = CInt(Int(43 * Rnd())) + 1
End Function

Next is the business of getting a random civilization string.

Private Function GetRandomCivilization(ByVal RandNum As Integer, ByVal ws As Worksheet) As String
    GetRandomCivilization = ws.Cells(RandNum, 16).Value & " (" & ws.Cells(RandNum, 15).Value & ")"
End Function

This is already making your code more readable at a high level. If anyone wants the details, they can dig into these private functions. We've also entirely eliminated a variable by doing this.

Dim RandCivilization As String
Dim checkVal As Boolean

checkVal = False
While checkVal = False
    RandCivilization = GetRandomCivilization(GetRandomNum(), ws)
    For Z = 1 To 50

Next let's clean up your While loop a bit.

Dim checkVal As Boolean

checkVal = False
While checkVal = False

Next, let's flip the logic to use a Not condition.

Dim checkVal As Boolean
checkVal = False

While Not checkVal

And finally, give it a better name.

Dim endOfRange As Boolean
endOfRange = False

While Not endOfRange

The next order of business is to extract this duplicated logic into its own method.

(ws.Cells(3, 7).Value + 2)

Private Function GetNumberOfCivilizations(ByVal ws As Worksheet)
    GetNumberOfCivilizations = ws.Cells(3, 7).Value
End Function

Which brings the current state of the code to this.

Public Sub Draw()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.ActiveSheet

    ws.Range("K2:M50").ClearContents

    Dim x As Integer
    x = ws.Cells(3, 3).Value

    Dim numberOfCivs As Integer
    numberOfCivs = GetNumberOfCivilizations()

    Dim i As Long
    For i = 1 To x
        ws.Cells(3 + (numberOfCivs + 2) * (i - 1), 11).Value = "Player " & i

        Dim j As Long
        For j = 1 To numberOfCivs
            Dim RandCivilization As String
            Dim endOfRange As Boolean

            endOfRange = False
            While Not endOfRange
                RandCivilization = GetRandomCivilization(GetRandomNum(), ws)

                Dim z As Long
                For z = 1 To 50
                    If ws.Cells(z, 12) = RandCivilization Then
                        Exit For
                    End If
                    If z = 50 Then
                        endOfRange = True
                    End If
                Next z
            Wend

            ws.Cells((numberOfCivs + 2) * (i - 1) + (j + 3), 12).Value = RandCivilization
        Next j
    Next i
End Sub

Private Function GetNumberOfCivilizations(ByVal ws As Worksheet)
    GetNumberOfCivilizations = ws.Cells(3, 7).Value
End Function

Private Function GetRandomNum() As Integer
    GetRandomNum = CInt(Int(43 * Rnd())) + 1
End Function

Private Function GetRandomCivilization(ByVal RandNum As Integer, ByVal ws As Worksheet) As String
    GetRandomCivilization = ws.Cells(RandNum, 16).Value & " (" & ws.Cells(RandNum, 15).Value & ")"
End Function

That's an improvement, but we're still dealing with a lot of numbers that don't mean much to us until we reference back to the actual worksheet. Let's define constant values for them and some functions that are responsible for getting data from the worksheet.

Private Function GetNumberOfPlayers(ByVal ws As Worksheet) As Integer
    GetNumberOfPlayers = ws.Cells(3, 3).Value
End Function

And yet another function to get the range we're writing the results to.

Private Function GetResultsRange(ByVal ws As Worksheet) As Range
    Set GetResultsRange = ws.Range("K2:M50")
End Function

Now, note that we're referencing the column positions within the results range, instead of the position relative to the worksheet. This is easier for a person to comprehend while only looking at the code.

Public Sub Draw()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.ActiveSheet

    Dim resultsRange As Range
    Set resultsRange = GetResultsRange(ws)
    resultsRange.ClearContents

    Dim numOfPlayers As Integer
    numberOfPlayers = GetNumberOfPlayers()

    Dim numberOfCivs As Integer
    numberOfCivs = GetNumberOfCivilizations()

    Dim i As Long
    For i = 1 To numberOfPlayers
        resultsRange.Cells(3 + (numberOfCivs + 2) * (i - 1), 1).Value = "Player " & i

        Dim j As Long
        For j = 1 To numberOfCivs
            Dim RandCivilization As String
            Dim endOfRange As Boolean

            endOfRange = False
            While Not endOfRange
                RandCivilization = GetRandomCivilization(GetRandomNum(), ws)

                Dim z As Long
                For z = 1 To resultsRange.Rows.Count
                    If resultsRange.Cells(z, 2) = RandCivilization Then
                        Exit For
                    End If
                    If z = resultsRange.Rows.Count Then
                        endOfRange = True
                    End If
                Next z
            Wend

            resultsRange.Cells((numberOfCivs + 2) * (i - 1) + (j + 3), 2).Value = RandCivilization
        Next j
    Next i
End Sub

At this point, you should be getting the idea. Keep extracting well named functions until there's no duplicated or obscure logic left in your main routine. This snippet would be my next target.

(numberOfCivs + 2) * (i - 1)

As well as a couple of subs that are responsible for writing the data into the results range.

The code as it was in my IDE when I stopped reviewing:

Option Explicit

Public Sub Draw()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.ActiveSheet

    Dim resultsRange As Range
    Set resultsRange = GetResultsRange(ws)
    resultsRange.ClearContents

    Dim numOfPlayers As Integer
    numberOfPlayers = GetNumberOfPlayers()

    Dim numberOfCivs As Integer
    numberOfCivs = GetNumberOfCivilizations()

    Dim i As Long
    For i = 1 To numberOfPlayers
        resultsRange.Cells(3 + (numberOfCivs + 2) * (i - 1), 1).Value = "Player " & i

        Dim j As Long
        For j = 1 To numberOfCivs
            Dim RandCivilization As String
            Dim endOfRange As Boolean

            endOfRange = False
            While Not endOfRange
                RandCivilization = GetRandomCivilization(GetRandomNum(), ws)

                Dim z As Long
                For z = 1 To resultsRange.Rows.Count
                    If resultsRange.Cells(z, 2) = RandCivilization Then
                        Exit For
                    End If
                    If z = resultsRange.Rows.Count Then
                        endOfRange = True
                    End If
                Next z
            Wend

            resultsRange.Cells((numberOfCivs + 2) * (i - 1) + (j + 3), 2).Value = RandCivilization
        Next j
    Next i
End Sub

Private Function GetNumberOfCivilizations(ByVal ws As Worksheet)
    GetNumberOfCivilizations = ws.Cells(3, 7).Value
End Function

Private Function GetRandomNum() As Integer
    GetRandomNum = CInt(Int(43 * Rnd())) + 1
End Function

Private Function GetRandomCivilization(ByVal RandNum As Integer, ByVal ws As Worksheet) As String
    GetRandomCivilization = ws.Cells(RandNum, 16).Value & " (" & ws.Cells(RandNum, 15).Value & ")"
End Function

Private Function GetNumberOfPlayers(ByVal ws As Worksheet) As Integer
    GetNumberOfPlayers = ws.Cells(3, 3).Value
End Function

Private Function GetResultsRange(ByVal ws As Worksheet) As Range
    Set GetResultsRange = ws.Range("K2:M50")
End Function


Total number of stops for an elevator to serve certain people

First of all I'd like to suggest you use a for-loop, since it would be easier to see, that you're going to increment the loop variable in every iteration independent of any conditions. Then you could also exchange your idx variable for i since the first does not convey more or less semantics than the second and it is somewhat unwritten convention.

Next: Why use a static_cast<int>for incrementing the stop_count? I think you would not need that, if you defined stop_count as a size_t.

Also: Was there some sort of requirement that solution() takes N as an argument? You could get rid of that parameter, since you have the weight-vector, which in turn has a size().

Furthermore: What is the parameter M (number_of_floors) going to be used for? I do not see much use for it other than boundary checking in the program, in a real world scenario no one could press button 10 in a 5-story building anyway.


I have some bad news for you... According to MSDN only one thread can enter an upgradeable read lock:

  Only one thread can enter upgradeable mode at any given time. If a thread is in upgradeable mode, and there are no threads waiting to enter write mode, any number of other threads can enter read mode, even if there are threads waiting to enter upgradeable mode.

That means your current implementation is basically just exclusive locking.

You should validate your parameters:

public Snoozy(Func<T> valueFactory)
{
    if (valueFactory == null)
    {
        throw new ArgumentNullException(nameof(valueFactory));
    }

and likewise in your conversions.

On the whole, this feels like a cached value to me - there are probably existing constructs which would suit your needs better depending on what framework/type of app you're building. Rolling your own cache is hard.
Remember, there are only 2 hard problems in programming: naming, cache invalidation and off by one errors.


set public $routes to private or protected if its jsut an internal resource of this class. Just use public if other classes/code explicitly should call the mothod/property
method_exists doesn't check if the method is callable. But that might be important if you execute legacy code
Avoid echo 'some text' Better use exceptions and an exception handler
If you use if (){} else{} you could think about using the if for the termination condition and the function continues regulary if its ok
Your note about the dependency injection cache is good. Keep your idea. You are on the rigth way.
I would recommend to use doc-blocks as annotation and for IDE autocompletion for all public functions as well as class properties. This will increase the readability
You didn't said which version of PHP you are using. Switch to >= 7.1 because 7.0 will reach its end of life soon. So you should use return types and type hinting


Interesting question:

As per @jfriend00, using a promise is odd there. Your repaint might work out, but in essence JS runs .reduce() single threaded, there really is not a lot of value there
Your Session is not immutable, it keeps updating the changes list
All your methods are static, I would have expected an "Immutable" class with session as in instance of the Immutable class
I would inside your class indeed maintain a mutable object that is up to date ( so a call to update would result in an update of both changes and say an object called state ) Since your class is mutable by having changes, you might as well go all the way.
I like mutable.js, in that there is no such thing as getState(), you would get the new state from calling update. This way you can update the data and have the state in 1 line.

All in all, even after reading the whole immutable.js page, I don't see the point. If truly your goal is to have A performant data store that will behave predictably., then a plain old Vanilla Object should do.