Personally I try to keep the view models as close to DTO's as possible.  That way you can have any number of objects populating the data from any number of sources.  And, as you mentioned, it helps keep them lean and free of domain logic.

If there was only one particular method of doing the transformation I might look at existing mapping solutions i.e. AutoMapper.  Alternatively as you suggested I might create a separate builder class that was responsible for doing the building.

The main problem I have with doing it your way (apart from those mentioned by Larry already) is that it tightly couples the ViewModel with your model.  Re-using the viewModel in different contexts becomes harder.

Also, if you were to to TDD, I might find it a bit strange writing a test like:

public void TestMyViewModel()
{
   try
   {
      // Act
      var viewModel = QuizPreviewViewModel(1);

      // nothing to arrange???

      // Assert
      Assert.AreEqual(1, viewModel.QuizId);
   }
   catch(Exception ex)
   {
      Assert.Fail();
   }
}

I think I would prefer something like:

public class QuizPreviewViewModelBuilder
{
    private readonly IQuizServiceWrapper _service;

    public QuizPreviewViewModel(IQuizServiceWrapper service)
    {
        _service = service;
    }

    public QuizPreviewViewModel GetViewModel(int quizId)
    {
        var viewModel = new QuizPreviewViewModel();
        var quiz = _service.GetQuizHeader(quizId);

        viewModel.QuizId = quizId;
        viewModel.QuizName = quiz.QuizName;
        viewModel.QuizQuestions = quiz.questions;

        return viewModel;
    }
}

then your test class would look like:

public void TestMyViewModelBuilder()
{
      // Act
      var mockService = // new mock service however this works
      var builder = QuizPreviewViewModelBuilder(mockService);

      // arrange
      var viewModel = builder.GetViewModel(1);

      // Assert
      Assert.AreEqual(1, viewModel.QuizId);
}

Even this has a potential downside I guess in the fact that you have to have a bit of knowledge as to how to build up the service in order for the GetViewModel to work, so I'm not completely sold on that idea.

Although this really just moves the logic of the building from the controller to another class I think it better allows for re-useability of the ViewModel while also providing a DRY approach to doing the actual building.

Just a couple of different thoughts for you to mull over.


Exporting HTML table data to Excel using C#

First off let's encapsulate what you are trying to do here.

Create a function that will format the DataTable.

private static DataTable FormatMovieReportTable(DataTable reportTable)
{
    foreach(DataColumn column in reportTable.Columns)
    {
        string colName = column.ColumnName;
        if(colName != "Movie Code")
        {
            foreach(DataRow row in reportTable.Rows)
            {
                string value = row[colName]
                if(value.Contains("%"))
                {
                    value = value.Replace("%", "");
                    if(value.Contains("."))
                    {
                        double number = 0.0;
                        double.TryParse(value, out number);
                        value = (number / 100).ToString("0.00##")
                    }
                    row[colName] = value;
                }
            }
        }
    }
    return reportTable;
}

Now create a function that will create the DataTable from the string values.

private DataTable JsonToTable<T>(string data, string html, string tableName)
{
    DataTable output = null;
    IEnumerable<T> serializedData = data.JsonDeserialize<T>().AsEnumerable<T>();
    List<SelectListItem> colOrder = ParseColumnsToList(html);
    output = serializedData.ToDataTable<T>(colOrder);
    if(output!= null)
    {
        output = FormatMovieReportTable(output);
        output.TableName = tableName;
    }
    return output
}

And now the excel output..

private void TableToExcel(DataTable table)
{
    ExcelPackage epackage = new ExcelPackage();
    // the ?? is just in case that the table name is null
    // "new sheet" is just some arbitrary default name
    ExcelWorksheet excel = epackage.Workbook.Worksheets.Add(table.TableName ?? "new sheet");
    excel.Cells["A1"].LoadFromDataTable(table, true);
}

From wherever you called the posted function you can separate the logic

private void ThisIsTheCallerMethod()
{
    string data, html, reportName;

    // Other things happen and variables are populated

    DataTable reportTable = JsonToTable<SomeType>(data, html, reportName);
    if(reportTable != null)
    {
        TableToExcel(reportTable);
    }

    // Create the MemoryStream, etc...
}


Low level programming is as much about optimization as it is legibility.
As you've noted, yours works, but I'd like to inject a few of my personal preferences here.

_start:

    ; Grab a buffer from stack suitably large enough to convert a 64 bit number

        push    rbp
        mov     rpb, rsp
        sub     rsp, 64                 ; Always keep RSP at least DWORD aligned

I prefer to keep functions distinct. Even though encorporating print into the conversion function
is doable, but maybe this conversion code could be used somewhere that printing isn't required.

        mov     esi, Value              ; Establish pointer to 16 bit value
        mov     rdi, rbp                ; Point to end of ASCII buffer
        call    Bin2Asc                 ; Return a pointer in RSI and characters in RDX

To accomodate SYSCALLs, have the function return values in register(s) that will be required.

        mov     eax, SYS_WRITE
        syscall

        leave                           ; Kill procedure frame
        xor     eax, eax
        mov     edi, eax
        mov      cl, SYS_EXIT
        syscall

NOTE: A lot of times I'm using 32 bit registers and that is because I'm taking advantage of
processors sign extension mechanism, where some instruction sign extend into 64 bits.

Bin2Asc:

        xor     eax, eax                ; Clear accum
        mov     edx, eax                ; EDX is what SYS_WRITE is going to need
        lodsw
        std                             ; Change direction so buffer is populated in reverse

  .L0:  push    rax
        and      al, 1                  ; Isolate bit
        xor      al, '0'                ; Convert to "0" or "1"
        stosb                           ; Write to buffer
        inc      dl                     ; Bump character cound
        pop     rax
        shr     eax, 1                  ; Until RAX = 0
        jnz     .L0

        cld                             ; Reset direction flag
        inc     edi                     ; Point back to first character
        ret

Might this code have ERRORS, it may very well have, but as I'm not doing it on a Linux box and
I usually like to check my work, but it does demonstrate a concept that is optimized at least a bit.


Simple class, solely for setting "globals"

If these are constants, use const, not static:

class VERS {
    const css = '_214';
    const js = '_167';
    const image = '_56';
    const other = '_19';
}

and then

echo .....VERS::css....

As to whether this is a good idea in general, it would be helpful to show a bigger picture: what the rest of config looks like? how it's used? etc.


import random should be at the top of the script.

The call to main should be guarded by if __name__ == "__main__":.

the_number and guess are already int, so the repeated calls to e.g. int(the_number) are redundant.

Docstrings should be formatted properly, as multi-line strings """ """ not comments #. Many of the actual comments are redundant - it's generally obvious what's going on (well done!)

The step argument to ask_number doesn't make much sense, and there's no error handling for non-numeric inputs.

The "magic numbers" 1 and 100 should be factored out.

Use str.format for combining strings with other objects.

Think about your logic more carefully - if guess isn't equal to or greater than the_number it must be less, you can just use else.

100 isn't in range(1, 100).

I would write it as:

import random

def main(low=1, high=100):
    """Guess My Number

    The computer picks a random number between low and high
    The player tries to guess it and the computer lets
    the player know if the guess is too high, too low
    or right on the money

    """
    print("Welcome to 'Guess My Number'!")
    print("I'm thinking of a number between {} and {}.".format(low, high))
    print("Try to guess it in as few attempts as possible.")

    the_number = random.randint(low, high)
    tries = 0

    while True:
        guess = ask_number("Enter your guess:", low, high)
        if guess == the_number:
            print("You're right on the money!")
            break
        elif guess > the_number:
            print("Too high!")
        else:
            print("Too low!")
        tries += 1

    print("You guessed it! The number was {}.".format(the_number))
    print("And it only took you {} tries!".format(tries))
    input("Press the enter key to exit.")

def ask_number(question, low, high):
    """Get the user to input a number in the appropriate range."""
    while True:
        try:
            response = int(input(question))
        except ValueError:
            print "Not an integer"
        else:
            if response in range(low, high+1):
                return response
            print "Out of range"

if __name__ == "__main__":
    main()

To play again, you could recursively call main, or have a loop at the end of the script:

if __name__ == "__main__":
    while True:
        main()
        again = input("Play again (y/n)? ").lower()
        if again not in {"y", "yes"}:
            break


A library for interacting with JPL Horizons

Use Requests
urllib is kind of a pain to use. Use Requests instead. Among other things, all of this code:
    for key in self.keys:
        request += "&" + key + "='" + self.keys[key] + "'"

will go away. Requests has query string formatting from a dictionary.
Julian conversion
It's doubtful that you need to be doing this yourself. Find a library such as https://pypi.org/project/julian/ .
Combined-inequality syntax
date.year < 1801 or date.year > 2099

should be
not (1800 < date.year < 2100)

Squaring
math.pow(60,2)

should just be
60**2

Late serialization
I would recommend that HorizonsRequest.keys (which, by the way, is not only a collection of keys - it's a dictionary, so it's misnamed) not be constructed until it's needed in send. Nor should you expose arbitrary set_key / delete_key. In theory you should understand enough about the request format that information to create it is stored in more strongly-typed variables that can receive better validation. For instance, do not store
"OBJ_DATA": "NO",

as a class member; instead store
obj_data: bool = False


Code to replace list of integers with nearest bigger element

As I already mentioned in a comment there's a bug in your replace2:
 input list 3,1,2,4 should result in 4,2,4,4 instead of all 4's since the 2 is the first bigger number on the right of number 1

Going for a List just for debugging seems odd to me. If you want to print a list to console you can use Arrays.toString(myArray) which looks exactly the same as myList.toString(). If you use a decent IDE you should be able to see the values clearly as well at a breakpoint. (I use IntelliJ and I know there are other IDE's that do this as well). In this case I would stick to using an array.

Since I currently only have java 8 installed for work I had a little trouble porting your program to java 8 to test it. The List.of() isn't available yet and any workaround to quickly initialise an explicit ArrayList gave me trouble. I instead changed all your ArrayList types to the more general List and it works. There's no reason to limit your method to ArrayList only.
Generally it's better to code using the interface instead of an explicit implementation. If at some point you would want to use a LinkedList instead of an ArrayList for example you can't use your current method.

Idea for a correct solution:
Loop through the list from right to left. Store the relevant larger numbers in a stack. At each step of the loop update the stack to only contain relevant larger numbers and replace the current element with the first (= smallest) larger element.

More concretely (try yourself first, use this if you're still stuck):

public static void replaceStack(int[] input) {
    if (input.length < 2) {
        return; //empty or 1 element list are trivial
    }
    Deque<Integer> largerKnown = new LinkedList<>(); //Java Stack implementation
    largerKnown.add(input[input.length - 1]); //last element is never replaced
    for (int i = input.length - 2; i >= 0; i--) { //loop from second to last downwards
        while (first element of stack is smaller) {
            remove first element from stack
        }
        if (largerKnown.isEmpty()) {
            largerKnown.addFirst(input[i]);
        } else {
            update the input[i] and add the old value of input[i] to the front of the stack
        }
    }
}

You'll still have to actually implement parts of this algorithm yourself. It shouldn't be that hard.


.parent().parent().parent().parent().parent().parent()

This can be much simplified by using parents() which returns an array, which you can just access with an index. I.e. you can replace the above with:

.parents()[5]

The upsides of this, besides being more concise, are that it the reader of your code can see which parent you're accessing without having to count the calls to parent and that if you ever need to access a different parent, you can just change the number instead of having to add or remove calls to parent.


This kind of switch statements can be refactored using maps/dictionaries. I would do it like this:

Edit: I actually made a couple of mistakes. After adding more unit tests I came up with a hopefully better version.

//V. 2:
public static string TranslatePersonTypeBetterRefactored(string personType, string lang)
{
    var allDicts = new Dictionary<string, Dictionary<string, string>>
                        {
                            {
                                "heb", new Dictionary<string, string>()
                                            {
                                                { "employee", "עובד" },
                                                { "contractor", "קבלן" },
                                                { "supplier", "ספק" },
                                                { "customer", "לקוח" }
                                            }
                            },
                            {
                                "eng", new Dictionary<string, string>()
                                            {
                                                { "עובד", "employee" },
                                                { "קבלן", "contractor" },
                                                { "ספק", "supplier" },
                                                { "לקוח", "customer" }
                                            }
                            },
                            {
                                "_eng", new Dictionary<string, string>()
                                            {
                                                { "employee", "employee" },
                                                { "contractor", "contractor" },
                                                { "supplier", "supplier" },
                                                { "customer", "customer" }
                                            }
                            }
                        };

    Dictionary<string, string> dict;
    string tran;

    if ((allDicts.TryGetValue(lang.ToLower(), out dict) &&
         dict.TryGetValue(personType.ToLower(), out tran)) ||
        (allDicts.TryGetValue(string.Format("_{0}", lang.ToLower()), out dict) &&
         dict.TryGetValue(personType.ToLower(), out tran)))
    {
        var shouldBeUpper = lang.Any(c => char.IsUpper(c));

        return shouldBeUpper ? tran.ToUpper()
                             : tran;
    }

    return string.Empty;
}

//V. 1 (buggy):
public static string TranslatePersonTypeRefactored(string personType, string lang)
{
    var engToUpper = lang == "ENG";
    var engToLower = lang == "eng";

    if (engToUpper && personType.Any(c => char.IsLower(c)))
        return personType.ToUpper();

    if (engToLower && personType.Any(c => char.IsUpper(c)))
        return personType.ToLower();

    var hebrewToEnglishWords = new Dictionary<string, string>
                        {
                            { "עובד", "employee" },
                            { "קבלן", "contractor" },
                            { "ספק", "supplier" },
                            { "לקוח", "customer" }
                        };

    var hebrewToEngTranslation = hebrewToEnglishWords[personType];

    return engToLower ? hebrewToEngTranslation
                      : hebrewToEngTranslation.ToUpper();
}


SpaceSaving frequent item counter in Python

Thanks for putting this code online! Two updates for people who may want to use it:

Correctness: The "if self.n > self.k:" is probably mistaken: for instance, when the sequence starts with k times the same element, we are later stuck with a data structure that contains a single counter. Instead, we can use self.k as representing the number of remaining counters with value 0: specifically, replace this line by "if self.k==0:" and just after the "else:" insert "self.k=self.k-1".
Small optimization: above "def push", replace by "self.push(self.counts[x], self.n, x)", i.e. use the latest value of x since we just updated it


Merge values of the objects properties with the same name into array

Your code looks ok overall. There are perhaps a few CoffeeScript features you can make use of, but nothing major.

However, I don't like that the input array is modified in-place (i.e. the function has side-effects). Other code may hold references to the param objects already, so altering them is potentially dangerous.

I'd rather have the function return a new, separate array with the results, leaving the input array untouched.

Here's a version that does that, and also removes duplicate params (I called it coalesce because it sounds fancier):

coalesce = (params) ->
  coalesced = {}

  for param in params
    {name, value} = param
    coalesced[name] or= []
    coalesced[name].push value

  for own name, value of coalesced
    value = value[0] if value.length is 1
    {name, value}


looping

Don't loop over indices. the iterattion used by Python is of such simplicity and elegance, and there are some really useful builtin helper functions, that looping over the index (or keys for a dict) is hardly ever necessary

I suggest you check out the excellent 'Looping like a Pro' talk by David Baumgold

def seek_and_convert(json_array, conversions):
    """seeks all data in a json array"""
    converted = []
    for item in json_array:
        if isinstance(item, dict):
            converted.append(seek_and_convert(item, conversions))
        elif isinstance(json_array[it_list], list):
            converted.append(seek_in_array(item, conversions))
        else:
            converted.append(item)
    return(converted)

the same for the dict

def seek_in_array(json_file, conversions):
    """seeks all data in a json file an converts it"""
    converted = {}
    for key, item in json_file.items():
        if conversions.has_option('CONVERSIONS', key):
            option = conversions.get('CONVERSIONS', key)
        else:
            option = key
        if isinstance(item, dict):
            converted[option] = seek_and_convert(item, conversions)
        elif isinstance(item, list):
            converted[option] = seek_in_array(item, conversions)
        else:
            converted[option] = item
    return(converted)

conversions.get

ConfigParser.get has a fallback argument, so instead of

if conversions.has_option('CONVERSIONS', key):
    option = conversions.get('CONVERSIONS', key)
else:
    option = key

This, together with the use of keyword arguments, can be converted to:

option = conversions.get(section='CONVERSIONS', option=key, fallback=key)

For testing and future expansio, it would also make more sense to pass the conversions on as a dict, instead as a ConfigParser object. You use it as a dict anyway.
Together with Hoist the IO, you get something like:

with StringIO(config_str) as config_file:
    config_parser = ConfigParser()
    config_parser.read_file(config_file)
    conversions = dict(config_parser.items(section="CONVERSIONS"))

In your real app, you can use with open(file, "r") as config_file instead of the StringIO

Then further on, all of this:

if conversions.has_option('CONVERSIONS', key):
    option = conversions.get('CONVERSIONS', key)
else:
    option = key

becomes:

option = conversions.get(key, key)

In contrast to your current load_conversion_table method, where you've hardcoded the filename, return a ConfigParser, and need to specify the section each time.

generators

Instead of keeping an intermediary dict or list, you can also yield the items:

def convert_dict(json_file, conversions):
    """seeks all data in a json file an converts it"""
    for key, item in json_file.items():
        option = conversions.get(key, key)
        if isinstance(item, dict):
            yield option, dict(seek_and_convert(item, conversions))
        elif isinstance(item, list):
            yield option, list(seek_in_array(item, conversions))
        else:
            yield option, item

dispatching

Instead of a chain of isinstance conditions, where depending on the type, a certain method is called with the same arguments, you can use the fact that functions are first-class citizens in Python and build a dict of parsers:

from collections import defaultdict

def fallback_parser():
    def parser(item, conversion):
        """parser that just returns the item, without conversion"""
        return item
    return parser

PARSERS = defaultdict(fallback_parser)
PARSERS[dict] = lambda item, conversion: dict(convert_dict(item, conversion))
PARSERS[list] = lambda item, conversion: list(convert_array(item, conversion))
PARSERS

and the parser functions become as simple as:

def convert_dict(json_dict, conversions):
    for key, item in json_dict.items():
        option = conversions.get(key, key)
        yield option, PARSERS[type(item)](item, conversions)

def convert_array(json_array, conversions):
    for item in json_array:
        yield PARSERS[type(item)](item, conversions)

If, later, you want support for datetime or other types, etc, this can be added by simply writing the parser and extending the PARSERS dict.

functools.singledispatch

An alternative is functools.singledispatch

from functools import singledispatch
@singledispatch
def parser(item, conversions):
    """parser that just returns the item, without conversion"""
    return item

@parser.register
def _(json_dict: dict, conversions):
    result = {}
    for key, item in json_dict.items():
        option = conversions.get(key, key)
        result[option] = parser(item, conversions)
    return result

@parser.register
def _(json_array: list, conversions):
    result = []
    for item in json_array:
        result.append(parser(item, conversions))
    return result

If you prefer the generator approach, you can do something like:

@singledispatch
def parser(item, conversions=None):
    """parser that just returns the item, without conversion"""
    return item

def convert_dict(json_dict: dict, conversions: dict = None):
    conversions = {} if conversions is None else conversions
    for key, item in json_dict.items():
        option = conversions.get(key, key)
        yield option, parser(item, conversions)

def convert_array(json_array: list, conversions: dict = None):
    for item in json_array:
        yield parser(item, conversions)

parser.register(
    dict, lambda item, conversions=None: dict(convert_dict(item, conversions))
)
parser.register(
    list, lambda item, conversions=None: list(convert_array(item, conversions))
)


Bash script that updates Intel e1000e driver

Simplifying the if-else that exit on failure

When the failure case of an if exits, you could move the success case out of the if, right after it, which will make it a bit shorter. And instead of an if, you could further simplify using the || operator. For example given this pattern:

if cmd; then
    echo "Done!"
else
    exit 1
fi

You could simplify as:

cmd || exit 1
echo "Done!"

You could apply this to all your ifs where you exit in case of failure.

But rather than just fail quietly, it would be better to do as @dopeghoti suggested and create a fail function and print some text in case of failure.

fail() {
    echo "$*"
    exit 1
}

cmd || fail 'Ouch, command failed'
echo "Done!"

Excessive comments

You have many obvious comments that add no value at all:

# Downloading driver and extracting it to current directory
echo "Downloading and extracting driver package..."

# Going into the driver source directory
cd e1000e-3.0.4/src/

In general, it's best when the code is self-explanatory. And in your script it's already the case, so you can remove all comments.

Error checking

Although you were careful to check errors in general, you forgot one:

cd e1000e-3.0.4/src/

Sure, if the tar earlier was successful, then this directory must exist, right? But what if one year later you update your script to get the package from e1000e-3.1.14.tar.gz instead and (heaven forbid) forget to update this directory name later in the script? If the cd command fails the script will happily continue and run the remaining commands, building whatever source you may have in the current directory instead of the right one. This will be safer:

cd e1000e-3.0.4/src/ || fail oopsie

Use more constants

It would be better to move more constants near the top of the file:

DRV_BASE_NAME=e1000e-3.0.4
DRV_SRC_DIR=$DRV_BASE_NAME/src
DRV_PKG_NAME=$DRV_BASE_NAME.tar.gz
DRV_PKG_URL=http://downloadmirror.intel.com/15817/eng/$DRV_PKG_NAME
MODULE_NAME=e1000e
MODULE_VERSION=3.0.4-NAPI

It will make the script easier to maintain.


Designing a service/business logic layer that returns useful/consistent messages

The problem with returning a message like this is that you are "hard coding" the messages in the registration method.  If you want to add localization (i.e. return a message in the users language as determined by the culture setting of the client) to the application later it will be much harder.  A cleaner approach would be to use custom exceptions and exception handling.  For example, if the an invalid email address is entered then a InvalidEmailException would be thrown by the RegisterUser method.  The part of the application that calls the RegisterUser method would determine what to present to the user for this type of exception or to percolate it up higher in the application for handling.  This is a cleaner separation of concerns of handling exceptions in the application from what is presented to the user.  This also promotes reuse because different users of the method may want to handle it differently.


I'm going to leave off suggesting anything about the algorithm for now as I don't fully understand what you want from it. Instead, I'm going to talk about your Point class in laborious depth...

public class Point
{
    public int X { get; set; }
    public int Y { get; set; }

I would argue that a point should be immutable - i.e. it doesn't change after you've created it. I would implement with full readonly properties:

private readonly int x;
public int X { get { return x; } }

private readonly int y;
public int Y { get { return y; } }

public Point(int x, int y)
{
   this.x = x;
   this.y = y
}

However, most people would let you off with private set auto properties:

public int X { get; private set; }

Let's look at your Equals implementations

public override bool Equals(Object obj)
{
    if (ReferenceEquals(null, obj)) return false;
    if (ReferenceEquals(this, obj)) return true;
    return obj.GetType() == GetType() && Equals((Point)obj);
}

protected bool Equals(Point other)
{
    return X.Equals(other.X) && Y.Equals(other.Y);
}

Firstly, bool Equals(Point other) -> that's IEquatable<Point> if made public so your class should implement that:

public class Point : IEquatable<Point>

Now, simplify the object.Equals override:

public override bool Equals(Object obj)
{
    return Equals(obj as Point);
}

And sharpen up the IEquatable<Point>.Equals:

public bool Equals(Point other)
{
    return other != null
            && other.X == X
            && other.Y == Y;
}

We should also override the == and != operators so that we're sure we are consistent with out equality:

public static bool operator ==(Point left, Point right)
{
    if (object.ReferenceEquals(left, null))
    {
        return object.ReferenceEquals(right, null);
    }

    return left.Equals(right);
}

public static bool operator !=(Point left, Point right)
{
    if (object.ReferenceEquals(left, null))
    {
        return !object.ReferenceEquals(right, null);
    }

    return !left.Equals(right);
}

Then you have a nice immutable class for your Point with consistent equality behaviour... Phew!

Edit

As EBrown pointed out in the comments, Point is a perfect fit for being a struct. It's less than 16 bytes, immutable and (0, 0) is a perfectly valid value (i.e. unitialized).


#include <vector> is pointless. There is no vectors in the code.
Unless I am missing something obvious, temp_space plays no role in the calculations.
pointsi and pointsj do not sound right (too much of visual noise makes it hard to tell them apart). It is one of the rear cases where I'd go for plain i and j.
t_step_t is confusing, and strictly speaking unnecessary. You may calculate it at the point of invocation as

result[t] = *besier_interp(..., t * t_step);


Evaluating two functions according to their performance

Time Complexity

Function A cost \$\mathcal{O}\left(n\right)\$

toLowerCase, split cost \$\mathcal{O}\left(n\right)\$
forEach cost \$\mathcal{O}\left(n\right)\$
Object.entries, filter cost \$\mathcal{O}\left(n\right)\$

counts[x] read / write may cost \$\mathcal{O}\left(1\right)\$ on average

Function B cost cost \$\mathcal{O}\left(n^2\right)\$

toLowerCase, split still cost \$\mathcal{O}\left(n\right)\$
filter cost \$\mathcal{O}\left(n^2\right)\$

indexOf, lastIndexOf cost \$\mathcal{O}\left(n\right)\$
filter repeat above operation \$\mathcal{O}\left(n\right)\$ times, thus \$\mathcal{O}\left(n\cdot n\right)\$

Time consume most occurred in loops. Not only forEach, fliter, but also toLowerCase, split, indexOf are loops. You didn't count the performance of nested loops correctly.
Also, notice that big-O notation is targeted to describe how fast the time consume increase when size of input increase. It not necessarily means an algorithm with better big-O notation will always be faster.
Implementation

Do not use str.split(''), use [...str] if you can. The split one won't handle some unicode points correctly. For example, [...'面'].length is 3 but '面'.split('').length is 5.
Use Map if you can (no need to support old browsers). Object is not an ideal way to use as a dictionary. Only if you want to keep ES5 support, you may use Object.create(null) instead.
You may count how many entries has at least count 2 during iteration by tracking if count[x] == 2 after increase. So there is no need to iterate Object.entries later.


Style

The general standard for Python is to indent by four spaces, or by one tab with a width of four spaces.
You shouldn't be doing wildcard imports, (from a import *).
Your naming can be greatly improved. For example, the variable b could be renamed to maximum_guess_limit.
Use str.format to format strings instead of using commas between string literals. Here's an example:

# str.format without positional or named parameters
print("{} {}".format("Hello", "world"))

# str.format with positional parameters
print("{1} {0}".format("world", "Hello"))

# str.format with named parameters
print("{word1} {word2}".format(word1="Hello", word2="world"))

Design

The logic in this program is very confusing, and with the bad variable names, it's not any easier to understand. From looking at the code, it looks like a number-guessing game of sorts, but I don't fully understand it's logic. I'd recommend encapsulating this into a function, or even separate functions. For example, to choose a random number based on a maximum integer, I'd create a function that looks something like this:

def choose_random_value(maximum_guess_limit):
    return randint(1, maximum_guess_limit)

In the end, I ended up with a result like this:

from random import randint

class NumberGuessingGame:
    def __init__(self, maximum_guess_limit):
        self.maximum_guess_limit = maximum_guess_limit
        self.__points = 0

    def __choose_random_integer(self):
        """
        Choose a random integer between one and the
        current maximum limit.
        """
        return randint(1, self.maximum_guess_limit)

    def __obtain_user_input(self, prompt):
        """
        Obtain the user input and ensure that
        it is a valid integer.
        """
        try:
            return int(input(prompt))
        except ValueError:
            print("You must enter a valid integer.")
            return None

    def __check_user_input(self, user_input, random_integer):
        """
        Check if the user guessed correctly, otherwise,
        display "Higher." or "Lower."
        """
        if user_input is not None:
            if user_input == random_integer:
                self.maximum_guess_limit += 5
                self.__points += self.__points

            elif user_input < random_integer:
                print("Higher.")

            else:
                print("Lower.")

    def play_game(self):
        while True:
            user_input = self.__obtain_user_input("Enter an integer: ")
            integer_to_guess = self.__choose_random_integer()
            self.__check_user_input(user_input, integer_to_guess)

game = NumberGuessingGame(10)
game.play_game()

It doesn't have support for exiting, but I'm sure you can implement it.


Styling

All forms should be separated by a single newline.
All let bindings should be on their own line. So

(let [my-max (max min-val max-val) my-min (min min-val max-val)] ... )

Should be:

(let [my-max (max min-val max-val)
      my-min (min min-val max-val)]

Instead of fully qualifying other namespaces, you should require them in your ns delclaration:

(ns numguess.core
  (:require [clojure.string :as string]))

(string/trim ...)
(string/lower-case ...)

Structure

Before I even read the requirements, I could tell this was some sort of number game. So that's good.

However, I found it very difficult to figure out how the user input was being read in. get-input is buried
three layers deep for every codepath it's in. Input is parsed ad-hoc in various places, and occasionally the input is altered by default.
I would suggest trying to clearly separate your concerns here. Your objectives are:

Prompt the user for input
Parse that input into usable data (this would include parsing "" to a default value)

If you can separate those things out, you can easily expand Number 2 for any data type you need to parse (e.g. boolean for the "y/n" prompt).

Also, gameplay can be simplified by using a cond rather than nested ifs.

All of that being said, the structure of mainloop gives a pretty clear overview of the entire program. So bravo there.

General Notes

I've said this in another Code Review answer, but I think it applies here too.

When I moved from Java to Clojure, I tended to like very small functions (e.g. is-yes, get-input-prompt, and get-number-input).
Over time, I've found it's a) more idiomatic and b) easier to understand if you start with a rather large function and break it up as needed to
increase understanding. My reasoning for this preference is that Clojure already gives you really good, simple building blocks.
This allows you to define the simple functions that directly enrich your domain without worrying as much about length.
If I want added documentation, I will let a variable with a good name.

In the solution I wrote while preparing this code review, I didn't even include a gameplay or a generate-my-number function. Those pieces
ended up being small enough to fit in mainloop without making it too complex. And, as I said, if you can do that, it actually ends up being
easier to understand because you're not creating artificial abstractions just to hide complexity.

Update in response to OP's comment

Just to clarify my statement about function size, the goal isn't to have small functions or large functions. The goal is to have functions that do one thing, and do it in a clear, concise way.

That goal is really what programming is all about, no matter the language.

The only difference I've found with Clojure is it's easier to express higher concepts clearly. So you're not looking for arbitrary seams just to make your function smaller. You look for concepts that you can cleanly abstract out.

All that to say, if you've found the right places to break up your program, testing should be easier, not harder. Because you're working with a particular domain concept instead of an arbitrary seam.

Additionally, I find testing less necessary overall. I spend more of my time trying to find those simple concepts and less of it building guard rails for myself. Take, for example target-num in my solution below. I could abstract that out (it is a single concept, so it wouldn't be a bad idea) and write a test for it, but a) it's random, so bleh, and b) I can see everything it's doing right there. So there is no real benefit to writing a test around it.

YMMV on the testing thing. Many people find it valuable as a feedback mechanism rather than a guardrail. Just my personal take. :)

Here's my solution:

(defn prompt [parser prompt-text]
  (println prompt-text)
  (if-some [value (try
                    (parser
                      (string/trim
                        (read-line)))
                    (catch Throwable _))]
    value
    (do
      (println "I'm sorry. I didn't understand you.")
      (recur parser prompt-text))))

(defn parse-int [s]
  (Integer/parseInt s))

(defn parse-bool [s]
  ({"y" true
    "yes" true
    "true" true
    "n" false
    "no" false
    "false" false} (string/lower-case s)))

(def prompt-int (partial prompt parse-int))
(def prompt-bool (partial prompt parse-bool))

(defn my-mainloop []
  (let [min-val (prompt-int "Please enter minimal value")
        max-val (prompt-int "Please enter maximal value")
        target-num (+ (rand-int
                        (- (inc max-val) min-val))
                      min-val)]
    (loop []
      (let [guess (prompt-int "What is your guess?")]
        (cond
          (< guess target-num) (do
                                 (println "My Number is bigger")
                                 (recur))
          (> guess target-num) (do
                                 (println "My Number is smaller")
                                 (recur))
          :else
          (println "You have guessed it: congratulations :)"))))
    (when (prompt-bool "Would you like to play again?")
      (recur))))


A few minor things:

Imports should generally be at the module level, not inside functions.
Use more intention-revealing variable names. no_of_guess is borderline OK, but a, b and c don't tell me anything.
Think about control flow more carefully. For example:

you increment the guess counter for any numerical input, so you don't necessarily need to wait for the conditional checks; and
outside the loop do you really need to recheck whether the input wasn't "y"?

You can use single-quoted strings to avoid escaping double quote within them.
You can also reduce duplication by extracting functions and constants

With these suggestions addressed:

import random

RULES = 'Enter "Y" if yes, and anything else to exit. '

def win_prompt():
    return input("You got it! Play again? " + RULES).lower()

def lose_prompt(message):
    return input(message + " Try again? " + RULES).lower()

def guessing_game():
    number_of_guesses = 0
    target = random.randint(1,9)
    continuing = "y"
    while continuing == "y":
        guess = input("Enter a guess: ")
        if guess.isdigit():
            number_of_guesses += 1
            if int(guess) == target:
                continuing = win_prompt()
                target = random.randint(1,9)
            elif int(guess) > target:
                continuing = lose_prompt("Too high.")
            else:
                continuing = lose_prompt("Too small.")
        else:
            continuing = lose_prompt("Haha.")
    print("How unfortunate. Well, you made %s guess(es)." % number_of_guesses)

guessing_game()


Merge some child values back into the parent multidimensional array

What's the criteria for deciding which keys to keep?

Check out the array_walk_recursive() function. For example, the following matches any element with a key that starts with "nice_value".

$array = /*your array example*/;
$filtered = array();
array_walk_recursive($array, function($val, $key) use(&$filtered) {
    if (strpos($key, 'nice_value') === 0) {
        $filtered[$key] = $val;
    }
});


String pattern matching - method needs improving

The function getTokenValues is actually a pattern matching function. It just uses a different syntax than the pattern format of java.util.regex.

I suggest you to convert your pattern string (the one with $ signs) into a valid Pattern.

${1}/andThen/${2}/followedBy/${3}

becomes

(.+?)/andThen/(.+?)/followedBy/(.+?)

And then you can use Pattern.matcher to find the content of the groups. There is still one thing missing : the fact that the numbering of the original pattern is lost. For that, you can parse the original pattern string to extract those numbers, to create a mapping table.

When you convert your pattern string into a Pattern, be careful to escape the substrings between the $ using Pattern.quote().

I don't know if this solution would be an improvement of yours, but it's an alternative to consider.

Edit

The implementation of my solution :

Map<String, String> getTokenValues(String pattern, String str) {
    Map<String, String> res = new HashMap<String, String>();
    List<String> identifiers = new ArrayList<String>();

    Pattern dollarRgx = Pattern.compile("\\$\\{([0-9]+?)\\}");
    Matcher dollarMatcher = dollarRgx.matcher(pattern);
    StringBuilder convRgxBd = new StringBuilder();
    int lastEnd = 0;
    while(dollarMatcher.find()) {
        String before = pattern.substring(lastEnd, dollarMatcher.start());
        convRgxBd.append(Pattern.quote(before));
        convRgxBd.append("(.+?)");
        lastEnd = dollarMatcher.end();
        identifiers.add(dollarMatcher.group(1));
    }
    String after = pattern.substring(lastEnd, pattern.length());
    convRgxBd.append(Pattern.quote(after));

    Pattern convRgx = Pattern.compile(convRgxBd.toString());
    Matcher convMatcher = convRgx.matcher(str);
    if(convMatcher.matches()) {
        for(int i = 0; i < convMatcher.groupCount(); i++) {
            String id = identifiers.get(i);
            res.put(id, convMatcher.group(i+1));
        }
    }

    return res;
}


Here is what I came up with:

#!/usr/bin python
from os import system as sys

def GetReceipt():
    prompt = "Insert receipt number (if you finished insert 'f'): "
    inserted_text = ''
    while True:
        sys('clear')
        inserted_text = raw_input(prompt).upper()
        if inserted_text == 'F': break
        yield inserted_text

def final(receipt):
    sys('clear')
    print ["You did a great job, here's your receipts:\n"+' '.join(receipt),
        "You did not enter a single receipt..."][len(receipt) == 0]

if __name__ == '__main__':
    valid_receipts = [ f for f in GetReceipt() ]
    final(valid_receipts)


If we assume that a float is represented in memory as a (sign, mantissa, exponent) tuple, and assume a radix of 2, then we can find the machine epsilon exactly.  That is, if we can assume the machine stores floats using base-2 representations of the mantissa and exponent, then we know that:

The machine will store a value of 1 in floating point exactly - this would be stored as 1 for the mantissa, and 0 for the exponent, i.e. 1 * 2^0.
The machine will store all powers of two that it can represent using a single bit in the mantissa, and by varying the exponent.  E.g. 1/4 could be represented as 1 * (2 ^ -2).  Any representable power of two will be stored without losing information.
1 + epsi will be the smallest value greater than 1 that can be stored in the mantissa of the floating-point number.

EDIT

The second version looks much better than the first, but I believe there's an off-by-one error in the number of times you recurse in find-epsi.  I suggest that you create a test function, to see if your result is the machine epsilon:

(defun epsi-sig-p (epsi)
  (> (+ 1.0 epsi) 1.0))

You'll probably find that (is-sig (find-epsi)) is #f...  This also suggests that you can refactor (under the DRY principle) find-epsi to use this test function in find-epsi:

(defun find-epsi (&OPTIONAL (epsi 1.0))
  (if (epsi-sig-p epsi)
    (find-epsi (/ epsi 2))
    epsi))

but we didn't change the behavior to fix the calculation, yet.  For this, I'd suggest another routine, to check whether we should try the next possible epsi:

(defun next-epsi (epsi) (/ epsi 2))
(defun is-epsi-p (epsi)
  (and (epsi-sig-p epsi) (not (epsi-sig-p (next-epsi epsi)))))
(defun find-epsi (&OPTIONAL (epsi 1.0))
  (if (is-epsi-p epsi)
    epsi
    (find-epsi (next-epsi epsi))))

is-epsi-p should return #t, now.


Using System.Security.Cryptography.ProtectedData, do you see any issue with encryption and encoding?

Your code is correct. I usually use Encoding.UTF8 because it is more compact for typical character sets.
SecureString is kind of a useless class. It is meant to never keep a secret unencrypted even in memory. This would only help if an attacker could read your processes memory. If he can do that you have lost already because he can read every character of your password the moment you use it or add it to the SecureString. Anyway, what attack scenario on earth allows an attacker to read your webserver process memory and not do other more dangerous things at the same time? In that case your box is probably compromised entirely. So you are right not using this class.


Better way to code download speed calcuation

Your summary complaint is that you're measuring short term xfer rate from system buffers to user space, rather than long term xfer rate from distant server to local network interface.

After a few roundtrips, TCP opens the congestion window and can have many KiB of data in flight. I don't know what your buffer.length is, but you make it sound like it is short enough that you're not blocking on read. That is, ns.Read() finds quite a lot of data buffered at the OS level, and returns a buffer's worth of it at once, so that your timing represents local CPU / memory bandwidth rather than network bandwidth.

The simplest remedy is to record initial starting time and don't touch it, report cumulative bytes read over cumulative elapsed time.

If your residential ISP does traffic shaping, and you want the display to reflect the fact that the first 30 seconds goes at 3 Mbps but longer downloads go at 1 Mbps, then keep a circular buffer of the last dozen or so timestamps, and use that to report on recent progress. Old measurements will age out, so after a while they will no longer affect the display.


I would:

Use a FormData instead of creating a form element.
Give it a name better than "postR", like... simply "post"?
Add an error handler to the $.ajax call
Unify both $.ajax calls

Pseudo code (Not tested):

function post(url, params, redir = false, callback = null) {
  var formData = new FormData();

  for (var key in params) {
    formData.append(key, value);
  }

  $.ajax({
    type: "POST",
    url: url,
    data: formData,
    success: function(data) {
      typeof(callback) === "function" && callback(data);
      redir && window.location.reload();
    }
  });
}


Use tuples

...instead of lists when your data are immutable. There are a few advantages, including marginal performance increases in some scenarios, and catching "surprises" where code is attempting to modify your data where it shouldn't.

Unpack your tuples

Indexing points is nasty.

Use more sets

I think my rewritten code with set operators is equivalent. Peruse the documentation for info on the symmetric difference ^ and subset < operators.

Edit: you don't even need the subset test; all you need is set equality.

Don't "ternary instead of if"

Even if you didn't do the symmetric set operation and kept your add/remove code, just... don't do this. It's the worst mix of "too clever", "too illegible" and "difficult to maintain".

Coalesce your returns

...into one boolean statement, for simplicity.

Proposed

def is_rectangle_cover_orig(rectangles):
    if len(rectangles) == 0 or len(rectangles[0]) == 0:
        return False
    x1 = float("inf")
    y1 = float("inf")
    x2 = 0
    y2 = 0
    rect = set()
    area = 0
    for points in rectangles:
        x1 = min(points[0], x1)
        y1 = min(points[1], y1)
        x2 = max(points[2], x2)
        y2 = max(points[3], y2)
        area += (points[3] - points[1]) * (points[2] - points[0])
        rect.remove((points[0], points[3])) if (points[0], points[
            3]) in rect else rect.add((points[0], points[3]))
        rect.remove((points[0], points[1])) if (points[0], points[
            1]) in rect else rect.add((points[0], points[1]))
        rect.remove((points[2], points[3])) if (points[2], points[
            3]) in rect else rect.add((points[2], points[3]))
        rect.remove((points[2], points[1])) if (points[2], points[
            1]) in rect else rect.add((points[2], points[1]))
    if (x1, y2) not in rect or (x2, y1) not in rect or \
            (x1, y1) not in rect or (x2, y2) not in rect or len(rect) != 4:
        return False
    return area == (y2 - y1) * (x2 - x1)

def is_rectangle_cover_new(rectangles):
    if len(rectangles) == 0 or len(rectangles[0]) == 0:
        return False
    x1, y1 = float("inf"), float("inf")
    x2, y2 = 0, 0
    rect = set()
    area = 0
    for xr1, yr1, xr2, yr2 in rectangles:
        x1 = min(xr1, x1)
        y1 = min(yr1, y1)
        x2 = max(xr2, x2)
        y2 = max(yr2, y2)
        area += (yr2 - yr1) * (xr2 - xr1)
        rect ^= {(xr1, yr2), (xr1, yr1), (xr2, yr2), (xr2, yr1)}
    return (
        rect == {(x1, y2), (x2, y1), (x1, y1), (x2, y2)} and
        area == (y2 - y1) * (x2 - x1)
    )

def test():
    for i, rects in enumerate((
        (
            (1, 1, 3, 3),
            (3, 1, 4, 2),
            (3, 2, 4, 4),
            (1, 3, 2, 4),
            (2, 3, 3, 4)
        ),
        (
            (1, 1, 2, 3),
            (1, 3, 2, 4),
            (3, 1, 4, 2),
            (3, 2, 4, 4)
        ),
        (
            (1, 1, 3, 3),
            (3, 1, 4, 2),
            (1, 3, 2, 4),
            (3, 2, 4, 4)
        ),
        (
            (1, 1, 3, 3),
            (3, 1, 4, 2),
            (1, 3, 2, 4),
            (2, 2, 4, 4)
        )
    ), 1):
        old_ans = is_rectangle_cover_orig(rects)
        new_ans = is_rectangle_cover_new(rects)
        print(f'Example {i}: {old_ans}')
        assert old_ans == new_ans

test()


Current property

You should never throw the Exception. There is almost always a more appropriate exception already available or you should create a new one. The name of the exception usually already indicates the reason for it.

In this case I would pick the InvalidOperationExctption.

LoadSession method

Is the user allowed to re-load the session? If not then either throw an exception if he tries it again or return the already loaded session with the coalesce operator:

session = session ?? storage.LoadSession(sessionId);

I would also prefer if the method returned the loaded session too so I can immediately use it without switching to the property:

return (session = storage.LoadSession(sessionId));

You can assign it and return it in a single line.

StudySession vs Session classes

I woudn't create another session object. I think you should just reuse the Seesion you get from the database. It already has everything you need. You are just copying the values.

Your code would become much simpler without this mappings.

Chapter class

To loosen the coupling you would need to make the methods of this classes non-static and pass to the constructor an instance of the DSDatabase or its interface and maybe a SessionManager but I don't entirely understand what it is good for. Actually you need a group id for the GetChildren query. So maybe pass it as a parameter.


C++: k-Nearest Neighbours with Lambdas and Priority Queues

Answers to your questions

Should other lambdas be captured by referenced or by value?

Functionally, for non-mutable lambdas, it doesn't matter. However, if a lambda is marked mutable then capturing by value will make a copy of the lambda's state, whereas if it's a reference no copy is made. Here is an example you can try out yourself:
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> vs[2];
    auto iota = [i=0]() mutable {return i++;};
    auto generator = [&iota]() mutable {return iota();}; // try removing the &

    for(auto &v: vs) {
        std::generate_n(std::back_inserter(v), 5, generator); // try using iota directly
        for(auto i: v)
            std::cout << i << ' ';
        std::cout << '\n';
    }
}

It's probably best to capture them by reference, unless mutable lambdas are used and you want a copy of the state to be made.

For auto return types, when should you use the arrow notation to signify a return type?

You should use it when it is important to constrain the return type, so that you don't accidentily return the wrong type. For example, if I want to write a function that calculates the square root of something, and always return the same type as the input, you should write:
auto square_root(auto value) -> decltype(value) {
    return std::sqrt(value);
}

If you omit the trailing return type, then calling the above function with an int will return a double instead. And that might then be a problem if you would do something like:
printf("Square root of 4 is %d\n", square_root(4)); // runtime error

Is there a cleaner way to declare the type of queue in the code below?

Yes, if you can make the compiler deduce that it should use closer() to compare two Points. One option is to make Point a class and implement operator<(), another one (as pointed out by Mikael H) is to just define a global overload for operator< that takes two Points:
bool operator<(const Point& p1, const Point& p2) {
    return closer(p1, p2);
}

Then you can just write:
std::priority_queue<Point> queue;

Use std::partial_sort_copy
Using a priority queue is one way to solve it, but it is a bit cumbersome here, since there is no fast way to get the first k elements out. Also, by adding all input elements to the queue, you have sorted all elements, which means you have done more work than necessary. What you want is just to do a partial sort, where you sort the input array until you get the first k smallest elements, and you don't care about the order of the rest. std::partial_sort_copy() allows you to do that, while still allowing a const reference to the input vector:
std::vector<Point> nearest_neighbours(k);
std::partial_sort_copy(points.begin(), points.end(), nearest_neighbours.begin(), neareset_neighbours.end(), closer);
return nearest_neighbours;


First, I'd prefer to parse the int[] into a Node[] or somesuch - I'd even argue the name of node_value is a code smell indicating that it should be a member called value of a type called Node. I believe this is part of what causes your consternation with the header variable.

Speaking of names, D naming conventions generally avoids underscores except for constants, so more idiomatic names would be nodeValue and countMetadata (which would perhaps more correctly be called sumMetadata).

One of the reasons you should parse to Node[] is it factors out the common parts between node_value and count_metadata, making their responsibilities clearer and the code easier to follow - remember, you're writing code for the next person who looks at it; the computer is happy with a string of bits that nobody can read.

Now, you mention genericity. For the most part, replacing (ref int[] r) with (R)(ref R r) if (isForwardRange!R) will deal with this. This templates the functions on the type of the range passed. Your code otherwise uses range functions (front, popFront, take, etc), so so no other change is necessary.

However, due to the structure of the file format, you will need to read all child nodes before getting at the metadata of a node. This limits the possible laziness of the solution. Since you are always iterating over every node, this doesn't matter a whole lot, but since that's one of the great benefits of ranges, it's worth pointing out.

As for consuming the range, there is no very simple, unobtrusive solution. You need to either create a temporary variable (like p1), have a duplicate function for the non-ref case, or use inner functions:

int count_metadata(R)(R r0)
if (isForwardRange!R)
{
    int impl(ref R r) {
        // Same code as before, but call impl instead of count_metadata
    }
    return impl(r);
}

You also mentioned efficiency. I don't think I can improve much on that. Both count_metadata and node_value are O(n), and my proposed solution doesn't change that.


My first thought based on your comment (behavioral and state testing in same test) was that you should just make two different tests.

However, then I took a step back. The specification says that:

  add[ing] a duplicated transaction will fail

It doesn't say anything about how a duplicate is determined. Currently, you are using the naive implementation is to check if and of existing transactions equal the one being added. However, that is not the only way satisfy the requirement.

If there are a large number of transaction, it will be slow to iterate over each transaction. Instead, the transactions could be stored in a map that uses the id as a key. Now be can check if the transaction already exists by doing a single key lookup, \$O(1)\$ instead of \$O(n)\$.

The fact that Transaction#== is called is an implementation detail. Based on this, the behavioral assertion should be removed from the test. If there happens to be a different requirement, that was not presented here, that the duplication check must be done throw an equivalence check, then that should be a different test.


Here are a few suggestions, in my opinion, to improve your code:

Using Port Registers:
You use PORTD, PIND, and DDRD in the code. These can be replaced bydigitalWrite(),digitalRead() and pinMode(). Here is the Arduino reference page for Port Registers. Although they will quicken the speed of execution, in your case, that high speed is not required, especially in the setup. The suggested alternatives will fulfill the task equally well.
Electronic Advice:
Avoid using the pin 0 and pin 1. These are used for Serial debugging, and even though you are not using serial communication, it is good practice to not use them for I/O. Here is a reddit post discussing that, here is the official board layout reference.
Specific Code reductions:
in set_mem(), instead of the logical conditions, you can predefine an array map = {0x01, 0x02, 0x04, 0x08} and then set the mem[i] = map[random(4)].
Gameplay improvements
As it stands, it is very confusing to see what is going on, and how to play the game. Assuming that you are limited by these components and the difficulty level of the code is not to be scaled, you can consider the following:

Indicating correct pressing. Currently, it is difficult to make out which two LEDs signal the completion of showing the required sequence, and which two signal you having pressed the buttons correctly. You can create another function which does not light up any LED but just signals a correct press by means of a musical sound, the relative pleasantness indicates to any onlooker that the answer was correct. Consider a simple increasing and decreasing tone, or even better, look-up the frequencies somewhere like here of musical notes and create a pleasant tune! Just replace the NT(0X06)by the new function.
Indicating failure. You can include the Failtone for a larger duration with all the 4 LEDs to indicate failure. You might have to make a new function to replace NT(0X09).
I am not sure whether having to repeat the sequence with one new added press each time is a part of the design. But if it is not, you can create a new sequence each time, by keeping set_mem() in the loop, so that every time they complete a sequence, an entirely new sequence of presses (longer by 1) comes up next.

Provisions for faulty game play. Currently, the person can press the buttons while the sequence is being displayed. Although it does not affect the gameplay in any way, it is generally good practice to anticipate faulty play. adding, for example, the following in the code below blink(mem[x]) in the nested for loop, may achieve that, where failurefunction is what you use to indicate failure.

Code:

  look = PIND >> 4;
  if (look != 0){
  failurefunction();
  break;
  }

I hope this was helpful.


Simple mutex and conditional variable signal in C

Needs volatile keyword
The way your program is written, predicate_value needs to be a volatile int instead of a normal int.  This is because you are reading it without locking the mutex in main(), and writing to it in do_work() from another thread.
Another way to avoid the problem is to ensure that you only ever read the variable with the mutex locked.


body { overflow: hidden; }

You should really never hide overflow on content-based elements. People with small browsers may not see the full content, rendering the site useless to them. overflow: auto is a much better alternative because scrollbars will only be shown if there is overflow. You can tune this even more with overflow-X, overflow-Y.

Using purely px based sizing creates very small text when people have large displays. People who browse on a TV will likely find the page to have tiny text and large side margins.

footer {
  position: absolute;
  bottom: 0;
  left: 0;
}

Using absolute positioning on block elements can cause portions of the content to get obscured. To counter this you can add padding or margin to the bottom of the body element.

You have odd indentation throughout the entire code. It's better to set a set style for readability.

For instance, instead of this:

h1 {
  line-height: 48px;
  margin: 24px 0;

  color: #fff;
  text-shadow: hsl(15, 84%, 10%) 1px 1px, hsl(15, 84%, 10%) 2px 2px, hsl(15,             84%, 10%) 3px 3px, hsl(15, 84%, 10%) 4px 4px;
    text-transform: uppercase;
    text-align: center;
    white-space: nowrap;
  }

This:

h1 {
  line-height: 48px;
  margin: 24px 0;

  color: #fff;
  text-shadow: hsl(15, 84%, 10%) 1px 1px,
               hsl(15, 84%, 10%) 2px 2px,
               hsl(15, 84%, 10%) 3px 3px,
               hsl(15, 84%, 10%) 4px 4px;
  text-transform: uppercase;
  text-align: center;
  white-space: nowrap;
}

  I'm not sure whether my use of the units is correct.

This looks pretty good. Here is information regarding use of units:

px is the pixels relative to pixel density. The pixel density can affect the size of a pixel with

<meta name="viewport" content="width=device-width, initial-scale=1">

where initial scale is the amount that the pixel density affects the size of a pixel.

Meta tags go in the head element.

em is the measure of one font size on the element, therefore if an element has font-size: 16px one em is 16px. Em is relative to the parent element as well so font-size: 1.5em is 1.5 times the parent's font size.

rem is the measure of one :root element font size. If :root { font-size: 16px } then most elements will base their font size off of a 6px multiplier. Some people use calc() in their :root font size to create a scaling font. This can be done like:

:root { font-size: calc(.5em + .5vw) }

which means that the root font size will be .5 of the browsers default font size plus .5% of the viewport width.

em and rem are usable on more than just the font-size property.

% is a percentage of that parent's measurement for the tag. If the parent has width: 50px and the child has width 50% the child's width will calculate to 25px.

Other units you might need are vw, vh, vmin, vmax. These are scaling units, always relative to the viewport's size. These are helpful for scaling elements so that they always fit in the browser window. These values can be negative or greater than 100.

vw is 1% of the viewport's width. If the viewport is 500px wide then 1vw is 5px, 2vw is 10px and 7vw is 35px.
vh is 1% of the viewport's height. If the viewport is 243px then 1vh is 2.43px.
vmin is 1% of the smaller viewport side's length. If the viewport is 624px wide and 437px tall then 1vmin is 4.73px.
vmax is 1% of the larger viewport side's length. If the viewport is 1242px wide and 804px tall then 1vmax is 12.42px.


Rendering nested array in a  with headings

This won't work if each suggestion does not start a new area.

foreach($suggestions as $suggestion)
    {
    if($currentarea != $suggestion['area'])
        {
        echo "
";
        echo $suggestion['area'];
        echo "
";
        if($status == 'closed')
            {
            echo "
";
            $status = 'open';
            }
        }
    foreach($suggestion['activity'] as $activity)
        {
            echo "
";
            echo $activity;
            echo "
";
        }
    if($status == 'open')
            {
            echo "
";
            $status = 'closed';
            }
    $currentarea = $suggestion['area'];
    }

You close on every iteration that it's open and add list items on every iteration, but you only open if the area changes.

foreach($suggestions as $suggestion)
{
    echo '
';
    echo $suggestion['area'];
    echo "
\n";
    echo "
\n";

    foreach($suggestion['activity'] as $activity)
    {
        echo '
';
        echo $activity;
        echo "
\n";
    }

    echo "
\n";
}

This code is simpler and will work more reliably.

This is the wrong place to discuss how to write new code.  But if you want to get the previous concept working, you'll want to open and close inside the if that checks if the area has changed.  Or pull off the first element of the list so that you can treat it differently.  Or make a new list where there's only one suggestion per area, combining multiple suggestions with the same area into one.


Message queue with multiple producer, single consumer and no duplicates

You code looks like it works just fine, but only because you have a single consumer thread. If you have multiple consumers, then you have a race-condition in your takeMessage method (a different thread may empty the queue after you call hasNext() but before you call next() causing an iteration exception....).

The whole iterator method also feels... clunky, and is a result of the basic Set usage.

I can't help but think that, in your situation, the use of the ConcurrentMap backing the set, is overkill. I know that HashSets have a backing Map as well, but that's different.

So, having thought some more about it as well, I also have to question the need to de-duplicate the producer messages as well in the Set... are you sure you need to?

Also, since you have the system you do, are you sure the queue will ever be big enough to worry about performance of the Set?

I can't help but feel you should go one of two ways:

Just use a LinkedTransferQueue and deal with duplicates elsewhere (use the add and poll methods respectively).
Just use a List with a simple contains() and basic synchronization.

Some other notes....

Why do you have a constructor that takes an initial size, but then does nothing?

Here's a simple synchronized version:

public class MessageClassHolder<T> {

    private final LinkedList<T> messages;

    public MessageClassHolder() {
        messages = new LinkedList<>();
    }

    /**
     * @param message to be inserted
     * @return if message already present returns false
     */
    public boolean insertMessage(T message) {
        synchronized(messages) {
            if (messages.contains(message)) {
                return false;
            }
            return messages.add(message);
        }
    }

    /**
     * @return returns the optional message and removes it
     */
    public Optional<T> takeMessage() {
        synchronized(messages) {
            return messages.isEmpty() ? Optional.empty() : Optional.of(messages.removeFirst());
        }
    }

    /**
     * Clear the message set
     */
    public void clear() {
        synchronized(messages) {
            messages.clear();
        }
    }
}


Finding the number of words from a user input string or a text file

On Regex use
To correctly split on white space and count the amount of words you want, use trim().split('\\s+').length
You want to split on all whitespace, not just a single ones in between, and you need to trim first because otherwise you'll also get inaccurate results for any input beginning with spaces.
This will also work just as well for your file input -- not too sure why you use a different method.


Wouldn't it be easier to unpack the tree into a dictionary mapping each symbol to its corresponding bit string?  Then you could simply look up each symbol in the input to generate the corresponding output bits.

EDIT:
As suggested by syb0rg, here is an implementation (C#, I'm afraid -- my Lisp is far too rusty -- although it's almost pure).  The part pertaining to my suggestion above lives in the HuffmanCodes function at the end.

void Main()
{
    var corpus = @"Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.";
    var hcs = HuffmanCodes(corpus);
    Console.WriteLine(hcs);
}

Dictionary<char, int> Histogram(string corpus) {
    var hg = new Dictionary<char, int>();
    foreach (var x in corpus) {
        int f;
        hg.TryGetValue(x, out f);
        hg[x] = f + 1;
    }
    return hg;
}

class HuffTree {
    internal char? Sym; // Non-null iff this is a leaf node with no children.
    internal int Freq;
    internal HuffTree L;
    internal HuffTree R;
}

// Oh, for a priority queue.  This is *really* inefficient!
HuffTree HuffmanTree(string corpus) {
    var hg = Histogram(corpus);
    var hts = hg.Keys.Select(x => new HuffTree { Sym = x, Freq = hg[x] }).OrderBy(t => t.Freq).ToList();
    while (2 <= hts.Count) {
        var leasts = hts.Take(2).ToList();
        var l = leasts[0];
        var r = leasts[1];
        var newHt = new HuffTree { Freq = l.Freq + r.Freq, L = l, R = r };
        hts = hts.Skip(2).Concat(new HuffTree[] { newHt }).OrderBy(t => t.Freq).ToList();
    }
    return hts.First();
}

Dictionary<char, string> HuffmanCodes(string corpus) {
    var codes = new Dictionary<char, string>();
    Action<HuffTree, string> a = null; // Sweet recursion.
    a = (ht, code) => {
        if (ht.Sym != null) {
            codes[(char)ht.Sym] = code;
        } else {
            a(ht.L, code + "0");
            a(ht.R, code + "1");
        }
    };
    a(HuffmanTree(corpus), "");
    return codes;
}


Perform loop through process on all sheets at once

I'll take a crack at this. First things first - always qualify where you're doing something e.g. AutoFilterMode = False should be ws.AutoFilterMode = False.
Your variable names are lacking - lrc, LR1 and LR2 give me no idea as to what they are being used for or if they are different from one another. Same goes for key1 - it's for a "Script Name" according to the inputbox, so why not name is ScriptName or ScriptNameKey? And ws as Worksheet, why not say MyWorksheet or CurrentWorksheet?
You're clearing out Sheets("SCRIPT") but I don't know why, I don't see anything going back to it.
Your indentation is difficult to follow, your for loops and if blocks should be offset like this -
key1 = InputBox("Type Script Name", "Title")

    For Each ws In ActiveWorkbook.Worksheets
         If (ws.Name <> "SCRIPT") And (ws.Name <> "MARKET") And (ws.Name <> "CHAIN") Then
              ws.Range("AE1:AJ500").ClearContents
              ws.Range("CB1:CH500").ClearContents
         End If
    Next

It makes it a lot easier to read. You can actually indent several lines in the VBE by highlighting and hitting Tab.
When you're working with all those .Range elements, you can use a With block -
 key1 = InputBox("Type Script Name", "Title")

        For Each ws In ActiveWorkbook.Worksheets
            If (ws.Name <> "SCRIPT") And (ws.Name <> "MARKET") And (ws.Name <> "CHAIN") Then
                With ws
                    .Range("AE1:AJ500").ClearContents

                    .Range("P1").AutoFilter
                End With
            End If
         Next

This will make it less cluttered. You should also use some comments to explain why things are happening -
 'These ranges need to be cleared to ensure the formatting of xxx doesn't change as it reaches the destination
 .Range("AE1:AJ500").ClearContents
 .Range("CB1:CH500").ClearContents
 'We filter on these two criteria because that allows ....
 .Range("A1").AutoFilter Field:=1, Criteria1:=key1
 .Range("A1").AutoFilter Field:=2, Criteria1:="28-Jan-16"

Speaking of your autofilters why not
Dim FilterDate as Date
FilterDate = Now() 'or whatever the date needs to be

Now you don't have to go into the code to find it.
The same goes for your second criteria, why not give those variables at the top as strings and then use the variables, that way if anything changes you can just change it at the top.
In your second If block you are moving between ws and two defined sheets. Why not give those sheets a variable as well?
Personally I don't like all the .Copy Destination methods. I like to work directly with the locations like this -
.Range("AG2") = .Range("L2:L" & lrc).SpecialCells(xlCellTypeVisible)
.Range("AE2") = .Range("C2:C" & lrc).SpecialCells(xlCellTypeVisible)
.Range("CD2") = .Range("L2:L" & lrc).SpecialCells(xlCellTypeVisible)

This has the added benefit that if you want to change the worksheets within your If block, you can just slap on a sheet variable.
Also what's up with this -
Application.Goto (ActiveWorkbook.Sheets("SCRIPT").Range("A1"))
Application.Goto (ActiveWorkbook.Sheets("CHAIN").Range("A1"))

The second one negates the first one, or are you just making sure nothing is still selected on those sheets? Nothing should be .Selected anyway.
If you need some more speed try doing these along with ScreenUpdating
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False

Just remember to turn them back on when you're finished.
One more thing, I don't see any error handling, what happens if there's an error? It will stop and you'll need to loop through all the sheets again once it's fixed.
Oh - also use Option Explicit on the top, you may have caught some of the things I mentioned just by compiling with that engaged.


Verify user account on button click with an AJAX call

From: http://api.jquery.com/jquery.ajax/

  Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

So, it looks like you should do:

$.ajax({ url: "/submit/checkuser" })
 .done(function(userStatus) {
     ... function to complete when done ...
 }).fail(function(e) {
     ... function to complete on error ...
 }).always(function() {
     ... move all your code that needs to be done regardless of error or completion,
     and re-run your timer here
 });

Otherwise, if you are using a version of jQuery that does not include this more-normal looking functionality, there is a "complete" callback available that you can supply just as you are supplying "success" and "error" callbacks, which you can use to do all your cleanup and re-start your timer.


You test the return value of fwrite, which is good. However, fread may fail as well. Since fread doesn't distinguish error from end of file, you should call ferror:

    while ((num_elements = fread(....)) > 0) {
        ....
    }
    if (ferror(src)) {
        handle_error
    }

fprintf(stdout), while technically valid, looks strange. A printf suffices.
cpy_buf doesn't belong to main. Define it directly in cpy.
Prefer passing file names via command line arguments.
The "Aborting..." message doesn't have a terminating newline, and the next prompt will be printed on the same line (on any shell except cmd.exe). Make a habit to print a newline at the end of the message.


Finding equivalent to % for the inner if clauses

The answer of t3chb0t provides a solution in the right direction. My point of "critique" with that solution is the overdose on LinQ for a simple solution like checking if a collection of numbers contains a certain number.

The point of predefining the collection is a good idea. I would do it like this:

var classesForOne = new [] { 0, 3, 6, 9, 12, 15, 18 };
var classesForTwo = new [] { 1, 4, 7, 10, 13, 16, 19 };
var classesForThree = new [] { 2, 5, 8, 11, 14, 17, 20 };

Now you can check if the variable i is present in a collection. This can be done like this:

if(iNumberOfClasses >= 1)
{
    if (classesForOne.Contains(i))
        filteredTypes.Add(allTypes[i]);
}

Writing it this way, you can combine the two if statements in one simpler statement:

if(iNumberOfClasses >= 1 && classesForOne.Contains(i))
{
    filteredTypes.Add(allTypes[i]);
}

So the whole code with loop would now look like following:

var classesForOne = new [] { 0, 3, 6, 9, 12, 15, 18 };
var classesForTwo = new [] { 1, 4, 7, 10, 13, 16, 19 };
var classesForThree = new [] { 2, 5, 8, 11, 14, 17, 20 };

for(int i = 0; i < allTypes.Length; i++)
{
    if(iNumberOfClasses >= 1 && classesForOne.Contains(i))
        filteredTypes.Add(allTypes[i]);

    if(iNumberOfClasses >= 2 && classesForTwo.Contains(i))
        filteredTypes.Add(allTypes[i]);

    if(iNumberOfClasses == 3 && classesForThree.Contains(i))
        filteredTypes.Add(allTypes[i]);
}

Edit:

The mod implementation:

This edit is not mandatory, it is just provided as extra information to your secondary question about using the modulus. You CAN implement the modulus-way to achieve the same result. I'm not saying this is a better implementation, just showing how it can be done :) . Let's look at each of the three cases.

{ 0, 3, 6, 9, 12, 15, 18 }

If i is divisible by 3, meaning it has a remainder of 0, it is in the first collection of numbers.

{ 1, 4, 7, 10, 13, 16, 19 }

If i is divided by 3, remainder 1, it is in the second collection.

{ 2, 5, 8, 11, 14, 17, 20 }

And for the last, if i is divided by 3, remainder 2, it is in the third.

Of course using this method you're not validating if the number i is valid within the range. If for example i is 22 (remainder is 1), the result would say that it is present in the second collection. You'll have to build in an extra check for this. Here's the implementation:

for(int i = 0; i < allTypes.Length; i++)
{
    if(iNumberOfClasses >= 1 && (i <= 18 && i % 3 == 0))
        filteredTypes.Add(allTypes[i]);

    if(iNumberOfClasses >= 2 && (i <= 19 && i % 3 == 1))
        filteredTypes.Add(allTypes[i]);

    if(iNumberOfClasses == 3 && (i <= 20 && i % 3 == 2))
        filteredTypes.Add(allTypes[i]);
}

In this way, you don't need to predefine a collection, the counterpart is that you have to built an extra check to set the maximum allowed number. Hope this explains it. :)


Python web page to display SSL certificate status

It just feels like I wrote some eye searing python to cobble something together...I am not even sure if a "Web Framework" would help or frankly why...I've looked into some of them but it's not sinking in.

I think it would definitely be better then what you have currently

I can recommend flask, a small web microframework.

Pretty easy to use and has plenty of features, it will handle serving the page, making nicely formatted html pages, handling routes.

If you want some pretty tables you could even use Flask-Table

But something simple as this should even work,

app.py

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def ssl_status():
    ssl_connections = [
        ["url.url", 165, "some-date-2019", "OK"]
    ]
    return render_template('ssl_status.html', ssl_connections=ssl_connections)

if __name__ == '__main__':
    app.run()

ssl_status.html

<!doctype html>
<title>SSL Status page</title>

    {% for row in ssl_connections %}

        {% for item in row %}
        {{ item }}
        {% endfor %}

    {% endfor %}

You'd need some .css probably to make the colors work, and some other stuff to make it look the same as your example.


Is this a good way to handle Web API UriTemplates?

There is an easier way. You can use uri templates to help you by making both handling methods operations.

[ServiceContract]
public class ContactsApi
{
    [WebGet(UriTemplate="{id}")]
    public string GetById(int id)
    {
        //return by id
    }

    [WebGet(UriTemplate="{first} {last}")]
    public string GetByName(string first, string last)
    {
        //return by name
    }
}

If you do a GET on /contacts/Matt%20Phillips the second method will get invoked.


The most obvious omission is error handling. You don't handle curl errors or xml parsing errors.

A REST api is like any other external service you might use in your application (such as a database). You might consider creating a client library for it (first check to see if one does not already exist for the service in question). Example usage with the implementation details neatly tucked away:

<?php
//read these values from your configuration and set here
$connection = array(
    'user' => '',
    'pass' => '',
    'baseUrl' => '',
    'version' => ''
);
try {
    $client = new FooClient($connection);
    $container = $client->getContainer('27-95');
    if ($container) {
        //do something with the fetched container
    }

    $sample = $client->getSample('DOR6A12');
    if ($sample) {
        $sample->setName('new name');
        $client->saveSample($sample);
    }
} catch (FooClientException $e) {
    //handle accordingly
}

I'm assuming that the client will return mapped objects for the getContainer and getSample methods. These mapped objects would be instances of php classes which are part of this client library. The xml responses returned by the service would be mapped to to these returned objects. That way, you are not directly dealing with the xml here, rather those details are dealt with in your client library (errors are handled there too with an appropriate exception being thrown if need be).


Implementation of Observer Pattern in C++14

I'm not sure we really need a base Observable class to inherit from anymore, because with lambdas and function type erasure, this pattern has become more or less trivial.

But if you want to do it that way, I think you can simplify and generalize it a bit more, by relaxing constraints in addObserver's signature (which I renamed attach because it's the canonical name if I'm not mistaken):

#include <iostream>
#include <functional>

class Observable {
    using Callback = std::function<void(void)>;
    std::vector<Callback> notifications;
public:
    void attach(Callback c) { notifications.push_back(c); }
    void notify() { for (auto& c : notifications) c(); }
};

struct Buzzer {
    void go() { std::cout << "drrrr... drrrr...\n"; }
};

struct Rooster {
    void sing() { std::cout << "Cocorico!\n"; }
};

struct Sun : public Observable {
    void rise() { std::cout << "Waoooh! the sun's rising!\n"; notify(); }
};

int main() {
    Sun sun;
    Buzzer buzzer;
    Rooster rooster;

    sun.attach([&buzzer] {buzzer.go();});
    sun.attach([&rooster] {rooster.sing();});
    sun.rise();
}


Copy Multiple Excel Tables to VBA Dictionary

Option Explicit!

Suggestion #1: Put Option Explicit at the top of the module. Always!

This would have prevented the very embarrassing error of Dict.Add Ary(I, 1), MyClass. Upon which I see that this code would neither compile nor run unless this Class is a default instance.

Function or Sub?

If you are only returning one value, then you can use a Function, not a Sub.

Keep it Simple!

You have made this more complicated than required. You already pass in a ListObject, and you want the DataRange. Just do that instead of calling custom classes that return something that you then have to modify/clean up.

Dim ThisList As TableHandler
Set ThisList = New TableHandler

Dim Ary As Variant

If ThisList.TryReadTable(Tbl, False, Ary) Then
    [...]

becomes

Dim Ary As Variant
If Not Tbl is Nothing then
    Ary = Tbl.DataRange
    [...]

In addition, you have pInitialized = True but you don't declare or use pInitialized anywhere else.

Interface or encapsulate?

This is a classic example where the use of an interface would greatly assist.
Create an interface class which basically sets up a contract for some of the methods to be used. In other words, make sure that all of these 10-12 Classes you mention have the right method or property so that you can call and create as required.

Public Sub MakeDictionary( _
    ByVal Tbl As ListObject, _
    ByRef Dict As Scripting.Dictionary)

Can become

Public Sub MakeDictionary( _
    ByVal Tbl As ListObject, _
    ByRef Dict As Scripting.Dictionary,
    ByVal SomeTag as <whatever type is most appropriate>)

And further in the code you can have

    For I = LBound(Ary, 1) To UBound(Ary, 1) '<- remember - we fixed this in my comment above!
        Dim ThisClass As IClass
        Select Case SomeTage
            Case TagA
                Set ThisClass = New MyClass1
            Case TagB
                Set ThisClass = New MyClass2
        End Select

        'ThisClass.Field1 = Ary(I, 1)
        'ThisClass.Field2 = Ary(I, 2)
        ThisClass.RelevantFillMethod(Ary(I, 1),Ary(I, 2))

        If Dict.Exists(Ary(I, 1)) Then ' Just in case there is some sort of transform?
            MsgBox "Entry already exists: " & Ary(I, 1)
        Else
            Dict.Add Ary(I, 1), ThisClass
        End If
    Next I

Now, if the Interface had a factory method which created a new version of the relevant class - you could dispense with the Dim and pass the MyClass1 instance as a parameter, calling MyClass1.New as necessary.

' Class IClass
Option Explicit

Public Function NewMe() As IClass
End Function

Public Sub RelevantFillMethod(val1 As Variant, val2 As Variant)
End Sub

And

' Class Class1
Option Explicit
Implements IClass

Private p_V1 As Variant
Private P_V2 As String

Public Function EverythingElse()
    '[...]
End Function

Private Function IClass_NewMe() As IClass
    Set IClass_NewMe = New Class1
End Function

Private Sub IClass_RelevantFillMethod(val1 As Variant, val2 As Variant)
    p_V1 = val1
    P_V2 = CStr(val2)
End Sub

Subs and functions!

Of course, you can make this a bit easier by addressing the single responsibility concept and using logical functions. However, in the OP there is not enough information to understand where this logic break is.

Identify and loop through tables
    Create array from table '<= can be a function that returns an array - single responsibility
    Identify relevant Class
    Update Dictionary based on array '<= single responsibility,
        'parameters could be the array, the dictionary and
        'the instance of the class based on the interface

For example

Sub UpdateDictionary(ByVal Ary as Variant, ByRef Dict as Dictionary, ThisClass as IClass)
    For I = LBound(Ary, 1) To UBound(Ary, 1)
        If Dict.Exists(Ary(I, 1)) Then
            MsgBox "Entry already exists: " & Ary(I, 1)
        Else
            Set ThisClass = ThisClass.NewMe
            ThisClass.RelevantFillMethod(Ary(I, 1),Ary(I, 2))
            Dict.Add Ary(I, 1), ThisClass
        End If
    Next I
End Sub

Final comments

What I have suggested above may not be the most elegant - but it is a start. Making something generic is about being able to abstract to the relevant layer.


This being Python, it should be relatively easy to present the illusion of an infinite tape, at least in the positive direction.  I don't see reason that cell_amount has to be specified, and the user shouldn't have to worry about such details.

Your input and output routines are wrong:

The . instruction should print one character, interpreting the cell value as an ASCII code.  Instead, you print the cell value as a base-10 number, followed by Newline.
The , instruction should read one character, storing its ASCII code as the cell value.  Instead, you read a string, and try to parse it as an integer.

while True: … is a lie.  What you really mean is while step < steps: ….  Then you can get rid of the if step == steps: exit(0) at the end of the loop.


Scrape data from website into dataframe(s) using Split function

Don't parse HTML manually, you should use the BeautifulSoup module!
import should be at the top of the file
Use a if __name__ == '__main__' guard
Functions and variable should be snake_case

First you can rewrite the getTable() alot using the BeautifulSoup module

import requests
from bs4 import BeautifulSoup

url = "http://webscraper.io/test-sites/tables"
soup = BeautifulSoup(requests.get(url).text, 'html.parser')
for table in soup.select('.table'):
    new_table = [[c.text for c in row.find_all('td')] for row in table.find_all('tr')]

The only problem is that it will also give back None values in the table, so we'd need to catch the None values and only yield when the list is not filled with None

Revised Code

import requests
import pandas as pd
from bs4 import BeautifulSoup

def parse_table(table):
    for row in table.find_all('tr'):
        col = [c.text for c in row.find_all('td')]
        if not all(c is None for c in col):
            yield col

def scrape_tables():
    url = "http://webscraper.io/test-sites/tables"
    soup = BeautifulSoup(requests.get(url).text, 'html.parser')
    for table in soup.select('.table'):
        parsed_table = [col for col in parse_table(table)]
        df = pd.DataFrame(parsed_table, columns=["#", "First Name", "Last Name", "User Name"])
        print()
        print(df)

if __name__ == '__main__':
    scrape_tables()


So your Init threw me off, initially I thought this class was doing something, but it was doing something else (not your fault, totally mine).

Here's how I would handle this:

Get rid of asDBType and just return the Status, we'll see how in a moment.
Don't call the private member type if the database member is Name, call it name.
Use CallerMemberNameAttribute so you don't need a magic string.

You want type-safety at compile time, against something that's inherently unsafe, so we have to cheat quite a bit to make that happen.

We're also going to use some Reflection - doing so means we can eliminate the List<StatusEnum> members, and replace a lot of this class with a couple quick calls.

public class StatusEnum
{
    private static Dictionary<string, Status> _lookup = new Dictionary<string, Status>();
    private static Status _get([CallerMemberName]string name = null) =>
        _lookup.Length > 0 ? _lookup[name] : throw new InvalidOperationException($"The method '{nameof(Init)}' has not been called.");
        // `CallerMemberNameAttribute` gives us the name of whatever
        // method or property called this method, which means since
        // our property calls `_get()`, we get the name of that
        // property implicitly

    public static Status ACTIVE => _get();
    public static Status COMPLETED => _get();
    public static Status DELETED => _get();
    public static Status INPROGRESS => _get();

    public static void Init(ECIContext ctx)
    {
        foreach (var prop in typeof(StatusEnum).GetProperties())
        {
            var name = prop.Name;

            // Assuming `ctx.Status` has a `SingleOrDefault`
            var status = ctx.Status.SingleOrDefault(x => x.Name == name);
            if (status == null) { throw new ArgumentException($"The value '{name}' is not a valid '{nameof(Status)}'."); }

            _lookup.Add(name, status);
        }
    }
}

Realistically, your StatusEnum class is a bunch of helper stuff, so you don't really need instance members, and you don't really want to keep an instance of this class, you care about the Status class. This is similar to how I do Setting objects in Entity Framework, though my setup was more complex.

Your version requires adding a property with a self-referencing name, this version eliminates that.

public static Status ONHOLD => _get();
public static readonly StatusEnum ONHOLD = new StatusEnum("ONHOLD");

Also, in your version, C#6.0 introduced nameof() which would allow you to safely initialize:

public static readonly StatusEnum ACTIVE = new StatusEnum(nameof(Active));

The other advantage to this version is you'll always be sure that you have a valid Status object, no need to asDBType, which means we can make this generic for your other situations:

public abstract class ItemizedEnum<TItem, TClass>
    where TClass : ItemizedEnum<TItem, TClass>
{
    private static Dictionary<string, TItem> _lookup = new Dictionary<string, TItem>();
    protected static TItem Get([CallerMemberName]string name = null) =>
        _lookup.Count > 0 ? _lookup[name] : throw new InvalidOperationException($"The '{nameof(Init)}' method MUST be called first.");

    protected abstract TItem GetFromDatabase(ECIContext ctx, string name);

    public static void Init(ECIContext ctx)
    {
        var classInstance = Activator.CreateInstance<TClass>();
        foreach (var prop in typeof(TClass).GetProperties())
        {
            var name = prop.Name;
            var obj = classInstance.GetFromDatabase(ctx, name);
            if (obj == null || obj.Equals(default(TItem)) == true) { throw new ArgumentException($"The value '{name}' is invalid for '{typeof(TClass).Name}'"); }
            _lookup.Add(name, obj);
        }
    }
}

Finally, in StatusEnum:

public class StatusEnum : ItemizedEnum<Status, StatusEnum>
{
    public static Status ACTIVE => Get();
    public static Status COMPLETED => Get();
    public static Status DELETED => Get();
    public static Status INPROGRESS => Get();

    protected override Status GetFromDatabase(ECIContext ctx, string name) =>
        ctx.Status.FirstOrDefault(x => x.Name == name);
}

This decreases the level of redundancy, the class only needs to implement a GetFromDatabase(ECIContext, string) method, and we now no longer care about any of that in StatusEnum itself, just what values it contains. We can then build other ItemizedEnum classes:

public class StateEnum : ItemizedEnum<State, StateEnum>
{
    protected override State GetFromDatabase(ECIContext ctx, string name) =>
        ctx.State.FirstOrDefault(x => x.Title == name);

    public static State OtherTest => Get();
}

And we get the same type-safety. Now a test of your live examples might be:

public class StatusEnum : ItemizedEnum<Status, StatusEnum>
{
    protected override Status GetFromDatabase(ECIContext ctx, string name) =>
        ctx.Status.FirstOrDefault(x => x.Name == name);

    public static Status Test => Get();
}

public class StateEnum : ItemizedEnum<State, StateEnum>
{
    protected override State GetFromDatabase(ECIContext ctx, string name) =>
        ctx.State.FirstOrDefault(x => x.Title == name);

    public static State OtherTest => Get();
}

StatusEnum.Init(new ECIContext());
StateEnum.Init(new ECIContext());
Console.WriteLine(StatusEnum.Test.Name);
Console.WriteLine(StateEnum.OtherTest.Title);


Is this a good object oriented design for a file validator?

That isn't OOP, that's procedural, with a thin wrapping that looks like OOP.  OOP will require that your validation be done on objects that share data and behavior.

Depending upon your file, this may or may not make sense.

OTOH, good procedural code is definitely better than the common PHP "just run it all together inside a single page" that frequently gets used.

EDIT: Expanding my answer after a comment.

First off, I should be clear that I wasn't criticizing your existing code, just saying they don't make it OOP. OOP is about data and behavior not just having things called classes and constructors.

Secondly, EDI probably means transactions of different types with well definined behavior for the various types -- that would be an opportunity to use/benefit from OOP.  I would try to design a base class or interface that can be applied to all lines/transactions and then have derived classes for the header/footer and body lines.

You need to focus on the similaririty of your data and your process for handling/validating it, your OOP implemention will come out of that.  It's a little to early to be asking about OOP.


The reason the position of the paddle doesn't update is because the paddle that you adjust the velocity of in class Shapes is a different instance of paddle than the one you're drawing.
Make these changes to class Shapes:

delete field: private Paddle paddle = new Paddle();

add line
Paddle paddle = panel.paddle;

in the constructor after you declare Panel panel = new Panel();

Additionally, you will likely want to switch your yVelocity values, as pressing "down" sends the box up, and vice versa.