Numerical precision of implementation for convex quadrilateral area

Debugging floating-point precision issues is, as @Bobby mentioned, off-topic for this site, so this is going to be just a code review :)

The first thing that strikes me, is the cryptic two-letter identifiers.

Let's start with the signature for GetTriangleArea. You're taking 9 parameters, this is bad. In reality you really need 3 groups of 3 numbers. Your code has failed to make this abstraction, and this is why you end up with a1-a2-a3 -style identifiers.

What if GetTriangleArea had a signature like this?

internal static double GetTriangleArea(Point3D pointA, Point3D pointB, Point3D pointC)

Given a Point3D struct with members X, Y and Z, the rest of the code would be much less cryptic.

The same applies to GetConvexQuadrilateralArea, which could look much less crowded like this:

internal static double GetConvexQuadrilateralArea(Point3D pointA, Point3D pointB, Point3D pointC, Point3D pointD)

Lastly, I'm not sure, but I think GetConvexQuadrilateralArea is lying - the method isn't actively verifying the convex-ness of the points it's given, which may or may not be problematic.


Python static / instance method or function?

Since you have classes that represent the configuration of various server types, you should keep the path structure in them and uses it from them. pathlib provide an abstraction over windows and unix file paths that you can store in these classes and reuse it from FileInfo.

import pathlib

class FileInfo(object):
    def __init__(self, server_info, folder_path, file_name):
        self.server_info = server_info
        self.folder_path = folder_path
        self.file_name = file_name

    def get_file_full_path(self):
        return self.server_info.paths(self.folder_path, self.file_name)

class ServerInfo(object):
    pass

class WindowsServerInfo(ServerInfo):
    paths = pathlib.PureWindowsPath

class SFTPServerInfo(ServerInfo):
    paths = pathlib.PurePosixPath

However, if the only purpose of the FileInfo class is to retrieve a path from its arguments, then you’re better of putting this function directly into ServerInfo:

class ServerInfo(object):
    def get_file_full_path(self, folder_path, file_name):
        return self.paths(folder_path, file_name)

class WindowsServerInfo(ServerInfo):
    paths = pathlib.PureWindowsPath

class SFTPServerInfo(ServerInfo):
    paths = pathlib.PurePosixPath

And you could improve it by allowing multiple path segments:

class ServerInfo(object):
    def get_file_full_path(self, *path_segments):
        return self.paths(*path_segments)

class WindowsServerInfo(ServerInfo):
    paths = pathlib.PureWindowsPath

class SFTPServerInfo(ServerInfo):
    paths = pathlib.PurePosixPath

But it seems that you're only using Python 2, so pathlib may not be available. You can still use your '%s/%s' or '%s\\%s' style approach, but you will loose some path simplifications provided by pathlib:

class ServerInfo(object):
    def get_file_full_path(self, *path_segments):
        return self.path_delimiter.join(*path_segments)

class WindowsServerInfo(ServerInfo):
    path_delimiter = '\\'

class SFTPServerInfo(ServerInfo):
    path_delimiter = '/'

Oh, and talking about '%s/%s' or '%s\\%s', str.format is the prefered way over % formating syntax.


Review

Function hasAceInHand could be boiled down to a one-liner using array.find. It returns the first element of the array that passes the condition x => x.face === "A" provided.

const hasAceInHand = (cardsOnHand) => {
  return cardsOnHand.find(x => x.face === "A") != null;
}

Function countHandValue iterates the items, and calls the other function which iterates the items nested in the outer iteration if (sum > 21 && hasAceInHand(cardsOnHand)) { ... You could just keep track of aces to avoid iterating the items more than once.

Alternative for countHandValue

In black-jack, at most 1 ace could have value 11, all other aces in the hand must have value 1, else 21 would get exceeded (11 + 11 > 21). I would change the default value of an ace to 1.

switch (face) {
    case "A":
        this.faceValue = 1;
        break;

As a first step, Array.reduce could be used to calculate the sum of card values.

const countHandValue = (cardsOnHand) => {
  return cardsOnHand.reduce((sum, current) => {
    sum += current.faceValue;
    return sum;
  }, 0);
}

Then we can implement a relaxation allowing at most 1 ace to get value 11.

const countHandValue = (cardsOnHand) => {
  let ace;
  let value = cardsOnHand.reduce((sum, current) => {
    ace |= current.faceValue === 1;
    sum += current.faceValue;
    return sum;
  }, 0);
  if (ace && value + 10 <= 21) {
    value += 10;
  }
  return value;
}

And we also no longer need to call hasAceInHand as we're tracking the ace inline.


Partial view for frequently used drop down lists

I'm new to MVC (relatively), but I don't think I'll ever plan on doing too much in a view. In my understanding, it's merely a template for an object (view model) you throw at it. There shouldn't be much server-side functionality in there at all. Getting data from a database and selecting a SelectList from this collection is too much. There isn't enough separation between concerns of presentation and functionality.

Get that database call into a controller (or better still, a business layer) and keep your views simple. Then you can decide whether you want to call this new action asynchronously or not.


Since the classes are all subclasses of _MyBase, they can be accessed via _MyBase.__subclasses__() after they have been imported:

for (module_loader, name, ispkg) in pkgutil.iter_modules([pkg_dir]):
    importlib.import_module('.' + name, __package__)

all_my_base_classes = {cls.__name__: cls for cls in base._MyBase.__subclasses__()}

For importing the modules, I followed the advice of Nihathrael.


Core Data code for manually creating a lot of entries from old ones

The first big problem I see with this code is here:

int i = 0;

for (NSManagedObject *media in mediaSet) {
    // stuff
    newMedia.positionInEntry = [NSNumber numberWithDouble:i + 1];
    // more stuff
    i++;
}

First of all, if positionInEntry is a property intended to hold some sort of index or something for your Media class, then it should be of the same type that collections tend to use for their indexing: NSUInteger.  Although... the object itself probably doesn't need to know what position it is in the array, and as this could change, it's probably best to just not have this property at all.

Next, i is defined as an int, and 1 is an int literal, so we're creating the NSNumber in the wrong way.  We should be doing this (if we're going to continue to keep this positionInEntry property):

newMedia.positionInEntry = [NSNumber numberWithInt:i + 1];

Finally, we really shouldn't be doing this in this manner at all.  If we want to know what index we're working with, we should use a traditional for loop.

for (int i = 0; i < [mediaSet count]; ++i) {
    NSManagedObject *media = mediaSet[i];
    // stuff
    newMedia.positionInEntry = @(i+1);
    // more stuff
}

However, there's a slightly better option.

It is good to use a forin loop where we can, because this actually is faster than a traditional for loop in Objective-C.  We still don't want to rely on i however, for a couple of reasons, right now, I'll say, the most important of which is readability.  But there is this option:

for (NSManagedObject *media in mediaSet) {
    // stuff

    NSUInteger index = [mediaSet indexOfObject:media];

    newMedia.positionInEntry = @(index + 1);

    // more stuff
}

We can call indexOfObject: on an NSArray and it will return the first index it finds that object at.  As a note, this method returns NSNotFound if the object isn't found in the array, but in a forin loop, this should hopefully never be the case.


It would probably be a good idea to generalize your code so you can use it with different values. I'm not suggesting you support the full calc() syntax, but making it configurable at least could be useful if you plan on using it in more than one place.

For the code you have though, I just have a couple suggestions:

I typically avoid underscores in variable names, but that's just a preference (although one that a lot of style guides I've seen share).
Replace if (newwidth == "10"){} else with if (newwidth !== 10) {. Instead of doing nothing in the true case, switch the comparison and skip the else. You can also compare directly with the number 10 (using the strict equality operator) instead of doing a string comparison.
Function declarations are technically not legal inside if statements in ECMAScript (they are only allowed at the global scope, or the top level of a function). Browsers tend to support it as an extension, but they behave differently and it can cause problems, so it's best to avoid that. Function expressions are fine, so I assigned an anonymous function directly to window.onresize and called it through that. You could also assign the function to a variable (replace function resize() {...} with var resize = function() {...};).
Instead of calling document.getElementById('content') three times, store the style object in a variable and reference that. You'll gain a speed and file-size advantage.
Semicolons aren't needed after function declarations or after an if statement block.

Here's what I ended up with:

// CSS calc() replacement
function calcfailback() {
    var d = document.createElement('div');

    // 1
    var body = document.getElementsByTagName('body')[0];
    body.appendChild(d);
    d.style.visibility = 'hidden';
    d.style.width = "-webkit-calc(10px)";
    d.style.width = "-o-calc(10px)";
    d.style.width = "-moz-calc(10px)";
    d.style.width = "calc(10px)";
    var newwidth = d.offsetWidth;

    // 2
    if (newwidth !== 10) {
        // 3
        window.onresize = function() {
            // 4
            var contentStyle = document.getElementById('content').style;
            contentStyle.height = window.innerHeight - 40 + 'px';
            contentStyle.width = window.innerWidth - 300 +'px';
            contentStyle.height = window.innerHeight - 40 + 'px';
        };
        window.onresize();
    } // 5
    body.removeChild(d);
} // 5
window.onload = calcfailback;


Coordinates Struct for Flow Field Pathfinding... am I doing this right?

I have no knowledge about Unity3d, so here are some general comments.
If world.SectorSize is constant throughout the session, you can change some of the properties to readonly fields and calculate them in the constructor:
public readonly int SectorX;
public readonly int SectorY;
public readonly FlowFieldSector Sector;
...

public Coordinates(int worldX, int worldY, FlowFieldWorld world)
{
  this.worldX = worldX;
  this.worldY = worldY;
  this.world = world;
  SectorX = worldX % world.SectorSize;
  SectorY = worldY % world.SectorSize;
  Sector =  world.Sectors[worldX / world.SectorSize, worldY / world.SectorSize];
}

Doing so with Sector, Cost, Integration and Flow requires of cause that these objects are reference types and not replaced - if they are updated while the Coordinates instance lives. It is probably just a micro optimization - but everything counts?

public bool Equals(Coordinates other)
{
  return worldX == other.worldX && worldY == other.worldY;
}

This is actually an implementation of IEquatable<Coordinates> so you can add this interface to the inheritance list:
public struct Coordinates : IEquatable<Coordinates>

In respect to the DRY-principle you could do the following changes:
The copy constructor can call the other constructor:
public Coordinates(Coordinates source) : this(source.worldX, source.worldY, source.world)
{
}

The comparison operators can call Equals(Coordinates other):
public static bool operator ==(Coordinates left, Coordinates right)
{
  return left.Equals(right);
}


Calculating the Percentage of a Pair Occurring Across a Lot of Lists

Creating your list of decks
"""-- ORIGINAL CODE --"""
#I'm not entirely sure how this works
#Somehow it takes everything with the same deckId (index:2) and puts them into one list
values = set(map(lambda x:x[2], decks))
newlist = [[y[1] for y in decks if y[2] == x] for x in values]

map() takes the function in the first argument, and applies it to every item in the iterable in the second argument.  In this case, each item is a (cardId, "card name", deckId) tuple, and  the function returns the value in index 2 of that tuple, namely deckId.  set() takes the iterable returned by map() and converts it into a set, which contains exactly one of each unique value in the iterable - in this case, each unique deckId.
Your second line uses two list comprehensions.  The outer one iterates over values (your set of deckIds) and for each deckId it uses another list comprehension to iterate over decks and returns index 1 of each tuple (namely "card name") if index 2 of the item equals the deckId currently being used from the outer list comprehension.
You could also write this line as a double for-loop:
newlist = []
for x in values:
    temp = []
    for y in decks:
        if y[2] == x:
            temp.append(y[1])
    newlist.append(temp)

But in general, this is pretty messy.  You loop over the entirely of decks in order to create values, then loop over values * decks.  That's very inefficent
You'd be much better off using a dictionary, where you can then fold this all into a single loop
deck_dict = {}
for (id, name, deck_id) in decks:
    if deck_id not in deck_dict:
        deck_dict[deck_id] = []
    deck_dict[deck_id].append(name)

You can even ditch the initial check to create the list if you use a defaultdict
from collections import defaultdict

deck_dict = defaultdict(list)
for (id, name, deck_id) in decks:
    deck_dict[deck_id].append(name)

However, this is still the wrong structure, because you don't actually cares about which cards are in each deck - you care about which decks contain each card.
from collections import defaultdict

card_dict = defaultdict(set)
for (id, name, deck_id) in decks:
    card_dict[name].add(deck_id)

Creating you superset
"""-- ORIGINAL CODE --"""
superSet = []
for l in newlist:
    for c in l:
        if c not in superSet:
            superSet.append(c)

Then you create loop through every item in an item in newlist to create your superSet.  You have the same number of items in items in newlist as you had in decks, just organized differently, so all you get for using it instead is a slightly more complicated for loop
superSet = []
for (id, name, deck_id) in decks:
    if name not in superSet:
        superSet.append(name)

Notably, since now you're iterating over decks, you could roll this into the same loop you used to create deck_dict.  But there's still room for improvement, because you made superSet a list, while it would make much more sense for it to be a set.
superSet = set()
for (id, name, deck_id) in decks:
    superSet.add(name)

Since a set only ever contains one of each unique value, this saves you from having to check whether each object is in superSet before you add it.  The operation x in s is a lot faster for a set than a list (O(1) on average instead of O(n)).
If superSet is a set, you can actually use the same assignment you were using earlier for values: superSet = set(map(lambda x:x[1], decks)).  Note that we're using x[1] here instead of x[2] because we want the card name instead of the deckId.  You can also replace map with a generator comprehension: superSet = set(x[1] for x in decks), which is generally considered more 'pythonic' than using map().
Counting your pairs
"""-- ORIGINAL CODE --"""
count = 0
for x in superSet:
    for y in superSet:
        if x is y:
            continue
        #print(x)
        #print(y)
        for d in newlist:
            #print(d)
            if x in d and y in d:
                count += 1
        deckPerc = count / len(newlist)
        if deckPerc != 0.0:
            print(count / len(newlist)) #needs to go into the db
        count = 0

Iterating over superSet twice like this actually gives you every pair you need twice - once as x='Shock' and y='Bolt', and once as x='Bolt' and y='Shock'.  Fortunately, the itertools library has you covered with the combinations() function.  And with card_dict providing the set of decks that contain each card, finding out the total number of decks that contain a pair is simply a matter of taking the union of the sets like so:
from itertools import combinations
for card1, card2 in combinations(superSet, 2):
    shared_decks = card_dict[card1] & card_dict[card2]
    count = len(shared_decks)
    if count > 0:
        print(f'{card1} + {card2}: {count}')

Now, rather than calculate the deck percentage, I merely used the count of decks that share the pair.  This is because I ditched deck_dict in favor of card_dict, and don't actually have a simple way of calculating the total number of decks at this point in the code.  This isn't a problem for the code shown, as if deckPerc != 0.0 is equivalent to if count != 0, but if you need the percentage for your actual use case, then we need to go back to before this loop and create it.  You can use deck_count = len(set(card[2] for card in decks)), or you can fold the set construction into the existing loop through decks to avoid having to loop through it twice.
Bringing it all together
from classes.general import Database
from collections import defaultdict
from itertools import combinations

def main():
    dbm = Database()
    with dbm.con:
        dbm.cur.execute("""SELECT c.id, c.name, ctd.deckId FROM cards c
        JOIN cardToDeck ctd ON ctd.cardId = c.id
        JOIN deckToEvent dte ON dte.deckId = ctd.deckId
        JOIN eventToFormat etf ON etf.eventId = dte.eventId
        WHERE etf.formatId = 5
        ORDER BY ctd.deckId""")
        decks = dbm.cur.fetchall()

        deck_set = set()
        card_set = set()
        card_dict = defaultdict(set)
        for card_id, card_name, deck_id in decks:
            deck_set.add(deck_id)
            card_set.add(card_name)
            card_dict[card_name].add(deck_id)

        deck_count = len(deck_set)

        for card1, card2 in combinations(card_set, 2):
            shared_decks = card_dict[card1] & card_dict[card2]
            deckPerc = len(shared_decks) / deck_count
            if deckPerc > 0:
                print(f'{card1} + {card2}: {count}') # needs to go into the db

if __name__ == "__main__":
    main()

And there you have it!  You have two loops, one of which iterates through decks once, and the other loops through N*(N-1)/2 items, where N is the number of unique cards.  Using sets and dicts mean that the time complexity of the operations inside the loops are all O(1), so this is pretty much as fast as you can make it.
Additional Notes
I know very little about databases, so there may be improvements possible in that area that I am unaware of.  I noticed that you kept the entirety of the code in the with block with the connection open, even though you never use it after you create decks.  This doesn't harm anything that I'm aware of, but it's good practice to exit a context as soon as you no longer need it (and it reduces the level of indenting your code is at, which is nice).  On the other hand, if you plan on using the connection to modify the database at the end of the code, then obviously leave everything as it is.
Style-wise, you could stand to improve your naming conventions.  values, newlist, and superSet are not very descriptive names.  Notice how I used deck_set, card_set, and card_dict to provide some indication as to what is in each object.  Additionally, most python style guides (in particular PEP 8 the style guide for Python's standard library) recommend using lower_case_with_underscores for the names of variables rather than camelCase as you are using.  You are of course free to pick any naming convention you want, but you should conciously choose your convention, and (unless you have a reason not to) it is best to use one of the standard conventions.


Applying a string-identified effect on an image

IMO your second solution (using a dict to store callables) is exactly right.

The first solution, with a series of if/else statements is not only inefficient, it also encourages and facilitates writing unrelated code inside the apply_fx function itself. To wit:

elif fx == 'b&w':
    return contrast(grayscale(img), 2)

Once you have put something other than a simple return func(img) in the code, a future maintainer will be tempted to "just write this inline here" rather than creating a lambda or a named function to encapsulate their code:

elif fx = 'grayscale':
    from thirdpartymodule import grayscale, formatconverter

    gsh = grayscale.Handle()
    img3p = formatconverter(img)
    result = grayscale.grayscale(gsh, img3p)
    return formatconverter(img3p, format=img)

Your second alternative, on the other hand, has a much more restricted, and thereby much cleaner interface: all operations must be encapsulated as callables.

Now, they could be functions, or they could be lambdas. They could be functools.partials or dynamically loaded or web api calls to a satellite orbiting planet Nebulon. But from the maintenance point of view, "create a callable, plug it in here with a name" is as good as you're likely to get. You could even do it dynamically, in response to a configuration file or plugin module:

def img2grayscale(img):
    from thirdpartymodule import grayscale, formatconverter

    gsh = grayscale.Handle()
    img3p = formatconverter(img)
    result = grayscale.grayscale(gsh, img3p)
    return formatconverter(img3p, format=img)

effects['grayscale'] = img2grayscale


Some Minor Points

(+ x 0) and (+x) can be replaced by just x, in (get-in board[(+ x 0) (+ x 0)])) and (get-in board [(+ x) (- 2 x)])) respectively.

You can omit the nil in else position in if : (if row ... nil) \$\rightarrow\$ (if row ...)

Idiomatic way of checking if something is one of a number of things is using a set of those values as a predicate: (or (= dist [:o]) (= dist [:x])) \$\rightarrow\$ (#{[:o] [:x]} dist)

Rename row to something not misleading. Since you named the collection checks you could name the iteration variable check.

Your Questions

  Could I have created the diagonal vectors in one expression?

Yes. If you factor out the differing portions, namely [x x] and [x (- 2 x)], you get:

(let [diagonals (for [f [#(list % %) #(list % (- 2 %))]]
                  (for [x (range 3)]
                    (get-in board (f x))))

Since diagonals is already a sequence, you replace
checks (concat board [vl] [vr] columns)] with checks (concat board diagonals columns)

  Is there a way that I could avoid recursion with this problem?

Recursive processing of collections/sequences can be straightforwardly transformed to for expressions. Your :

(letfn [(check-board [[row & res]]
                (if row
                  (let [dist (distinct row)]
                      (if (or (= dist [:o]) (= dist [:x]))
                        (first dist)
                        (check-board res)))
                  nil))]
        (check-board checks))))

becomes this:

(first
  (for [row checks
        :let [dist (distinct row)]
        :when (or (= dist [:o]) (= dist [:x]))]
    (first dist)))

Note for is lazy, therefore (first (for ... is equivalent to your short-circuit return.

These Changes Applied Altogether

(fn [board]
  (let [diagonals (for [f [#(list % %) #(list % (- 2 %))]]
                    (for [x (range 3)]
                      (get-in board (f x))))
        columns (apply map vector board)
        checks (concat board diagonals columns)]
    (first
      (for [check checks
            :let [dist (distinct check)]
            :when (#{[:o] [:x]} dist)]
        (first dist)))))

Final Point

Also check out some, every?, keep, etc. which process collections with a predicate; and which this exercise probably wants you to learn. For example some is probably what you mean by short-cut evaluation reduce.


Displaying grades and calculating average grade

Let's go through refactoring your code step by step.

Get (almost) everything out of main()

main() should consist of the fewest lines to launch the program.  In this case you only need one.

    new UserInteraction().run();

Or, for clarity, you can break that into two lines.

    UserInteraction ui = new UserInteraction();
    ui.run();

You would then put everything from main() into a method called run().  The actually name of the new method is not important.  You can use start() if you like.

This step may seem almost silly at first, but it is very important.  First, all your methods and variables stop needing to be static.  For a beginner, you should avoid static as much as possible.  Second, it starts you thinking in an object oriented way (as opposed to procedurally).  Here's the first consequence of getting everything out of main():

    private double getAverage(int[] array)
    ...
    private double getSum(int[] array)

Notice that the methods are no longer static.  This is a good thing.  I also changed the accessibility to private.  Like static, a member should be private unless there is a good reason for it not to be.

Methods should do one thing well

So now we have a monolithic run() method doing all sorts of this.  Let's make run() only do one thing well.  We're shooting for something like this:

    private void run() {
        int choice = 0;

        do {
            showMenu();
            choice = scan.nextInt();

            switch (choice) {
            case 1:
                enterCourses();
                break;
            case 2:
                displayGrades();
                break;
            case 3:
                displayAverageGrade();
            }
        } while (choice != 4);
    }

Now run() only concerns itself with one thing: running the basic flow of the program.

Declare variables in the tightest scope possible

So where are all the variable declarations?  In general, you want to declare your variables "as close as you can."  Variable scope is a little tricky but for a beginner, try to declare your variables in the same block as their used.  (A block is roughly the code between braces {}).  choice needs to be declared where it is because it's used outside the switch block.

You only need one scanner object and it needs to be declared once.  It will be used in several methods, so it needs to be declared outside of all methods but inside of a class.

    public class UserInteraction {
        Scanner scan = new Scanner(System.in);

        public static void main(String[] args) { // ...

Let's leave the rest of the variable declarations and initializations for later and move code into our new methods.

    private void showMenu() {
        System.out.println("1. Enter a course name and a grade");
        System.out.println("2. Display all grades");
        System.out.println("3. Calculate the average grade");
        System.out.println("4. Exit program");
    }

    private void enterCourses() {
        System.out.println("Enter 10 subjects and their corresponding grades:");
        System.out.println();

        for (int i = 0; i < subjects.length; i++) {
            System.out.println("Subject:");
            subjects[i] = scan.nextLine();

            System.out.println("Grade:");
            grades[i] = scan.nextInt();
            scan.nextLine();

            if (i == (subjects.length - 1)) {
                System.out.println("Thank you!");
                System.out.println();
            }
        }
    }

    private void displayGrades() {
        System.out.println("Subjects" + "\tGrades");
        System.out.println("---------------------");

        for (int p = 0; p < subjects.length; p++) {

            System.out.println(subjects[p] + "\t" + "\t" + grades[p]);
        }
    }

    private void displayAverageGrade() {
        System.out.println("Total of grades: " + getSum(grades));
        System.out.println("Count of grades: " + grades.length);
        System.out.println("Average of grades: " + getAverage(grades));
        System.out.println();
    }

Now you can see that subjects and grades need to have class scope, that is, to be declared outside of all methods.  And we notice that declaring sum in run() is unnecessary because a local variable (one inside a method) will do.

Scanner weirdness

The scanner class has some oddities that I can't go into at length, but the long and the short is that you either put the line scan.nextLine() after each scan.nextInt(), or write a wrapper around scanner to hide the weirdness, or, like you did, have two scanner objects, one for strings and one for ints.  The wrapper is best, but as you can imagine, it's the hardest.  The nice thing though is if you write it correctly, you can reuse it anywhere.

Final thoughts

There is a lot more you can do, but I need to wrap this up.  Here are some things to think about.

You could put all your display into one class
What happens when you enter a non-integer into the menu or grades prompts?
There's a better way to store the subjects and grades.  What about a class that holds one subject and grade?  How does that change the program?
You have repeated code in your getAverage() and getSum() methods.  How can you get rid of that?

Okay, here's the "final" code, but not really final as there's a lot still to do:

import java.util.Scanner;

public class UserInteraction {
    private Scanner scan = new Scanner(System.in);
    private String[] subjects = new String[10];
    private int grades[] = new int[10];

    public static void main(String[] args) {
        new UserInteraction().run();
    }

    private void run() {
        int choice;

        do {
            showMenu();
            choice = scan.nextInt();
            scan.nextLine();

            switch (choice) {
            case 1:
                enterCourses();
                break;
            case 2:
                displayGrades();
                break;
            case 3:
                displayAverageGrade();
            }
        } while (choice != 4);
    }

    private void showMenu() {
        System.out.println("1. Enter a course name and a grade");
        System.out.println("2. Display all grades");
        System.out.println("3. Calculate the average grade");
        System.out.println("4. Exit program");
    }

    private void enterCourses() {
        System.out.println("Enter 10 subjects and their corresponding grades:");
        System.out.println();

        for (int i = 0; i < subjects.length; i++) {
            System.out.println("Subject:");
            subjects[i] = scan.nextLine();

            System.out.println("Grade:");
            grades[i] = scan.nextInt();
            scan.nextLine();

            if (i == (subjects.length - 1)) {
                System.out.println("Thank you!");
                System.out.println();
            }
        }
    }

    private void displayGrades() {
        System.out.println("Subjects" + "\tGrades");
        System.out.println("---------------------");

        for (int p = 0; p < subjects.length; p++) {
            System.out.println(subjects[p] + "\t" + "\t" + grades[p]);
        }
    }

    private void displayAverageGrade() {
        System.out.println("Total of grades: " + getSum(grades));
        System.out.println("Count of grades: " + grades.length);
        System.out.println("Average of grades: " + getAverage(grades));
        System.out.println();
    }

    private double getAverage(int[] array) {
        int sum = 0;
        for (int i : array) {
            sum += i;
        }
        return ((double) sum) / array.length;
    }

    private double getSum(int[] array) {
        int sum = 0;
        for (int i : array) {
            sum += i;
        }
        return sum;
    }

}


There are already two good answers here, but in addition:

Consider using the C# type keywords (bool intead of Boolean, int instead of Int32, string instead of String)
Consider using Contains instead of IndexOf
Consider introducing a method to set the port. If you can't modify HttpCommandBuilder, an extension method is one option.
Consider using object initializers

Here's an example with these suggestions put together:

public bool SwitchOn2(int portNumber)
{
    var builder = new HttpCommandBuilder(_ipAddress)
    {
        Command = HttpCommandBuilder.CommandType.SetPower
    };

    builder.SetPort(portNumber);
    var result = SendCommand(builder.GenerateUrl());
    return !string.IsNullOrEmpty(result) && result.Contains($"p6{portNumber}=1");
}

internal static class HttpCommandBuilderExtensions
{
    public static void SetPort(this HttpCommandBuilder builder, int portNumber)
    {
        if (builder == null)
        {
            throw new ArgumentNullException(nameof(builder));
        }

        switch (portNumber)
        {
            case 1:
                builder.Port1 = true;
                break;
            case 2:
                builder.Port2 = true;
                break;
            case 3:
                builder.Port3 = true;
                break;
            case 4:
                builder.Port4 = true;
                break;
            default:
                throw new ArgumentOutOfRangeException(nameof(portNumber));
        }
    }
}

For what it's worth, here are the code metrics from VS2015:

Member: SwitchOn2(int) : bool
Maintainability Index: 70
Cyclomatic Complexity: 2
Class Coupling: 2
Lines of Code: 5

Member: SetPort(this HttpCommandBuilder, int) : void
Maintainability Index: 62
Cyclomatic Complexity: 6
Class Coupling: 4
Lines of Code: 12

And for the original:

Member: SwitchOn(int) : bool
Maintainability Index: 45
Cyclomatic Complexity: 13
Class Coupling: 2
Lines of Code: 36


There are no docstrings. What do these functions do? What arguments do they take? What do they return?
Decorators are normally named after the effect they have on the decorated function. For example @functools.lru_cache adds an LRU cache to a function; @unittest.skip causes a test case to be skipped, and so on.

The effect of @from_iterable is that it converts the arguments into a tuple and passes that tuple as a single argument to the original function. I would not have guessed this functionality from the name; in fact I would have guessed the reverse (that it would convert a single iterable argument to individual arguments).
It was established in comments that the intention of this decorator is to transform a function into a pair of functions like chain and chain.from_iterable (where the original function becomes available under the latter name, and the new function under the former name).

The trouble with this is that chain was a mistake. If we only had chain.from_iterable, then we would not need chain, because we could just make a tuple: we'd write chain.from_iterable((arg1, arg2, ...)) instead of chain(arg1, arg2, ...). This is a trivial change to calling convention (just two parentheses) that does not need another function to support it. (For example, it would be ridiculous to have sorted and sorted.from_iterable.)

The Python developers were constrained by backwards compatibility to leave chain alone, and so the only thing they could do was add another function. I don't think they intended it to be a pattern to be followed (it's certainly not used anywhere else in the standard library). To this day, Python programmers looking for a "flatten" function are surprised to find that it already exists in the standard library under an obscure name.

Note that the code in the post does not actually use merge, it only uses merge.from_iterable. So the obvious thing to do would be to write merge so that it takes an iterable, and avoid the need for the @from_iterable decorator and its associated confusion.
Since headA and headB are not used independently of each other, you could change the calling convention for MergeLists so that it took an arbitrary number of linked lists, like this:

def merge_linked_lists(*lists):
    "Merge multiple sorted linked lists."
    return merge(map(iter_nodes, lists))

The expression:

str(i) for i in vals

can be written:

map(str, vals)

Or if you prefer the comprehension, then consider improving the name of the loop variable. The name i is conventionally used for an index, but here we are not iterating over indexes, but over values, so v or value would be clearer.
The code in merge does not use the built-in function id, so there is no need to respell the variable as id_ in order to avoid shadowing the built-in.
The function merge maintains two data structures. The dictionary source maps a source id to an iterator over the corresponding source, and the dictionary values maps a source id to the value at the front of the corresponding source. The code would be simplified if the two data structures were combined into one, like this:

def merge(iterables):
    "Merge sorted iterables."
    entries = {} # Map from id to [front value, id, iterator].
    for id, it in enumerate(map(iter, iterables)):
        try:
            entries[id] = [next(it), id, it]
        except StopIteration:
            pass
    by_value = operator.itemgetter(1)
    while entries:
        id, entry = min(entries.items(), key=by_value)
        value, _, it = entry
        yield value
        try:
            entry[0] = next(it)
        except StopIteration:
            del entries[id]

The runtime bottleneck is the call to min to find the entry with the smallest value. This takes time proportional to the number of remaining iterables, that is, \$O(l)\$.

We can improve this to \$O(\log l)\$ if we keep the entries in a heap, using the heapq module:

from heapq import heapify, heappop, heapreplace

def merge(iterables):
    "Merge sorted iterables."
    entries = []          # Heap of [front value, id, iterator].
    for id, it in enumerate(map(iter, iterables)):
        try:
            entries.append([next(it), id, it])
        except StopIteration:
            pass
    heapify(entries)
    while entries:
        value, _, it = entry = entries[0]
        yield value
        try:
            entry[0] = next(it)
            heapreplace(entries, entry)
        except StopIteration:
            heappop(entries)

This improves the overall runtime to \$O((n + l)\log l)\$.
This is already built into Python as heapq.merge. It's worth taking a look at the source code — the code in §8 above is a simplified version of this.


Sort array of objects with hierarchy by hierarchy and name

Since you have a representation of a tree i suggest using it,
then traverse it in pre-order

So if

[
    {_id:1, parent:0, name:'Z'},
    {_id:4, parent:0, name:'A'},
    {_id:2, parent:1, name:'H'},
    {_id:8, parent:2, name:'G'},
    {_id:5, parent:4, name:'M'},
    {_id:6, parent:4, name:'N'},
    {_id:3, parent:1, name:'Z'},
    {_id:7, parent:2, name:'L'}
]

lets build a tree like this

   [
      {_id:1, parent:0, name:'Z', children:
         [
             {_id:2, parent:1, name:'H', children:
                [
                   {_id:8, parent:2, name:'G', children: []},
                   {_id:7, parent:2, name:'L', children: []}
                ]
             },
             {_id:3, parent:1, name:'Z', children: []}
         ]
      },
      {_id:4, parent:0, name:'A', children:
         [
             {_id:5, parent:4, name:'M', children: []},
             {_id:6, parent:4, name:'N', children: []}
         ]},
   ]

my suggestion is like this:

var nodes = [
    {_id:1, parent:0, name:'Z'},
    {_id:4, parent:0, name:'A'},
    {_id:2, parent:1, name:'H'},
    {_id:8, parent:2, name:'G'},
    {_id:5, parent:4, name:'M'},
    {_id:6, parent:4, name:'N'},
    {_id:3, parent:1, name:'Z'},
    {_id:7, parent:2, name:'L'}
]
var tree = {_id:0};

var addChildrenToNode = function(node,cmp){
    var currentNodeId = node._id;
    node.children = [];
    nodes.forEach(function(e){
        if(e.parent === currentNodeId){
            e = addChildrenToNode(e);
            node.children.push(e);
        }
    });
    node.children = node.children.sort(cmp); // sort the children
    return node;
};

var cmp = function(a, b) {
    if(a.name < b.name) return -1;
    if(a.name > b.name) return 1;
    return 0;
};
tree = addChildrenToNode(tree,cmp);

Then you only have to do the pre-order traverse, like this:

var preOrderTraverse = function(node, fn){ // sends values of tree to fn in pre-order
    fn(node); //call at preorder
    if(node.children.length > 0){
        node.children.forEach(function(e){
            preOrderTraverse(e,fn);
        });
    }
}

preOrderTraverse(tree,
    function(node){ // do what you like with each node
        console.log(node);
    }
);


I'm not saying I like this but you could reuse the longest overload for the shorter ones. Here I took the one that takes three parameters.

public static string PatternReplace(
    this string seed,
    string pattern,
    Func<string, string> outPattern
)
{
    return seed.PatternReplace(pattern, (x, y, z) => outPattern(x));
}

public static string PatternReplace(
    this string seed,
    string pattern,
    Func<string, string, string> outPattern
)
{
    return seed.PatternReplace(pattern, (x, y, z) => outPattern(x, y));
}

Here's another small experiment with C# 7 where you could use anonymous tuples with only one method. But actually you could return a tuple in you current solution too.

public static class RegexStringExtensions
{
    public static string PatternReplace(
        this string seed,
        string pattern,
        Func<(string, string, string), string> outPattern
    )
    {
        return Regex.Replace(
            seed,
            pattern,
            m => outPattern((
                m.Groups[1].Value,
                m.Groups[2].Value,
                m.Groups[3].Value)
            )
        );
    }
}

Usage:

string val = "abcdef".PatternReplace(
    @"(ab)(cd)(ef)",
    t => t.Item1 + string.Concat(t.Item2.Reverse())
);


Passing a 1D array (single column of a Range object) to .NET to manipulate it without loops and returning it back to VBA

I don't know much about VBA or COM, so I'm going to focus on the single C# function:

If you know that all elements in the input sequence are of the same type, you should use Cast, not OfType. OfType filters out all elements of the wrong type, which could easily hide bugs.

You don't need to call ToList to start using LINQ methods, they work on anything that's IEnumerable<T>, which includes the results of Cast and OfType.

When calling a method like Distinct, you don't need to specify the type parameter (string in your case), the compiler is able to infer it itself.


Maximum product of 3 integers in an int array using Python

First, I'm not a Python guy, so please don't use anything I say to suggest style.  I'm trying to copy the style that you used with minor algorithmic differences.  I apologize if I make a mistake in doing so.

        if x > 0 and x > pos[0]:
            pos[2], pos[1], pos[0] = pos[1], pos[0], x
        elif x > 0 and x > pos[1]:
            pos[2], pos[1] = pos[1], x
        elif x > 0 and x > pos[2]:
            pos[2] = x
        elif x < 0 and x < neg[0]:
            neg[1], neg[0] = neg[0], x
        elif x < 0 and x < neg[1]:
            neg[1] = x

The x > 0 and x < 0 will have the same result throughout.  So we can do just one of each.

        if x > 0:
            if x > pos[0]:
                pos[2], pos[1], pos[0] = pos[1], pos[0], x
            elif x > pos[1]:
                pos[2], pos[1] = pos[1], x
            elif x > pos[2]:
                pos[2] = x
        elif x < 0:
            if x < neg[0]:
                neg[1], neg[0] = neg[0], x
            elif x < neg[1]:
                neg[1] = x

Now we do at most four comparisons and may do as few as two.  The original also did at least two and could do as many as eight (if greater than 0 but smaller than the three largest positive values).

We can actually reduce that and keep the same behavior

        if x > pos[2]:
            if x > pos[0]:
                pos[2], pos[1], pos[0] = pos[1], pos[0], x
            elif x > pos[1]:
                pos[2], pos[1] = pos[1], x
            else:
                pos[2] = x
        elif x < neg[1]:
            if x < neg[0]:
                neg[1], neg[0] = neg[0], x
            else:
                neg[1] = x

Still the same minimum of two, but the maximum drops to three.  We get the same behavior because both values are initialized to 0 and only move in one direction from there.  So if x > pos[2], it will also be greater than 0.  And x < neg[1] means that it is less than 0.

Perhaps you've noticed a problem though.  This code does not solve the problem correctly.  But it does produce the same result as your original code, so the bug is in the original code.

Bug

You have one unit test:

class TestHighestProduct(unittest.TestCase):
    def test_highest_product(self):
        self.assertEqual(highest_product([6, -1, -1, -2, 0]), 12)

But what if you add a second that says

        self.assertEqual(highest_product([-6, -1, -1, -2]), -2)

Your code will fail, returning 0 instead of -2.  This is because you initialize the arrays to 0, but you don't verify that there are non-negative members of the array.  0 is not a valid answer here.

If all the numbers are negative, then max_product is negative when

        max_product = max(pos[0] * pos[1] * pos[2], max_product)

So the first product is 0 * 0 * 0, which is 0.  0 will be greater than the product of any three negative numbers.  This incorrect answer will hide any possible correct answer.

        max_product = max([x * neg[0] * neg[1] for x in pos])

This is also wrong.  Even if you fix the other line, this may multiply the wrong three numbers.  For example, consider the input above.  The neg variable would hold -6 and -2 (the two smallest negative numbers).  So the max product would be -6 * -2 * -1 = -12.  But the actual answer should be -2 * -1 * -1 = -2, which is the product of the three largest numbers.

I'll leave it up to you to think through the ramifications of possible fixes.  You may want to consider when

        max_product = pos[0] * neg[0] * neg[1];

will give a different result than checking every x.  Also, how do you tell when pos[0] * pos[1] * pos[2] should and should not be zero?  In particular, consider if it matters if those three values are positive.

To what else could you initialize pos other than 0?


Designing stack and queue from scratch in C

casting and malloc

Unnecessary casting is generally frowned upon.  malloc returns a void*, so you don't need to cast it when you're assigned it.

cache = (NODE *) malloc(sizeof(NODE));

can just be

cache = malloc(sizeof(NODE));

Bug

You've got a bug in your dequeue function.  It doesn't update tail, which means that if you empty the queue, then start adding to it again you get errors.

enqueue_node(&Q_head, 1, &Q_tail);
printf("%d\n", dequeue(&Q_head));
enqueue_node(&Q_head, 1, &Q_tail);
printf("%d\n", dequeue(&Q_head));

Results in:

1
queue is empty ! ! !
-1

naming

It's a little odd that your push/enqueue methods have have a _node postfix, but your pop/dequeue methods don't.  I'd pick one and stick to it.

heads and tails

I'd rather see the head and tail of the queue wrapped up together in a queue structure.  This means that you only have to pass one parameter (the queue) into your enqueue/dequeue.  It also means that if you decide to change the way you implement the queue, your clients aren't impacted.

Are Queues Stacks?

As you've implemented it, it's possible to call stack functions on queue nodes and queue functions on stack nodes.  Is this really desirable?  If not, then making the change above to introduce a QUEUE structure that wraps a QNODE head and QNODE tail would mean that you would at least have some level of type safety and the compiler would warn you if you tried to call dequeue on your stack.


Common function to check if an element exists

You shouldn't even need to do a check for element exists before calling a jQuery method. All internal methods, and any plugin that follows good practices, just won't do anything at all if there are no elements in the set. So you could just simplify that part of the code down to (without the if):

$('.iCheck').iCheck({
    checkboxClass: 'icheckbox_minimal-blue',
    radioClass: 'iradio_minimal-blue',
    increaseArea: '20%' // optional
});


MCRYPT - are there any flaws or areas for improvement in this class?

I'm no security expert, however I think answering this would be fun!

I'll start off by doing my best answering your four questions:

The salt is unnecessary.

  a salt is random data that is used as an additional input to a one-way
  function... The primary function of salts is to defend against
  dictionary attacks versus a list of password hashes and against
  pre-computed rainbow table attacks.

These first few lines from the Wikipedia page for salts
basically sum it up. Because we're working with encryption
(opposed to say, hashing), the private key and the IV are our protection, not a salt. Reiterated over here on our Security Stack Exchange site.

This section elaborates on why it's necessary for hashing to
have salts:

  Without a salt, a successful SQL injection attack may yield easily
  crackable passwords.

Well, we just found out that having a salt infused really isn't very
beneficial. So if we eliminate the salt, then all we have left in
the encrypted output is the actual encryption, and the IV. Because
the IV size won't be changing in this example, it's A-OK to strip
the IV from the string using the IV size, and then the left over is
the message encrypted.
No, it cannot be unique. How would you decrypt it later on if the data left the class?

I'm not sure how you're creating the key, but I suggest something
such as to get a truly random one:

pack("H*", bin2hex(openssl_random_pseudo_bytes(32)));

Yes. Rijndael has three members in it's family: Rijndael-128,
Rijndael-192, and Rijndael-256 (there're more, but only these three are AES standard). However, each has a block size of
128 bits. So therefore Rijndael-256 with a (the only option) block
size of 128 would be the same as saying AES-256.

  The AES algorithm is capable of using cryptographic keys of 128, 192,
  and 256 bits to encrypt and decrypt data in blocks of 128 bits.

Via NIST
Depends. Where do you want to use it? In production, I'd say pick up a framework which already has this topic highly covered and critiqued. It also depends on what you're encrypting.

Other comments

private $eMethod = MCRYPT_RIJNDAEL_128;

never changes, so you could turn this into a constant.

return($newData);

It's up to you, but it's more common to leave the parentheses off.

Your whitespace and vertical alignment can have negative effects on readability. Of course, it's up to you, but you may want to check out some other coding styles.


ASP.NET REST controller with try-catch error handling

throw ex;

This is a fatal mistake. It'll create a new stack-trace and you won't be able to tell where the actual exception occured. If you want to rethrow it then use just

throw;

without  ex.


Justify text from a file using a LaTeX method

You should have a look at Python's official style-guide, PEP8. One of its recommendations is to use PascalCase for class names and lower_case for function and variable names.

Since you read all words into memory anyway, you can just write:

with open(in_file_name) as fp:
    self.words = fp.read().split()

This is because split splits by default on all whitespace (so both space and newlines). Also note that the default behaviour of open is to open a file in read mode, so "r" is also not needed here.

Caching (or memoization) of a functions return value is best done with a decorator. This way you avoid interleaving the actual implementation of the function with the caching. One example could be:

import functools

def memoize_method(func):
    cache = func.cache = {}

    @functools.wraps(func)
    def wrapper(self, n):
        if n not in cache:
            cache[n] = func(self, n)
        return cache[n]
    return wrapper

class JustifyText:
    ...
    @memoize_method
    def min_badness(self, i):
        if i == self.n:
            f, j_min = 0, self.n
        else:
            f, j_min = min((self.min_badness(j) + self.badness(i, j), j)
                           for j in range(i + 1, self.n + 1))
        self.break_point_track[i] = j_min
        return f

Your badness function can be simplified by using sum, similar to how I used min above:

def badness(self, start, end):
    total_width = sum(len(word) for word in self.words[start:end])
    return abs((self.page_width - total_width)**3)

While it might be your most used use case, writing the output to a file prevents anyone from using this module in any other way. It would be better if justify just returned (even better and simpler: yielded) the justified text and writing to a file is left to the user or a dedicated method using justify internally.

def justify(self):
     self.min_badness(0)  # no-op or to populate the cache?
     brk = 0
     while brk < self.n:
         start, brk = brk, self.break_point_track[brk]
         yield " ".join(self.words[start:brk]) + "\n"

def write(self):
    with open(self.out_file_name, "w") as f_out:
        f_out.writelines(self.justify())

I'm not exactly sure why you have a lone self.min_badness(0) in justify. is it just to populate the cache with the value for zero? If so, this is worth to put a comment here, because otherwise you might accidentally delete it.


I can't tell from your question whether you are wanting ideas to improve this python code or the project itself.  Your code above works and is readable, so take the following re-spelling of it as minor nitpicks.

def topics(f):
    for i in open(f):   # inline the call to open(), and drop the implicit 'r'.
        yield i.strip() # "yield" turns this into a generator function that will only
                        # read as many lines of the file as are requested.

def mainp():  # consider renaming to something more descriptive (generate_topics?)
    wordlist = topics('../data/' + sys.argv[1])
    response = True # Or any "truthy" value that drops us into the while loop one time.
    while response:
        print random.sample(wordlist, int(sys.argv[2]))
        response = raw_input()

if __name__ == "__main__":  # Putting in this if guard allows you to import your
    mainp()                 # functions above from anywhere else you might want them.

You may want to peruse the HOWTO for generator functions.


Optimizing regex alternation, ability to view which choice matched?

First of all you can use non capturing groups to simplify the indices

var patt = /(?:(volume):\s\d+\n(?:.+\n)+?OK\n|OK\s(MPD)\s\d+\.\d+\.\d+|(OK)|(ACK).+\n)/;

var mycase = null;
var result = patt.exec(data);
if (result[1] == "volume")
    mycase= "volume";
else if (result[2] == "MPD")
    mycase= "MPD";
else if (result[3] == "OK")
    mycase= "OK";
else if (result[4] == "ACK")
   mycase= "ACK";

With this the result of the regex will be one of these

[ "complete match",  "volume", undefined, undefined, undefined ]
[ "complete match", undefined,     "MPD", undefined, undefined ]
[ "complete match", undefined, undefined,      "OK", undefined ]
[ "complete match", undefined, undefined, undefined,     "ACK" ]

Now you can either use the OR operator to get the case

mycase = result[1] || result[2] || result[3] || result[4];

Or just use a loop (be sure to only use non capturing groups for anything else but your cases)

for(var i = 1; i < result.length; i++){
    mycase = mycase || result[i];
}


Basic network layer for a JSON API client

There are few things that can be improved, will start with the major ones:

General

Instead of having function for each API call you can generalise it a bit like so:

/* Updated the name, since it's not only for transactions anymore
Since we no longer know the exact endpoint we will have to pass it to the function

I would also add `requestMeta` parameter that will contain any other information that would be needed to perform the api call
`parameters`, `encoding`, `authenticationType`, `additionalHeaders`, `shouldReauthenticate`
but this is in case you need them
*/

func apiReques<T: Codable>(_ dataType: T.Type,
                                    endpoint: Endpoint,
                                  completion: @escaping (Result<[T], ResultError>) -> Void) {

        self.httpLayer.request(at: endpoint) { (data, error) in

// In general an "early return" strategy is preferred, use guard when applicable and avoid nesting `if` statements
            if let error = error as NSError? {
                completion(.failure(error))
                return
            }

// Do not force unwrap, it's better to show empty screen (or error) instead of crashing the app
            guard let data = data else {
                completion(.failure(NSError(domain: "", code: 1, userInfo: [:])))
                return
            }

            do {
                let transactions = try JSONDecoder().decode([T].self, from: data)
                completion(.success(transactions))
            } catch {
                completion(.failure(self.defaultError))
            }
        }
    }

So, since your structures are Decodable (consider using Codable) you can easily use generics.

The _ dataType: T.Type is a bit tricky. Since we are not returning T we have to add it as a parameter so the compiler can infer the actual type (more on the topic can be found here

I would prefer keeping all the urls in one place, so I would move baseURL to endpoints enum. Again do not force unwrap

enum Endpoint {

    static let baseURLString = "https://example.com"

    case listTransactions
    case transactionDetails(String)
}

extension Endpoint {

    var method: HTTPMethod {
        return .get
    }

    var path: String {
        switch self {
        case .listTransactions:
            return Endpoint.baseURLString + "/api/transactions/"
        case .transactionDetails(let id):
            return Endpoint.baseURLString + "/api/transactions/\(id)"
        }
    }
}

This will affect your request func:

func request(at endpoint: Endpoint, completion: @escaping (Data?, Error?) -> Void) {

        guard let url = URL(string: endpoint.path) else { return }
// endpoint.method is available as well if needed

        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            completion(data, error)
        }
        task.resume()
    }

It seems that you are instantiating new HTTPLayer for every APIClient. In that case I would just go with private let httpLayer: HTTPLayer = HTTPLayer() and deleting the init. In that case you can mark class HTTPLayer as fileprivate so noone beside APIClient can access it and if any params needs to be passed to it will go through APIClient -> apiReques()

Error handling

If you want to go a bit further you can update the enum Result

enum Result<Value, Error: Swift.Error> {
    case success(Value)
    case failure(Error)
}

and also adding your custom errors:

enum ResultError: Error {
    case general(String?)
    case specific(Int?)
    case `default` // default is a keyword so if you want to use it, you should wrap it in ``, imo don't and choose another name
    case whateverYouWant
}

extension ResultError {
    var errorString: String {
        switch self {
...
        }
    }

    private func specificErrorString(_ errorCode: Int) -> String {
        switch errorCode {
...
        }
    }
}

This will affect the generic apiRequest a bit in the signature @escaping (Result<[T], ResultError>) -> Void) and ofc the completions

completion(.failure(.general("something went wrong")))
completion(.failure(.specific(123))
completion(.failure(.default)

Now you can delete var defaultError: NSError = NSError(domain: "", code: 1, userInfo: nil)

How to use it

APIClient(). apiReques(Transaction.self,endpoint: Endpoint.listTransactions) { data in

    switch data {
    case .success(let response):
        print("Success")
    case .failure(let error):
        print("error")
    }
}

Bonus

You can also split the completion into two completion success and failure

Signature

func apiReques <T: Decodable>(_ dataType: T.Type,
                                    endpoint: Endpoint,
                                    success: @escaping (([T]) -> Void),
                                    failure: @escaping ((ResultError) -> Void))

block calls

failure(.general(""))
failure(.default)
success(data)

Usage

APIClient().transactions(Transaction.self,
                         endpoint: Endpoint.listTransactions,
                         success: { data in
                            print(data)
}, failure: { error in
    print(error)
})


I see several opportunities for simplification and improvement in your main() function:

int main(){
    ifstream infile;
    ofstream outfile;
    infile.open("C-large-practice.in");
    outfile.open("C-large-practice-result.in");

std::ifstream and std::ofstream both have constructors that take the filename to open as an argument. You can collapse these lines to:

    ifstream infile("C-large-practice.in");
    ofstream outfile("C-large-practice-result.in");

You don't need the all vector; see below for why.

    int i=0,n=1;
    int N;
    string line;
    vector<string> all;

This piece of code skips reads in the number of lines remaining in the file, then has special case handling to discard the remainder of the line:

    infile>>N;  //number of test cases
    while(i<N+1){
        if(i<1){
        getline(infile,line);
        i++;
    }

Instead of putting a special case inside the while-loop, move that std::getline() call to above the while loop. Then the whole thing simplifies to:

    infile>>N;  //number of test cases
    getline(infile,line); // Discard the rest of the line.

    while(i < N) {
    // Note: condition in the while() has changed because we don't have
    // the extra line at the start
        string result;
        getline(infile,line);
        result = process_ln(line);
        all.push_back(result);
        outfile<<"Case #"<<n<<": "<<all[i-1]<<endl;
        n++,i++;
    }

You're storing the processed line in a vector, but the only place you're using that vector is right on the next line, where you output the string that you just put in there. So you could simplify further to:

        string result = process_ln(line);
        outfile << "Case #" << n << ": " <<  result << endl;

This eliminates the need for the all vector, as mentioned above. Note that I've combined the declaration and initialization of result. This is generally a good habit to get into when using C++.

Another useful optimization to note is that the return value from std::getline() is the stream that is passed as its first argument, and streams have an implicit conversion to bool so they can be used as the conditional in while() or for() loops. If you use the return from getline() as the conditional part of a for() loop, you can declare the string in the same for() statement:

    int n = 1;
    for(string line; getline(infile, line); ++n) {
        string result = process_ln(line);
        outfile << "Case #" << n << ": " << result <<endl;
    }

Then you don't need to declare i, line or all earlier in main()

The return at the end of main() is not necessary in C++; if you omit it, the compiler will generate code for the return 0 for you.

return 0;
}

In the process_ln() function, there are also some opportunities for improvement:

string process_ln(string line){
    int j;
    char letter;
    vector<string> val,temp;
    vector<char> v;
    string keep;

std::string has an indexing operator, so you don't need to extract each character from line here, you can simply index into it in the switch statement below and remove this code:

for(j=0; j<line.length(); j++)
    v.push_back(line[j]);

The C++ standard library has the std::ostringstream class which is very handy for building up strings one piece at a time, so in the big switch statement, where you've got temp.push_back("....") in your code, you could replace it with:

std::ostringstream  keep;
/// process the line, building it up a piece at a time.
return keep.str();

In the for loop, you're storing all the digits that you use in the val vector. You really only need the current and previous digits to keep track of this. You're also storing all the fragments for each digit, where you really only need to keep one. Since your original code also swallowed invalid input, I'm doing the same here:

        std::ostringstream  keep;

        // Note: initialized to an invalid digit value to guarantee that we|
        // don't inject a space at the start of the output string.
        char    last_digit = 'X';
        char    this_digit;
        string  digits;

        for(int i = 0; i < line.length(); i++){

        switch(line[i]){
            case ' ': this_digit = '0'; digits = "0"; break;
            case 'a': this_digit = '2'; digits = "2"; break;
            case 'b': this_digit = '2'; digits = "22"; break;
            /// and so on for the rest of the letters.
            default : this_digit = 'X'; digits = ""; break;
        }//end switch

        if(this_digit == last_digit)
        {
            keep << " ";
        }
        keep << digits;
        last_digit = this_digit;
    }//end for loop
    return keep;
}//end process_ln

Note that if you follow all of my advice, you won't need any of the variables j, letter, val, temp or v declared at the start of the function (though I admit I did introduce a few new ones).


dput() concatenated vector with no quotes, separated by commas in R


I'd simplify as follows:

(defn get-digit [x k] (Character/digit (.codePointAt x k) 10))

codePointAt is a method of Java's String class.
digit is a static method of Java's Character class.

Both of these are in Java.lang, hence included by default.

(->> 1
     (iterate (partial * 10))
     (map (comp (partial get-digit d) dec))
     (take 7)
     (apply *))
;210

You can replace apply with reduce, if you prefer.

The calculation may be easier to follow as a series of bindings in a  let form:

(let [powers-of-ten (iterate (partial * 10) 1)
      digits (map (comp (partial get-digit d) dec) powers-of-ten)
      seven-digits (take 7 digits)
      answer (apply * seven-digits)]
  answer)


On a cursory glance, you can change the statement:

if (enabled) then _G["min"..option].cbutton:SetChecked(1) else _G["min"..option].cbutton:SetChecked(0) end

to

_G["min"..option].cbutton:SetChecked( enabled and 1 or 0 )


I think that is ok, only that i see not necesary make url.indexOf('?') if queryString is empty, because you are not going to use it.

exports.addQueryString = function(url, queryString) {
  if (queryString) {
    var isQuestionMarkPresent = url && url.indexOf('?') !== -1,
      separator = isQuestionMarkPresent ? '&' : '?';
    url += separator + queryString;
  }

  return url;
};


Possible improvements on admin login area?

Tha major security issue I see is that you do not have any limiting or logs for wrong/success attempts. One can use automated brute force attacks trying all day/night long to guess your username and password. If lack of success, at least you might have your app slowed down, because of the billion requests.

As you requested, I tried to add some code examples around my suggestion:

<?php

//the db interaction is pseudo code, because it depends on the API you are using
/**
 *
 * @param int $success : 0 for fail, 1 for success
 */
function logAttempt($success) {
    $user = $db->escape($_POST['userName']);
    $pass = $db->escape($_POST['password']);
    $session_id = session_id();
    if (!in_array($success, array(0, 1))) {
        return false;
    }
    $db->query("INSERT INTO `log_attempts`
                    (`user`, `pass`, `ip`, `session_id`, `success`, `tried_on`)
                VALUES
                    ('$user', '$pass', '{$_SERVER['REMOTE_ADDR']}', '$session_id', '$success', NOW());
            ");
    return $db->affected_rows > 0;
}

function isAttemptsLimitExceeded() {
    $max_attempts = 5;
    $session_id = session_id();
    $res = $db->query("SELECT
                            COUNT(*) AS cnt
                        FROM
                            `log_attempts`
                        WHERE
                            `session_id` = '$session_id' AND
                            `tried_on` > DATE_SUB(NOW(), INTERVAL 24 HOUR) AND
                            `success` = '0';
                    ");
    $row = $db->fetch($res);
    if ($row['cnt'] >= $max_attempts) {
        return true;
    }
    return false;
}

function banFailedLogins() {
    if(isAttemptsLimitExceeded()) {
        $db->query("INSERT INTO `blacklist`
                        (`ip`, `banned_on`)
                    VALUES
                        ('{$_SERVER['REMOTE_ADDR']}', NOW()");
    }
    return $db->affected_rows > 0;
}

function clearBans() {
    $db->query("DELETE from `blacklist` WHERE `ip` = '{$_SERVER['REMOTE_ADDR']}';");
    return $db->affected_rows > 0;
}

//check for expired bans?
function canAcess() {
    $ban_expire = 24; // hours
    $res = $db->query("SELECT
                            COUNT(*) AS cnt
                        FROM
                            `blacklist`
                        WHERE
                            `ip` = '{$_SERVER['REMOTE_ADDR']}' AND
                            `banned_on` > DATE_SUB(NOW(), INTERVAL $ban_expire HOUR);
                        ");
    $row = $db->fetch($res);
    if ($row['cnt'] > 0) {
        return false;
    }
    else {
        clearBans();
        return true;
    }
}

if (!canAcess()) {
    die("You are banned for failed login attempts");
}
  if (isset($_POST['password']) && isset($_POST['userName'])) {
    if ($_POST['password'] == "myPassword" && $_POST['userName'] == "myUsername") {
      if (!session_id()) {
        session_start();
        $_SESSION['logon'] = true;
        logAttempt(1); //log successfull attempt
        header('Location: admin_area.php');
        die();
      }
    } else if ($_POST["password"] == "" || $_POST["userName"] == "") {
      echo "Please enter both a username and a password! You are sent back in 3 seconds";
      logAttempt(0); //log failed attempt
      banFailedLogins();
      echo "<meta http-equiv='refresh' content='3;url=login.html'>";
    } else {
      echo "Wrong username and/or password! You are set back in 3 seconds";
      logAttempt(0); //log failed attempt
      banFailedLogins();
      echo "<meta http-equiv='refresh' content='3;url=login.html'>";
    }
  } else {
    echo "This is a restricted area, you have to log in!";
    echo "<meta http-equiv='refresh' content='3;url=login.html'>";
  }

?>


Use a local database to store information

You could start by testing what takes the longest, and concentrate your efforts there. I cannot do this test. However, getting multiple bits of information, from an external API, can never be quick. This is probably what is slowing you down.

The API is: https://www.eventbrite.com/developer/v3

I had a very short look at the API you're using, and quickly stopped when I noticed it was quite complex. :-)

Do you retrieve information from the API for every page you render? Does this mean that the same information is requested from the API several times?

In that case it would be better to store the retrieved information in a local database, and use the information from your local database to build the web pages.

The API has webhooks. These can be useful to update the information in your database. Use them.

I know this isn't really an answer that reviews your code.


Print out all possible letter combinations a given phone number can represent

This can certainly be optimized.
Your algorithm works in loops that iterate over all permutations, placing one letter each time.
Let us take a different approach:

The number of output combinations can be calculated in advanced: multiply the number of letters for all input numbers. in yout example ("23") the calculation is
number 2 has 3 letters
number 3 has 3 letters
output combinations will be 3*3=9

Furthermore, we can calculate which letter will be placed in each combination based on the combination index. if we assume combination index goes from 0 to 8:
for number 2 (first number in input)
- combinations 0-2 will contain 1st letter
- combinations 3-5 will contain 2nd letter
- combinations 6-8 will contain 3rd letter
for number 3 (2nd number in input)
- combinations 0,3,6 will contain 1st letter
- combinations 1,4,7 will contain 2nd letter
- combinations 2,5,8 will contain 3rd letter

so the formula for letter placement is based on the combination index, the position of the number in the input and the position of the letter in the letters-of-number String.

the complexity of this algorithm is o(n*m) where n is number of input letters and m number of output combinations.

one comment regarding the code: You use the results as a Queue.  the LinkedList is an implementation of this interface. For clarity sake, the variable should be defined with the type that states its usage. This is also true for the map variable (should be defined as Map)


In your example you iterate over the same collection. In that case I'd write:

[1, 2, 3].repeated_permutation(4).each do |n1, n2, n3, n4|
  if n1 == 1 && n2 == 2 && n3 == 3 && n3 == n4
    p [n1, n2, n3, n4]
  end
end

If instead you need to iterate over different collections, check Enumerable#product.

Of course, any of these alternatives will perform worse than your original code, since you drop whole groups of permutations when some condition is not satisfied.

Note that you could create a compact abstraction as efficient as your original code (it would take collections to iterate and conditions -with procs?- over them), but this won't pay off if you are going to use it only once.


Solving the travelling salesman problem using a genetic algorithm

How about using a slice for Gene.Data?

You just allocate

var allData := make([]int, nCrossover * ts.geneLength)

before entering the for loop and assign

newGenes[i].Data = allData[i * ts.geneLength: (i + 1) * ts.geneLength]

You'd cut down on the amount of allocations (and system calls) without changing much else (except findNextCity and isInArray - but they should be written to accept slices instead of array pointers anyway).

And you'd follow the advice given by the languages creators in Effective Go.


You're overdoing it with comments. A lot. And trivial ones at that. Every programmer knows that std::vector<boost::thread *> t; creates a vector of pointers to boost::thread, or that you have to use -> with pointers. Such comments are really just clutter and actually make the code harder to read. Save them for the non-obvious bits.
It's unclear what mtx protects. Does it protect data? Or r? Or both? This is one of the places where you should comment, but you didn't (//Create a mutex is absolutely pointless). If possible, rename the mutex to match its purpose. It would also be a good idea to wrap the mutex and the data it protects in a class, to ensure that unsafe access is impossible.
((CORES>count?count:CORES)) requires the reader to parse it (and what's with the double parentheses?) The meaning of std::min(CORES, count), on the other hand, is immediately obvious. And how does it create 4 threads? You could just as well rewrite the entire loop to make it more concise (and perhaps more efficient too):

while (count > 0) {
  std::vector<boost::thread *> threads(std::min(CORES, count));
  for (size_t i = 0; i < threads.size(); ++i) { // Start appropriate number of threads
    threads[i] = new boost::thread(threadFunction, i);
  }
  for (size_t i = 0; i < threads.size(); ++i) { // Wait for all threads to finish
    threads[i]->join();
    delete threads[i];
    --count;
  }
}

Also note that I added a call to delete into the waiting loop. Your previous code was leaking the threads.
You're writing C++. Don't use (type unsafe!) C I/O. Do this instead:

{
  std::ofstream out("RandomNumbers.txt");
  for (size_t idx = 0; idx < data.size(); ++idx) {
    out << data[idx] << '\n';
  }
}

The same holds for all other uses of C I/O (printf(), getchar()), of course.
count and CORES would be better declared with type size_t, as they represent the number of some objects.
If you have access to C++11, all the above could be simplified even further using range-based for loops, lambdas in standard algorithms, or at the very least iterator-based loops. I didn't bother with iterators here (even though they could be used), because their type has to be spelled out explicitly.

In such case, it would also make more sense not to allocate the threads dynamically, but create them directly in the vector. No need for manual deallocation, no dynamic allocation overhead.


Picking weighed enumerable values at random

You're right that all the casting is a sign that there's better way.  Rather than using the int value of an ActionPlan as the index to an array, you should use a structure that's designed to store two values in the first place.  There's a couple of alternatives here.

My first instinct is to use a Dictionary<ActionPlan, double>.  That most explicitly matches the concept of what you're trying to do (each A has a value B), but it's not actually the best option.  You're not going to be looking up the value based on the key, the order of the keys may change which could lead to hard-to-reproduce bugs, and it's less memory-efficient.

Instead, I'd use a List<KeyValuePair<ActionPlan, double>>, List<Tuple<ActionPlan, double>>, or (in C# 7) List<(ActionPlan, double)>.  They're all effectively the same thing in this case, and best convey the concept "here is a pair of related values" without implying the A->B relationship of the Dictionary.  (Note that you can also use arrays instead of List<>, like I do below).  To make PickOption() handle this, you would need to make it generic, so that you can pass any arbitrary type in and get that same type out.

Here's what the code would look like using C# 7's ValueTuples:

private ActionPlan PickPlan()
{
    (ActionPlan, double)[] odds = new[] {
        (ActionPlan.DoNothing, 2.5),
        (ActionPlan.Eat, 3),
        (ActionPlan.StealFoodCovertly, 1),
        (ActionPlan.AttackAndSteal, 0.5),
    };

    ActionPlan plan = PickOption(odds);
    return plan;
}

private T PickOption<T>((T, double)[] odds)
{
    double totalOdds = 0;
    foreach (var odd in odds)
    {
        totalOdds += odd.Item2;
    }
    double pick = rand.NextDouble() * totalOdds;

    for (int i = 0; i < odds.Length; ++i)
    {
        pick -= odds[i].Item2;
        if (pick <= 0)
        {
            return odds[i].Item1;
        }
    }
    return odds.Last().Item1; // In case there are some precision shenanigans
}

or better:

private T PickOption<T>((T Action, double Weight)[] odds)
{
    double totalOdds = 0;
    foreach (var odd in odds)
    {
        totalOdds += odd.Weight;
    }
    double pick = rand.NextDouble() * totalOdds;

    foreach (var odd in odds)
    {
        pick -= odd.Weight;
        if (pick <= 0) return odd.Action;
    }
    return odds.Last().Action; // In case there are some precision shenanigans
}

There are other improvements that can be made here, too, depending on how much you simplified for this question, and how far you want to go.  For a few examples:

Both methods can be made static, because they don't depend on anything specific to whatever class they're in.
Rather than redefining the odds each time that PickPlan() is called, you can create a static readonly (ActionPlan, double)[] odds and populate it once.  This also lets you do that right next to where your ActionPlan enum is defined, so that when you add a new enum value, the odds are right there.
If you have other properties associated with an ActionPlan, you may want to consider a class to consolidate them all, rather than let each place they're used keep track.


Store object in memory or de-reference it for performance

There will be no difference in performance whatsoever between the two approaches.

I would suggest you don't break the responsibility principle and leave the handling of the tablemodel to the Table class.

One remark though: if there are additional computations done in getTableModel() aside from a plain setter, you will bypass these if your create the local variable. This may or may not be something you desire.


Function calls as parameters for other functions

I'm typically an advocate of liberal use of space, but in this situation, I'd go with the third option:

soup = BeautifulSoup(mechanize.Browser().open(__URL))

(I'm not actually sure if that's valid syntax or not. I'm not very familiar with Python [I think it's Python?].)

I find that just as readable. There are of course situations where you must separate it though. The first thing that comes to mind is error handling. I suspect that open throws exceptions, but if it were to return boolean false on failure rather than a string, then I would be a fan of option two. Option two would still be brief, but would allow for properly checking for the false return.

I think this really comes down to personal taste. There's no magical rule book for this type of thing (though I'm sure there are convoluted, borderline-dogmatic metrics somewhere that support one way or the other).

I tend to just eyeball things like this and see if they make me visually uncomfortable or not.

For example:

superLongVariableNameHere(someParamWithLongName, someFunctionLong(param1, param2), someFunc3(param, func4(param1, param2, func5(param)))

Makes me cry a little whereas:

func(g(x), y(z))

Seems perfectly fine. I just have some weird mental barrier of what length/nesting level becomes excessive.

While I'm at it, I'd also disagree with Juann Strauss' dislike of JavaScript's practically idiomatic use of anonymous and inline-defined functions. Yes, people go overboard sometimes with a 30 line callback, but for the most part, there's nothing wrong with a 1-10 line anonymous function as long as it's used in one and only one place and it doesn't overly clutter its context.

In fact, to have a closure, you often have to define functions in the middle of scopes (well, by definition you do). Often in that situation you might as well inline it within another function call rather than defining it separately (once again, provided the body is brief).

If he means this though, then yeah, I'd agree 95% of the time:

f((function(x) { return x * x; }(5))

That gets ugly fast.


First thing, you're right about HttpRequest and the oddness of having to pass manually body and url .

To improve the code, I would suggest to chose a programming paradigm, and to stick to it:

example in OOP:

class HttpRequest<TResult> {
    constructor(private method: HttpMethod, private url: string, private body?: any) {}
    request():Promise<TResult> {
        return request(this.method, this.url, this.body);
    }
};

const req1  = new HttpRequest<FirstResponse>('POST', `http://example.com/one`, {
    id: 9,
    data: [`hi`, `there`]
  });
const req2 = new HttpRequest<SecondResponse>('GET', `http://example.com/one`);

// you now just have to call req1.request() for example , without parameters

in more FP friendly way of doing thing:

function my_request<T>(httpReq: HttpRequest) {
    return  (): Promise<T> => request(httpReq.method, httpReq.ufl, httpReq.body)
}

const req1  = my_request<FirstResponse>({method:'POST', url:`http://example.com/one`, body:{
    id: 9,
    data: [`hi`, `there`]
});
const req2 = my_request<SecondResponse>({method:'GET', url:`http://example.com/one`});

// you now just have to call req1() for example , without parameters

Now, we can improve the typing of waitAll with mapped types, for example for the OOP version (it's equivalent for the FP one):

function waitAll<T extends any[]>(...reqs: {[K in keyof T]: HttpRequest<T[K]>}): Promise<T> {
  // the any here is mandatory as Promise.all doesn't support (yet) the above signature
  return Promise.all(reqs.map(req => req.request())) as any;
}

// result type will be a [FirstResponse, SecondResponse]
const result = waitAll(req1, req2)

Now, you should ask yourself if you're not "over-abstracting". A code like that:

const req1 = request('POST', `http://example.com/one`, {id: 9});
const req2 = request('GET', `http://example.com/one`);

const [r1, r2] = await Promise.all(req1, req2);

const finalResponse = await request('POST', `http://example.com/three`, body);

uses only standard TS stuffs (await, Promise.all), hence is often easier to read for a developper that didn't write the code.


Find the year when the user will turn 100

Your findYearWhenAge100() function has a print() statement, and returns nothing, so your __main__ doesn’t need to print the return value.

A good habit is adding """docstrings"""  to your functions.  Eg)

def inputInfo():
    """Asks the user for name and age"""
    #... remainder of code

The userInput() function should do things like turning the userAge string into an int.  That should not be the responsibility of functions which need the age.

Use pylint.  It will help you write more standardized code.  Things like a space is expected after a comma, not before.


Asynchronously fetching Bitcoin orders and quotes

One of the main benefits of using await is to keep your code flat and to avoid .thens - you're not doing that in getOrderBook. nor in getTicker. If you want to use await, try awaiting each asynchronous operation.

Accessing a property of an object is not an asynchronous operation, nor is creating a new object: those lines should not be in .thens.

Because both fetch() and .json() access the .result property, you can keep from repeating yourself by putting that into another function:

const fetchBittrexResult = async (method) => {
  const params = 'market=BTC-' + currency + (method === 'getorderbook' ? '&type=both' : '');
  const url = `https://bittrex.com/api/v1.1/public/${method}?${params}`;
  const response = await fetch(url);
  const responseObj = await response.json();
  return responseObj.result;
};

Then consume it:

const getOrderBook = async () => {
  const { buy, sell } = await fetchBittrexResult('getorderbook');
  return {
    buys: buy.slice(0, 10),
    sells: sell.slice(0, 10),
  };
};

const getTicker = () => fetchBittrexResult('getticker');

(no need for getTicker to be async anymore)

For getCurrencyData, I'm doubtful that continually re-assigning top-level variables is a good way to do this, but without seeing the consumers of the fetched data, it's hard to say what the better solution is. Argument destructuring will help reduce the syntax noise there, and don't feel like you have to squash everything onto one long line:

const getCurrencyData = () => {
  getOrderBook()
    .then(({ buys, sells }) => ([buyOrders, sellOrders] =  [buys, sells] ));
  getTicker()
    .then(({ Bid, Ask, Last }) => ([bid, ask, lastBuy] = [Bid, Ask, Last]));
};

It would probably be better to assign to an object rather than to multiple standalone variables, though.


Refactoring custom validator using lots of if's

You can refactor each condition using extract method

def validate_mlb_score
def validate_nba_score

Also you can methods to determine min/max score

def max_score_for(event)
  event.league_is_mlb? ? 49 : 370 # judging by your elseif without else I've suggested about only two leagues
end

I think my code would look like:

def validate(event)
  if event.total_score < event.min_score
    event.errors.add :base, "min total score for an #{event.name} event is #{event.min_score}"
  elsif event.total_score > event.max_score
    event.errors.add :base, "max total score for an #{event.name} event is #{event.max_score}"
  end
end

# I also suggest what you have this kind of model
class Event < ActiveRecord::Base

  def min_score
    self.league_is_mlb? ? 1 : 119
  end

  def max_score
    self.league_is_mlb? ? 49 : 370
  end
end


I frequently write extension methods for IPrincipal and ClaimsPrincipal objects (depending on .NET framework version). Creating an abstraction for a business concept is a good idea, because it centralizes this knowledge (think: Single Source of Truth). If this happens to change in the future, you have one file, one method to modify. Option 1 is preferred, since it simplifies maintenance.
Some additional improvements:

Call extension methods from the object context: user.GetCurrentlyLoggedInUserEmail()
This is what extension methods are for. Take advantage of their syntactical sugar.

Do not duplicate concepts in the method name that already exist in the type it extends. This just makes method names too long for no added benefit: calling user.GetEmail() conveys the same information in a fraction of the characters.
Plus, "LoggedIn" is contextual, and assumes you are calling this on a ClaimsPrincipal that is the currently logged in user. This is not something the .NET type system enforces, so your method name should not make this assumption.


Stack* helper (char val, int x, int y)
  {

Your indentation and whitespace are kind of funky; I recommend looking at what some popular open-source code on GitHub does, and trying to copy them as closely as possible. Or, just run your code through a formatter such as clang-format.

Stack *helper(char val, int x, int y)
{

This function is only ever used in one place, so why do you have it? Right now it's kind of unsafe, because helper returns a Stack * which:

must be freed by the caller to avoid memory leaks, and
has uninitialized garbage in its next field.

If you inlined it into push, you'd have a complete unit of work, without either of those dangerous sharp edges.

Look into proper library organization. You should have a .h file that defines struct Stack and declares push and pop, and a .c file with the implementations.

You should probably name the functions something like stack_push and stack_pop, since push and pop are likely to be common names; e.g. you might later want to write a struct Queue with a queue_push and queue_pop. This kind of "manual namespacing" is common in C libraries.

Of course push shouldn't call printf (there's no "I" in "TEAM" and there's no "printf" in "push data onto a stack").

In pop's argument list, you use w and h where you meant x and y.

pop has interesting behavior on an empty stack: it just returns without initializing *x and *y. This is a problem for the caller, because the caller doesn't have any indication that anything went wrong! You should probably make pop return a bool to indicate whether it was successful.

Compare a pointer for null with (top == NULL), not !top. Clarity counts!

Here's an idea if you want to push yourself harder: Right now you're passing x, y, and value as individual arguments to push, and retrieving them individually from pop. Package them up into a struct!

Here's the struct definitions and function declarations for a different stack implementation. Can you see how to implement these functions?

struct Data { int x, y, value; };

struct DataStack { struct Data data; struct DataStack *next; }

struct DataStack *datastack_push(struct DataStack *, struct Data);
struct DataStack *datastack_pop(struct DataStack *);
struct Data datastack_top(const struct DataStack *);
bool datastack_empty(const struct DataStack *);


Simplest way to write "FizzBuzz" in Rust

I think that match is better, you just do not know how to cook it ;)

fn main() {
    for i in 1..102 {
        match (i%3, i%5) {
            (0, 0) => println!("FizzBuzz"),
            (0, _) => println!("Fizz"),
            (_, 0) => println!("Buzz"),
            (_, _) => println!("{}", i)
        }
    }
}


Python CLI-Parser improvement for "one of those options"

Okay, I found a better way

import argparse
parser = argparse.ArgumentParser()

class RequiredLen(argparse.Action):
        def __call__(self, parser, args, values, option_string=None):
            if not 1 <= len(values) <= 2:
                msg = f"argument {self.dest} requires 1 or 2 arguments"
                raise argparse.ArgumentTypeError(msg)
            setattr(args, self.dest, values)
# Just give me 1 or 2 files
parser.add_argument(
    "--paired",
    nargs    = '+',
    action   = RequiredLen,
    required = True,
    help     = "input file(s)"
)
# Specify either ext1 or ext2 format
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument(
    "--ext1",
    action = "store_const",
    dest   = "format",
    const  = "ext1",
    help   = "input is ext1 format"
)
group.add_argument(
    "--ext2",
    action = "store_const",
    dest   = "format",
    const  = "ext2",
    help   = "input is ext2 format"
)
args = parser.parse_args()
print(args)

This way I can later just use something like:

def process_ext1(l: list):
   print("ext1 file(s)")
   for i in l:
       print(i)

def process_ext2(l: list):
   print("ext2 file(s)")
   for i in l:
       print(i)

process_format = { 'ext1': process_ext1, 'ext2': process_ext2 }
process_format[args.format](args.paired)


Enum for handling network request errors in Swift

I would not recommend this pattern. I see no compelling reason to encumber NetworkRequestError (and presumably every other Error enumeration throughout your project) with this finish cruft.

So, instead of:

enum NetworkRequestError: Error {
    case hostNotAvailable
    case accountNotAvailable

    func finish<T>() -> Result<T, NetworkRequestError> {
        return .failure(self)
    }
}

func fetch(result: @escaping (Result<(any: [Any], any1: [Any]), NetworkRequestError>) -> Void) {
    guard host != nil else {
        result(NetworkRequestError.hostNotAvailable.finish())
        return
    }

    ...
}

I’d instead suggest:

enum NetworkRequestError: Error {
    case hostNotAvailable
    case accountNotAvailable
}

func fetch(result: @escaping (Result<(any: [Any], any1: [Any]), NetworkRequestError>) -> Void) {
    guard let host = host else {
        result(.failure(.hostNotAvailable))
        return
    }

    ...
}

This is more concise, conforms to established patterns (making it easier to reason about) and it doesn’t entangle Error types and Result types.

Also you’re undoubtedly checking host because you’re going to use it later in this method, so you might as well do guard let, like above. It saves you from having to do subsequent unwrapping of the optional.

I’m assuming your question was primarily about the Error type and this finish method. I must say that I am equally uneasy about the .success associated type, namely the tuple of [Any] arrays. Perhaps this was just a placeholder in your example, but I generally find references to Any to be code smell. Often specific types or generics would be better than Any to types in one’s code. If you have a question about why you’re using a “success” type which is two arrays of Any, that might warrant its own question, showing why you did that. It, too, could probably be improved.


Advanced formatting with argument passing

list always uses repr on it's elements.
When you str or repr it.
And internally list is doing roughly the equivalent of what you are doing in format_array.

The only way to make this work is to use something like format_array,
or subclass list.
But they will both be doing the same thing, just depends on how much sugar you want.

Your code is nice, readable and follows PEP8.
As this is tending towards example code, it's not in it's native environment, it's hard to comment distinctively on it.

But format_data can be merged with the class.

class InsideB(object):
    def __init__(self, data):
        self.data = data

    def __repr__(self):
        data = self._data(True)
        return "InsideB(data={0})".format(data)

    def __format__(self, formatstr):
        data = self._data('x' in formatstr)
        return "InsideB(data={0})".format(data)

    def _data(self, as_hex):
        if as_hex:
            return binascii.b2a_hex(self.data).decode('ascii')
        else:
            return repr(self.data)

You can then add an option to use 'hex' or repr as the output type to the class.
With the option to reverting to the original after a use.
Obviously it depends on your usage.

class InsideB(object):
    def __init__(self, data, as_hex=False, revert_hex=False):
        self.data = data
        self._as_hex = as_hex
        self.output_type = as_hex
        self._revert_hex = revert_hex

    def _data(self, as_hex):
        if as_hex or self.output_type:
            data = binascii.b2a_hex(self.data).decode('ascii')
        else:
            data = repr(self.data)

        if self._revert_hex:
            self.output_type = self._as_hex

        return data

Then you would need to make a function that maps over all the items in the list,
changes output_type to what you want, and you'll be in the same position as you are now.
But with a bit more sugar.

If you choose to subclass list, and to use str in __str__,
then you'll get output which is just wrong.

>>> print('{!s}, {!s}'.format('a', 'b'))
a, b
>>> print('{!r}, {!r}'.format('a', 'b'))
'a', 'b'

No matter how I look at it you wont be able to change the output 'nicely'.
Unless you think something more robust to map(lambda i: i.output_type = True, array) is nice.

Bottom line you have to manually implement this, as repr is hard-coded.