General

Try to comply with PEP-8. PEP-8 is the name of the official Python style guide. Complying with it makes your code easier to read. Ultimately, developers can more easily collaborate on a project.

Every import-statement should be on a separate line. The only exception is importing 'from' a module / package. Furthermore, imports should be grouped:

standard library imports
third-party imports
local project imports

... Where the groups are separated by a single empty line.1

Putting this together:

from msvcrt import getch
import os
# Sort alphabetically

import colorama
from colorama import Fore, Back, Style

Functions should follow the snake_case naming convention.2 Classes should follow the PascalCase naming convention.3
Top-level function and class definitions should be preceded by two empty lines.4
Keyword arguments should separate their name and default value only by an equals-sign ('='), not by any spaces.5
Don't mix single and double quotes. They're functionally the same, but when you start mixing them, this can become confusing to people who are used to other languages, like C, where there is a difference.

In getKeyInput(), you use 7 magic numbers.

Instead of adding comments to explain what these numbers represent, you can give them a name. For example, by declaring these constants at the top of the file:

NEXT_KEY_IS_ARROW_KEY = 224
UP_ARROW_KEY = 72
DOWN_ARROW_KEY = 80
ENTER_KEY = 13

POINTER_UP = 1
POINTER_DOWN = -1
PRESS_BUTTON = 0

... no additional explanation is needed in getKeyInput():

def getKeyInput():
    key = ord(getch())
    if key == NEXT_KEY_IS_ARROW_KEY:
        key = ord(getch())
    if key == UP_ARROW_KEY:
        return POINTER_UP
    elif key == DOWN_ARROW_KEY:
        return POINTER_DOWN
    elif key == ENTER_KEY:
        return PRESS_BUTTON

(Even better would be to use an enum).

Bugs

You forgot to define quit().
I'm not sure if this is a quirk of my terminal emulator / MacOS Sierra, or if it's present regardless of setup, but the bounds checking in Menu.show() doesn't do its job: I can keep moving the pointer down forever, which causes interesting screen glitches.6, 7
This isn't strictly a bug, but if a user presses anything other than △, ▽, or return, the program crashes.

Public API

I know you used the windows-tag, but you might reach a broader audience by making this platform-independent.

msvcrt and os.system("cls") only work on Windows platforms. If I run the program on MacOS, I get a ModuleNotFoundError. Even if I could patch that, the os.system("cls") call would print out an error message instead of clearing the screen. There's three partially satisfying solutions:

msvcrt.getch() returns a single keypress. By default, the terminal is in 'cooked' mode. (I'm using UNIX terminology, not sure how much of this applies to Windows) so sys.stdin.read(1) won't work, as the user must press enter first. By putting the terminal in 'cbreak' mode, we can read one keypress at a time. The standard library tty.setcbreak() function does exactly that. One small issue is that there is no standard library function for resetting the terminal mode. Luckily, it's as simple as saving the terminal options, putting the terminal in cbreak mode, and restoring the saved options when done.
On Windows, the command for clearing the screen is '$ cls'. On most other systems, the command is '$ clear'. Keeping that in mind (pseudocode):

if platform is Windows then
    $ cls
else
    $ clear

If your terminal supports ANSI escape codes, you don't even need to make a system call to clear the screen. Instead, you print the 'Erase in Display' code (source, modified for formatting):

  CSI n J

  ED – Erase in Display

  Clears part of the screen. If n is 0 (or missing), clear from cursor to end of screen. If n is 1, clear from cursor to beginning of the screen. If n is 2, clear entire screen (and moves cursor to upper left on DOS ANSI.SYS). If n is 3, clear entire screen and delete all lines saved in the scrollback buffer (this feature was added for xterm and is supported by other terminal applications).

A major drawback of this approach is that there is no straightforward way of testing whether or not a terminal supports these codes. Most modern terminals do, but there are some exceptions.8

Unless you plan on extending the class with methods, comm is superfluous. A lambda is enough.
Move colorama.init() to the if __name__ == "__main__" body.
Try abbreviating names less. While abbreviating is customary in other languages, in Python, developers should be as verbose as possible (within reason).
Make functions and attributes private when it makes sense. Especially when you're designing a public API, you want to hide away all the unimportant / difficult to comprehend stuff. For example, in Menu.__init__(), all the arguments should be private attributes, because developers should not be allowed to modify them after initialization.
Add docstrings to public functions and classes.

Names

getKeyInput() is a misleading name. It doesn't return user input, it returns an action (move the cursor up, move the cursor down, press a button) based on the input. I suggest get_action_from_user_input().
In this context, the variable name buffer suggests it has to do with I/O buffering, which is not true. I suggest decorative_line (?).
Menu. Well, sure. But what kind of menu? It's a menu where you make a selection → SelectionMenu.
Menu.show() tells only part of the story. It doesn't just output stuff, it also waits for user input: it is waiting for the user to press return. How about Menu.await_selection()?

My take on it

import enum
import os
import sys

import colorama as cla

try:
    import msvcrt
except ImportError:
    # POSIX
    import termios
    import tty

class Terminal:
    """A `Terminal` instance represents a terminal (emulator)."""

    _ANSI_CODE_CLEAR_SCREEN = "\033[2J"
    _ANSI_CODE_MOVE_CURSOR_TOP_LEFT = "\033[1;1H"

    def __init__(self, ansi_escape_codes_supported=False):
        """Initialize the terminal.
        If this method is called on a POSIX system, set the terminal
        mode to 'cbreak'.

        Arguments:
            - ansi_escape_codes_supported [bool]: Whether or not to
            assume ANSI escape codes are supported. Defaults to
            `False`. When in doubt, don't set to `True`.
        Returns:
            - `None`.
        """
        if os.name == "posix":
            self.posix = True
        elif os.name == "nt":
            self.posix = False
        else:
            raise RuntimeError("Only POSIX and NT systems are supported.")
        self._ansi_escape_codes_supported = ansi_escape_codes_supported
        self._prepare()

    def _prepare(self):
        """Prepare the terminal.
        On NT systems, this is a no-op. On POSIX systems, save the
        terminal attributes, then set the terminal mode to 'cbreak'
        using `tty.setcbreak()`.

        Returns:
            - `None`.
        """
        if not self.posix:
            return
        self._saved_terminal_options = termios.tcgetattr(sys.stdin)
        tty.setcbreak(sys.stdin)

    def clear_screen(self):
        """Clear the screen.
        If ANSI escape codes are supported, print ED (CSI 2 J), then
        print CUP (CSI 1 ; 1 H). Otherwise: on POSIX systems, call
        '$ clear'. On NT systems, call '$ cls'.

        Returns:
            - `None`.
        """
        if self._ansi_escape_codes_supported:
            print(self._ANSI_CODE_CLEAR_SCREEN)
            print(self._ANSI_CODE_MOVE_CURSOR_TOP_LEFT, end="")
        elif self.posix:
            os.system("clear")
        else:
            os.system("cls")

    def get_character(self):
        """Get a single character from stdin.

        Returns:
            - [str] A single character.
        """
        if self.posix:
            return sys.stdin.read(1)
        return msvcrt.getch()

    def finalize(self):
        """Finalize the terminal.
        On NT systems, this is a no-op. On POSIX systems, reset the
        saved terminal attributes.

        Returns:
            - `None`.
        """
        if not self.posix:
            return
        termios.tcsetattr(
            sys.stdin,
            termios.TCSANOW,
            self._saved_terminal_options
        )

class POSIXCodePointValues:
    """
    MacOS Sierra code point values.
    NOTE: Don't rely on this!
    There are no standardized code points for arrow keys, so these are
    the values for my machine. They are most likely *not* the same for
    you.
    """
    NEXT_KEY_IS_ARROW_KEY_SEQ = (27, 91)
    UP_ARROW_KEY = 65
    DOWN_ARROW_KEY = 66
    ENTER_KEY_SEQ = (10, 13)
    # Either 10 or 13

class NTCodePointValues:
    """
    NT code point values.
    NOTE: These are most likely not very portable either.
    """
    NEXT_KEY_IS_ARROW_KEY = 224
    UP_ARROW_KEY = 72
    DOWN_ARROW_KEY = 80
    ENTER_KEY = 13

class UIAction(enum.Enum):
    """Values:
        - POINTER_UP (1): Move the cursor up one row.
        - POINTER_DOWN (2): Move the pointer down one row.
        - PRESS_BUTTON (3): Press the currently selected button.
        - NONE (4): Do nothing.
    """

    POINTER_UP = 1
    POINTER_DOWN = 2
    PRESS_BUTTON = 3
    NONE = 4

def _get_action_from_user_input_nt(terminal):
    code_point = ord(terminal.get_character())
    if code_point == NTCodePointValues.ENTER_KEY:
        return UIAction.PRESS_BUTTON
    elif code_point != NTCodePointValues.NEXT_KEY_IS_ARROW_KEY:
        return UIAction.NONE

    # Definitely an arrow key
    code_point = ord(terminal.get_character())
    if code_point == NTCodePointValues.UP_ARROW_KEY:
        return UIAction.POINTER_UP
    elif code_point == NTCodePointValues.DOWN_ARROW_KEY:
        return UIAction.POINTER_DOWN
    # Left or right arrow key
    return UIAction.NONE

def _get_action_from_user_input_posix(terminal):
    code_point = ord(terminal.get_character())
    if code_point in POSIXCodePointValues.ENTER_KEY_SEQ:
        return UIAction.PRESS_BUTTON
    elif code_point != POSIXCodePointValues.NEXT_KEY_IS_ARROW_KEY_SEQ[0]:
        return UIAction.NONE

    code_point = ord(terminal.get_character())
    if code_point != POSIXCodePointValues.NEXT_KEY_IS_ARROW_KEY_SEQ[1]:
        return UIAction.NONE

    code_point = ord(terminal.get_character())
    # Definitely an arrow key
    if code_point == POSIXCodePointValues.UP_ARROW_KEY:
        return UIAction.POINTER_UP
    elif code_point == POSIXCodePointValues.DOWN_ARROW_KEY:
        return UIAction.POINTER_DOWN
    # Left or right arrow key
    return UIAction.NONE

def get_action_from_user_input(terminal):
    """Get a UI action from user input.
    Read characters from stdin until a relevant UI action can be
    constructed. See `UIAction` for the possible actions.

    Arguments:
        - terminal [Terminal]: A terminal instance, used for reading
        single characters.

    Returns:
        - [UIAction] A UI action.
    """
    if terminal.posix:
        return _get_action_from_user_input_posix(terminal=terminal)
    return _get_action_from_user_input_nt(terminal=terminal)

class SelectionMenu:
    """A `SelectionMenu` represents a group of options,
    from which the user can pick only one.
    """

    _RESET_COLOUR = cla.Fore.WHITE + cla.Back.BLACK

    def __init__(
        self,
        title,
        options,
        callbacks,
        terminal,
    ):
        """Initialize the menu.

        Arguments:
            - title [str]: The text to display as a title.
            - options [list]: A list of options the user can pick from.
              The elements must be `str` instances.
            - callbacks [list]: A list of functions to call when the user
              makes a selection. The length of this list must be equal to
              the amount of options provided.
            - terminal [Terminal]: A terminal instance to use for I/O.

        Returns:
            - `None`.
        """
        self._title = title
        self._options = options
        self._callbacks = callbacks
        self._terminal = terminal
        self._pointer = 0

    def await_selection(self):
        """Wait for the user to make a selection.
        Handle user input, draw the menu, and wait until the user
        presses enter.

        Returns:
            - `None`.
        """
        self._terminal.clear_screen()
        decorative_line = "-" * len(self._title)
        print("{}\n{}\n{}".format(
            decorative_line,
            self._title,
            decorative_line
            )
        )

        for option in self._options:
            colour = cla.Fore.WHITE + cla.Back.BLACK
            if self._pointer == self._options.index(option):
                # i.e. if this is the currently selected button
                colour = cla.Fore.BLACK + cla.Back.WHITE
            print("{}{}\n{}".format(colour, option, self._RESET_COLOUR), end="")

        action = get_action_from_user_input(self._terminal)

        if action == UIAction.PRESS_BUTTON:
            self._terminal.clear_screen()
            if self._callbacks:
                self._callbacks[self._pointer]()
            else:
                print("Picking {}".format(self._options[self._pointer]))
            self._terminal.finalize()
            return None
        elif action == UIAction.POINTER_DOWN:
            self._pointer += 1
        elif action == UIAction.POINTER_UP:
            self._pointer -= 1

        self._pointer = max(min(self._pointer, len(self._options) - 1), 0)
        # Assure the pointer stays within bounds
        self.await_selection()

def margherita():
    print("Margherita it is!")

def pepperoni():
    print("Pepperoni it is!")

def four_cheese():
    print("Four Cheese it is!")

def no_pizza():
    print("Curious.")

if __name__ == "__main__":
    cla.init()

    TITLE = "Pizza"
    BUTTONS = [
        "Margherita",
        "Pepperoni",
        "Four Cheese",
        "Ew! No pizza for me..."
    ]
    ACTIONS = [
        margherita,
        pepperoni,
        four_cheese,
        no_pizza
    ]

    terminal = Terminal(True)

    select_a_pizza = SelectionMenu(TITLE, BUTTONS, ACTIONS, terminal=terminal)
    select_a_pizza.await_selection()

References

1 PEP-8: Imports

2 PEP-8: Function and variable names

3 PEP-8: Class Names

4 PEP-8: Blank Lines

5 PEP-8: Other Recommendations

6 Here's what I mean.

7 Using ANSI escape codes fixes the problem for me, which suggests the bug is related to '$ clear'.

8 Wikipedia: ANSI escape code: Platform support

Appendix: My reasoning

With most of the points I wanted to make out of the way, I want to explain some of the changes I made.

I started out by rewriting getKeyInput() to handle both POSIX and NT systems. After having found out I was also going to need prepare_terminal(), reset_terminal(), clear_screen() and get_character() functions, I decided to extract all terminal-related stuff into a class of its own.
I originally let the Menu constructor initialize a new Terminal instance. That's a pretty bad design choice: it means every time a UI widget is created, a new Terminal instance is created as well; and developers can't interact with the terminal directly. Therefore, I made it a parameter.
Since code point values associated with arrow keys differ per system, I created a class to hold the values for my laptop. From the little research I've done, it seems the values are the same for most recent Windows releases.
Instead of crashing, the UI should ignore meaningless input. That's why I added UIAction.NONE to the UIAction enum.

Appendix: Design

API design

Since you plan on matching PyGame's functionality, you should take the time to think about how you want to design your API. You've taken an event-driven (callback functions) approach, which is probably the most sensible thing to do for user interfaces in general. As it stands, though, the caller can't retrieve the return value of the callback functions, which means in more complex cases, you'd have to modify a shared variable, which can get really messy, really fast. And I haven't even covered threading yet.

Interrupt handling

If I press Ctrl-C, I get a bunch of traceback lines, but more importantly, my terminal is still in cbreak mode. Once your codebase starts growing, it becomes tiresome to wrap every terminal.get_character() call in a try / except-block. You could put the block in terminal.get_character(), but that would mean a forceful exit any time the user presses Ctrl-C. Unfortunately, there's no trivial solution.

Backend

I have my doubts about the UI backend:

Using recursion in Menu.show(). There's really no need to, you might as well use a while-loop.

The following two points only apply if you want your UIs to be dynamic, and you need to create reasonably complex applications.

There's no parent-child relationship. You can create two instances of Menu, but they won't be related to one another. The second instance simply waits for the first one to complete, and then, completely independently, does its thing. If you want to add other types of UI widgets (frames, text labels, input fields, multiline text boxes, sliders, ...), you need a widget hierarchy.
Text is left-aligned, and there's no way of placing it dynamically. Once you've implemented a widget hierarchy, you need a way to map widgets anywhere on-screen. This is where ANSI escape sequences come in handy, because they allow you to move the cursor anywhere you want, and even save the cursor position and restore it later.

Getting this right is possible, but you must be willing to spend time and effort to do research, lay out an API, and document it.


This approach is not bad but I'd highlight a few issues:

You wrap each element with a <div>, it's unnecessary and for a very long list you create many useless elements. This also prevents <RFor> to be conveniently used (for example) to generate rows in a table.
You're assigning data to the properties of each item. While this might be convenient it's also fragile: what if an object as a property named key, or children, ref or...anything else already used? I'd assign data to a single property.
const { items } = props || [] does not do what you, probably, think it's doing. [] won't be the default if items is falsy but the default if props is falsy. The correct syntax, if the value is undefined is const { items = [] } = props;. If you want to handle also null then you can't destructure: const items = props.items || [];.
To use index as key is, more often than not, a terrible idea if the list isn't fixed (for example if you can remove/add elements anywhere in the list). Leave this responsibility to the caller because it's the only one with enough knowledge to pick a sensible unique ID (which in some very specific cases can even be the index).
You're passing props.children directly to React.cloneElement however it expects a single element and children can be an array. Enforce this rule using React.only().

To put things together (leaving out the key for the moment):

const RFor = props => {
    const items = props.items || [];
    return items.map(data => React.cloneElement(React.only(props.children), { data });
};

All these said you may start wondering if you even need RFor, let's compare with few alternatives:

<RFor items={TEMP_DATA_ARRAY}>
    <Item />
<RFor>

Vs

{TEMP_DATA_ARRAY.map(data => <Item key={data.id} {...data} />)}

Or:

{TEMP_DATA_ARRAY.map(data => <Item key={data.id} data={data} />)}

I don't see any benefit (note that you may, instead of children use a property like:

<RFor items={TEMP_DATA_ARRAY} component={Item} />

Also note that to solve the key problem you might use a render function:

<RFor items={TEMP_DATA_ARRAY}>
    {data => <Item key={data.key} data={data} />}
<RFor>

RFor IMHO makes sense only if it adds any other value over map(), it might be filtering or it might be part of an abstraction to build a presentation component with templates (with properties like controlTemplate, headerTemplate and itemTemplate as you often see in WPF).


Fun question,

if (campaign_names && campaign_names.length > 1) {
  campaign_names = campaign_names.join(", ");
} else if (campaign_names) {
  campaign_names = campaign_names[0];
}

is equivalent to

if (campaign_names && campaign_names.length ) {
  campaign_names = campaign_names.join(", ");
}

if you initialized campaign_names and list_names to '' you could simplify the last part to

if (campaign_names && list_names) {
  title = campaign_names + " & " + list_names;
} else {
  title = campaign_names + list_names;
}

Personally I would go for this:

var campaigns = data["campaign_names"] || [],
    lists = data["list_names"] || [],
    title;

if (campaigns.length) {
  campaigns = campaigns .join(", ");
}

if (lists.length) {
  lists = lists.join(", ");
}

if (campaigns && lists) {
  title = campaigns + " & " + lists;
} else {
  title = campaigns + lists;
}

If I was feeling ternary that day I would write the last part as

  title = campaigns + (campaigns&&lists) ? " & " : "" + lists;


Autofill a table based on the input provided in a userform

Whenever you find yourself writing a block of nearly identical code, I recommend creating a common function that simplifies and isolates that functionality. The advantage is that you now have a single location for the logic and can easily make a change that is consistent for each instance you need to use that logic. In your case, you are repeatedly finding the last row in a column and adding a value to the first empty row in that column. So create a separate routine for that.

You have three tricky parts. The first is that you're not always adding a value. In at least one case, you want to add a formula. For this, I created a simple enumeration type as an optional parameter. The second is you wanted to use the row index in your formula, so that row index value is returned from the function to use if needed. The last tricky bit is adding a value to a column that is completely empty. You can't blindly always add one to the lastRow value because you'll end up skipping that top row. This isn't always a problem since many folks reserve the first row for a column header, but the function takes this into account to be thorough.

Option Explicit

Private Enum DataType
    DataValue
    FormulaValue
End Enum

Private Sub CommandButton1_Click()
    AppendToColumn Sheet1, "A", JobID.Text  'Adds the TextBox3 into Col A & Last Blank Row
    AppendToColumn Sheet1, "B", Surveyor.Text
    AppendToColumn Sheet1, "C", DateBox.Text
    AppendToColumn Sheet1, "D", AddressBox.Text
    AppendToColumn Sheet1, "E", CityBox.Text
    AppendToColumn Sheet1, "F", PostcodeBox.Text
    AppendToColumn Sheet1, "G", THPBox.Text
    AppendToColumn Sheet1, "H", ChamberBox.Text
    Dim lastRowI As Long
    lastRowI = AppendToColumn(Sheet1, "I", ORFibreBox.Text)
    AppendToColumn Sheet1, "K", ("=I" & lastRowI & "*5"), FormulaValue
End Sub

Private Function AppendToColumn(ByRef ws As Worksheet, _
                                ByVal columm As Variant, _
                                ByVal value As Variant, _
                                Optional ByVal kindOfValue As DataType = DataValue) As Long
    '--- copies the given value to the first empty cell in the
    '    specified column. the "columm" value can be either numeric
    '    or alphabetic. RETURNS the index of the last row
    Dim colIndex As Long
    Dim lastRow As Long
    Dim firstEmptyRow As Long
    With ws
        '--- quick conversion to make sure we have a numeric column index
        colIndex = IIf(IsNumeric(columm), columm, .Cells(1, columm).column)
        lastRow = .Cells(.Rows.Count, colIndex).End(xlUp).Row
        '--- if the column is completely empty, the first empty row is 1,
        '    otherwise it's one row down from the last row
        firstEmptyRow = IIf(IsEmpty(.Cells(lastRow, colIndex)), 1, lastRow + 1)
        Select Case kindOfValue
        Case DataValue
            .Cells(firstEmptyRow, colIndex).value = value
        Case FormulaValue
            .Cells(firstEmptyRow, colIndex).Formula = value
        End Select
    End With
    AppendToColumn = lastRow
End Function


General Style
Your translation dict uses a keyword and lower case letters.
Consider writing constants with upper-case letters and giving them expressive names like MORSE_CODES = {...}.
According to PEP 8, functions should be named using snake_case. CamelCase is reserved for classes:
outputMessage → output_message, def Encrypt(...) → def encrypt(...), etc.
Performance
Using the Get_Key function is not very performant, since it performs a linear search of the dict. Just reverse the translation dict once and then use it:
MORSE_ENCODING = {
    'a': '.-',
    'b': '-...',
    ...
}
MORSE_DECODING = {value: key for key, value in MORSE_ENCODING.items()}

...

        temp = MORSE_DECODING[letter]

Handling errors
Currently the Encrypt function silently skips all non-translatable characters. Consider Throwing a ValueError() instead to indicate, that invalid input was provided:
def encode(message):
    """Encodes a string into morse code."""

    code = ''

    for index, char in enumerate(message):
        try:
            code += MORSE_ENCODING[char.lower()]
        except KeyError:
            raise ValueError(f'Char "{char}" at {index} cannot be encoded.')

        code += ' '

    return code[:-1]  # Remove trailing space.

def decode(morse_code):
    """Decodes morse code."""

    message = ''

    for index, sequence in enumerate(morse_code.split()):
        try:
            message += MORSE_DECODING[sequence]
        except KeyError:
            raise ValueError(f'Cannot decode code "{sequence}" at {index}.')

    return message

Correctness
Your Encrypt function currently always returns a trailing space. You can avoid that by returning output[:-1].
Terminology
Converting from morse code to text back and forth is not really an encryption in its sense. You might want to rephrase {en,de}crypt with {en,de}code.
Globals
Using global variables like outputMessage can have nasty side-effects when the program is used as a library. All the code below the def Play_Sound function should go into a def main() function that you can invoke via
if __name__ == '__main__':
    main()

At the bottom of the unit.


The slowest part will be the request to the remote server. There is not much you can do to make this faster. You may want to cache the results you get back from hostip, or you may want to have a local database.

Furthermore, the API seems to return XX if it does not know the country, you may want to check for that.

Also, you do not close the InputStream or the InputStreamReader, and it is possible that you do not close the BufferedReader when an exception occurs. I don't know exactly whether this will cause any problems.


Sort an array of sentences alphabetically, ignoring the first word if it equals 'the' (case insensitive)

With some testing, it should look like the below

function order_ignore_the($a, $b) {
    return strcasecmp(
        strcasecmp(substr($a, 0, 4), "the ") != 0 ? $a : substr($a, 4),
        strcasecmp(substr($b, 0, 4), "the ") != 0 ? $b : substr($b, 4)
    );
}

Main differences being:

Widening the search for "the" to include the space after. Otherwise, you're matching on things like "theater", etc.
The last substr should likewise have start position 4. Otherwise, you're comparing on the space after "the".
You'll want the main comparison to ignore capitalization, too.


First; I agree with the points made by @Austin. I like it that your code is written such that it is easy to read (which I find important).
However, I find the structure of the program a bit hard to follow. For example; there are two display functions (display_info and result). I would merge these or at the least group them together.

In Python there seem to be two schools: 1) put everything in a function (as a means of documentation), 2) create functions to aid "separation of concerns" and add comments for documentation. My guess is that @Austin is more a type-1 person and I am more a type-2 person. I would suggest to add comments (especially to document functions and function arguments).

These are some observations from my side:

a lot of functions take both the player as the dealer as argument, while their actions are similar. It could be benificial to create a more generic function for an action (stand/hit) and call that function separately. For example: create a function which asks the action of the dealer and a function asking the action of the player.
the dealer_play function always returns False. So I guess you can get rid of the return argument, as well as the 'while dealer_plays:' loop.
the results function seems overly complex to me. I would not call the function at all as long as the dealer or the player are still playing. This would remove the need to keep track of who is still playing. Print the intermediate scores separately and evaluate the winner after the game.
there is no need to provide a boolean for first_hand. Each player and dealer always start with two cards. So len(cards)==2 gives the same information. For readability it could be good to perform this action at the start of the function (first_hand = len(dealer) == 2), as this way there is no need to change the code too much and you remove the burden of keeping track of this variable from the function-caller.

There is one other point that caught my eye: you are mixing different string formatting methods (''.format() vs f-strings). I would choose one of the methods and stick with that.

All these comments might seem like I do not like your code. This is not the case, my aim is to point out some possible improvements.


Is this code thread-safe - Singleton Implementation using Concurrent Dictionary

Never create two connection objects with the same parameters. If one exists, use it.

If you really need to guarantee this, then I think you will need to use locking instead of ConcurrentDictionary.

If it's okay to create duplicate Connections (that will never be used) in rare circumstances, then you can use an overload of GetOrAdd() that takes a lambda that creates the Connection:

return activeConnections.GetOrAdd(
    Tuple.Create(param1,param2), _ => new Connection (param1, param2));

With your current code, every time you call getInstance(), a new Connection is created and then most of the time thrown away.


}catch (Exception e){
    System.out.println("Popping off an empty stack:" + e);
}

Why? You should be able to know if your stack is empty before you even try to pop it. And in that case, any consumer of that Stack class is going to expect an exception to be thrown.

Actually, something's fishy about that catch block.

Stack<int> foo = new Stack<int>();
foo.pop();

What does that do? head is null, you've made sure... twice.

Once here:

private Node head = null;

And another here:

public Stack(){
    size = 0;
    head = null;
}

The constructor seems redundant.

Now, with head being null, foo.pop() will throw a rather surprising NPE, despite that try/catch block seemingly handling the "stack is empty!" case.

You should avoid having that NPE thrown, and instead throw an EmptyStackException, for which your consumer code will be thankful.


Printing a Binary Tree top-down (column wise)

Using recursion in this instance helps a lot to reduce code duplication. Particularly, in this case, you have different code blocks depending on whether left() or right() are null.

Using recursion you only need one null check, and this removes a big chunk of code.

The queue is only needed for recursion as well, and, it's purpose was hard to figure out... you should have documented it more carefully...

The map variable is also a variable which has a poorly documented purpose... it's hard to tell what variables are on that, and why.

All in all, your suspicions are right that there's a better way to do this.....

Algorithmically it strikes me that a single Map<List<Integer>> is probably the right structure, and that recursion is a better solution.... consider a recursive function:

recurseTraverse(final Node<Integer> node, final Map<Integer, List<Node<Integer>>> columnmap, final int column) {
    if (node == null) {
        return;
    }
    List<Node<Integer>> list = columnmap.get(column);
    if (list == null) {
        list = new ArrayList<Node<Integer>>();
        columnmap.put(column, list);
    }
    list.add(node);
    recurse(node.left(), columnmap, column - 1);
    recurse(node.right(), columnmap, column + 1);

}

Then calling that with a TreeMap<Integer, List<Node<Integer>>> you should be able to get an improved version of your result.

public void traverse(Node<Integer> root) {
    TreeMap<Integer, List<Node<Integer>>> columnMap = new TreeMap<>();

    recurseTraverse(root, columnMap, 0);

    for (Entry<Integer, List<Node<Integer>>> entry: columnMap.entrySet()) {
        System.out.println("Column - " + entry.getKey() + " : " + entry.getValue());
    }
}

Update: It has been pointed out by Fihop that this answer produces the incorrect results. While it correctly puts each node in to the correct column, it adds them in a depth-first order:

  The accepted solution actually does not work. For example:

    1
   / \
  2   3
   \
    4
     \
      5

  it gives:

2
1 4
5 3 => should be 3 5???

The right solution to this problem is to perform a breadth first traversal (traversing each row of the tree at a time), which requires a queue, and recursion is no longer the best, or even a viable, solution.

In re-working this answer, I have also actually run the code (rather than just typing it in to an answer), and I have almost 2 more years of experience on this. So, there are some other things to point out.

First up, this code can now use Java 8, and the computeIfAbsent() Map method.

Next, using static methods that are also generic methods makes the dependence on Node<Integer> become the generic Node<N>. I have still worked the example using Integers, and I have invented what I believe the Node class should be. It's not exactly the way I would write it because the method names left() and right() would probably be named differently. I have also created a rudimentary toString.

Finally, to work the traversal a helper container-class ColumnFind was created to link a node to a column, and allow the temporary storage of the column for when the next level of the tree is traversed.

It pains me that the traversal and the println calls are in the same method, I feel they should be separate, but to keep the code consistent with my earlier answer, I will leave it like that. A Java 8 function passed in to the traversal would be a better solution....

So, here's the traversal code (and it is working in ideone here: http://ideone.com/p8RWmE ).

public static final <N> void traverse(Node<N> root) {

    final TreeMap<Integer, List<Node<N>>> columnMap = new TreeMap<>();
    final Queue<ColumnFind<N>> queue = new LinkedList<>();

    queueChild(0, root, queue);

    while (!queue.isEmpty()) {
        ColumnFind<N> cf = queue.remove();
        int column = cf.column;
        Node<N> node = cf.node;
        columnMap.computeIfAbsent(column, c -> new ArrayList<>()).add(node);
        queueChild(column - 1, node.left(), queue);
        queueChild(column + 1, node.right(), queue);
    }

    for (Entry<Integer, List<Node<N>>> entry: columnMap.entrySet()) {
        System.out.println("Column - " + entry.getKey() + " : " + entry.getValue());
    }
}

private static final <N> void queueChild(int column, Node<N> node,
                 Queue<ColumnFind<N>> queue) {
    if (node == null) {
        return;
    }
    queue.add(new ColumnFind<>(column, node));
}


Why don't you unroll the inner loop?  So the final method will be like

private void writerContent(Integer firstRow, List<Record> records) {
    XSSFSheet sheet = workBook.getSheetAt(0);
    for (int lineId=firstRow; lineId<records.size(); lineId++) {
        Record rec = records.get(lineId);
        Row row = sheet.getRow(lineId);
        row.createCell(0).setCellValue(rec.getNumber());
        row.createCell(1).setCellValue(rec.getName());
        row.createCell(2).setCellValue(rec.getCode());
        row.createCell(3).setCellValue(rec.getCount());
        row.createCell(4).setCellValue(rec.getSimultaneouslyProcessedProducts());
        row.createCell(5).setCellValue(rec.isSimultaneousProcessing());
        row.createCell(6).setCellValue(rec.getInterchangeability());
    }
}


Reducing the amount of code in any program is good because that reduces the possible errors or bugs in the code. Providing general functions that can be reused is a good habit to get into.

DRY Code

There is a programming principle called the Don't Repeat Yourself Principle sometimes referred to as DRY code. If you find yourself repeating the same code multiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well.

As shown in another answer all the if statements of the form

        if (diceRoll1 == **x** && diceRoll2 == diceRoll1 && diceRoll3 == diceRoll1) {
            printf("Congratulations! You won **YY** credits.\n");
        }

Can be reduced to a simple function that can be reused.

This code can also be simplified, although it is not absolutely necessary

    diceRoll1 = (rand() % 6) + 1;
    diceRoll2 = (rand() % 6) + 1;
    diceRoll3 = (rand() % 6) + 1;

Can be

static constexpr int dieFaces = 6;      // Allows the number of faces of the dice to be changed in one place
                                        // if this is used in a board game such as D & D

int rollOneDie()
{
    return (rand() % dieFaces) + 1;
}

void rollTheDice(int &die1, int &die2, int &die3)
{
    die1 = rollOneDie();
    die2 = rollOneDie();
    die3 = rollOneDie();
}

Any time I see variables with the names var1, var2 and var3 I see the potential for using an array instead of separate variables. The entire program might be simplified if instead of 3 separate variables diceRoll1, diceRoll2 and diceRoll3 there was one array of dice. This would also allow the program to be easily changed so that more or less dice are used.

static constexpr int diceCount = 3;
static constexpr int highScore = 90;
static constexpr int normalScore = 40;
static constexpr int lowScore = 10;
static constexpr int noScore = 0;

void rollTheDice2(int dice[])
{
    for (int i = 0; i < diceCount; i++)
    {
        dice[i] = rollOneDie();
    }
}

bool allTheDiceEqualThisNumber(int dice[],int faceValue)
{
    for (int i = 0; i < diceCount; i++)
    {
        if (dice[i] != faceValue)
        {
            return false;
        }
    }
    return true;
}

int earnCredit(int dice[])
{
    if (allTheDiceEqualThisNumber(dice, dieFaces))
    {
        return highScore;
    }
    else if (allTheDiceEqualThisNumber(dice, 1))
    {
        return lowScore;
    }
    else
    {
        for (int i = 2; i < dieFaces - 1; i++) {
            if (allTheDiceEqualThisNumber(dice, i)) {
                return normalScore;
            }
        }
    }
    return noScore;
}

void showDice(int dice[])
{
    printf("Your dices are ");
    for (int i = 0; i < diceCount; i++)
    {
        printf("%d ", dice[i]);
    }
    printf("\n");
}

void playGame()
{
    int diceRolls[diceCount];

    rollTheDice2(diceRolls);

    showDice(diceRolls);

    int newCredits = earnCredit(diceRolls);
    if (newCredits > 0)
    {
        printf("Congratulations! You won 90 credits.\n");
    }
}

Complexity

The function main() is too complex (does too much). As programs grow in size the use of main() should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.

There is also a programming principle called the Single Responsibility Principle that applies here. The Single Responsibility Principle states:

  that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.

int main(void)
{
    srand((int)time(NULL));

    char yn;

    do {
        printf("\nDo you want to play? (y/n): ");
        scanf_s("%c", &yn);
        getchar();

        if (yn == 'n') {
            printf("Coward!");
            getchar();
            return 0;
        }

        playGame();

    } while (yn != 'n');

    getchar();
    return 0;
}

Magic Numbers

There are Magic Numbers in the main() function (6, 90, 40, 10), it might be better to create symbolic constants for them to make the code more readble and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier.

Numeric constants in code are sometimes referred to as Magic Numbers, because there is no obvious meaning for them. There is a discussion of this on stackoverflow.

The possible symbolic constants are show in the examples for DRY Code

C versus C++

This question was originally tagged with C rather than C++. The strict version of C can't compile #include <iostream>, it uses #include <stdio.h> instead. Also input in C++ generally prefers

std::cin >> variableName;

over scanf, scanf_s or getchar() and

std::cout << "Your score was " << variableName << "\n";

over printf().

C++ also has a newer random number generator with better distribution using #include <random>.


Set the entitlement of a case based on record type

Well done on your first try for Apex code.

A few pointers:

Record types aren't always available for all users, when doing logic on Record types by Name I usually add a Formula to retrieve the name (one less query and I can control the permissions)
Don't add queries in for loops, you could / would hit SOQL limits very very quicly

I haven't proven that this will work but here is an example of what you should do:

trigger SetCaseEntitlementOnInsert on Case (before insert) {
    System.debug('SetCaseEntitlementOnInsert executed');

    // 1) Loop through the Case(s) to be inserted.
    // 2) Get the Entitlement for each based on the RecordType.
    // 3) Retrieve the Entitlement.
    // 4) Assign the Entitlement to the Case

    // Assuming you create a custom field with a Formula to retrieve RecordType.Name with API name RecordTypeName__c

    // Collection of Entitlement Names
    Set<String> theEntitlementNames = new Set<String> {
        'Priority 1',
        'Priority 2',
        'Priority 3',
        'Priority 4'
    };

    // Query the Entitelments
    List<Entitlement> theEntitlements = [SELECT Id, Name FROM Entitlement WHERE Name IN :theEntitlementNames];

    // If we have Entitlements
    if (!theEntitlements.isEmpty()) {

        // Map the Entitlement Ids by Name
        Map<String, Id> theEntitlementIdsByName = new Map<String, Id>();
        for (Entitlement theEntitlement : theEntitlements) {
            theEntitlementIdsByName.put(theEntitlement.Name, theEntitlement.Id);
        }

        // Now for each Case
        for (Case theCase : Trigger.New) {
            if (theCase.RecordTypeName__c == 'Trouble Tickets') {
                theCase.EntitlementId = theEntitlementIdsByName.get(theEntitlementNames[0]);
            } else if (theCase.RecordTypeName__c == 'Access Request/New Hire') {
                theCase.EntitlementId = theEntitlementIdsByName.get(theEntitlementNames[1]);
            } else if (theCase.RecordTypeName__c == 'Purchase Order') {
                theCase.EntitlementId = theEntitlementIdsByName.get(theEntitlementNames[2]);
            } else {
                theCase.EntitlementId = theEntitlementIdsByName.get(theEntitlementNames[3]);
            }
        }

    }
}


Keyboard handler to move a shape in response to arrow keys

If you move shipLeft and shipTop into an object called shipPositions rather than just top level variables, you could also use a map-driven approach like this:

function anim(e) {
    var key = e.KeyCode || e, val, info;
    var keyMap = {
        "37": {direction: "left", ship: "shipLeft", delta: -11},
        "39": {direction: "left", ship: "shipLeft", delta: 11},
        "40": {direction: "top", ship: "shipTop", delta: 11},
        "38": {direction: "top", ship: "shipTop", delta: -11},

    };
    info = keyMap[key];
    if (!info) {
        return;
    }
    shipPositions[info.ship] += info.delta;
    val = shipPositions[info.ship];
    ship.style[info.direction] = val + 'px';
    changeColor();
    return val;
}


Sorting elements in array with a certain condition

How can I make the function look better?

One alternative approach to the switch statement inside get_sort_by_key() is to define a lookup-table using an array:

define('KEY_MAPPING',array('lng','topic','page','sort','search'));

(or it could be a constant defined on a class if such a relevant class exists).

Then the code block in the foreach can be simplified using array_search() to see if a corresponding index is returned. If not (i.e. it returned false) then use 5 as the fallback value.

foreach ($array as $key => $value) {
    $key = strtolower(trim($key));
    $order = array_search($key, KEY_MAPPING);
    if ($order === false) {
        $order = 5;
    }
    $new_array[$order][$key] = $value;
 }

See this playground example for a demonstration.

For small lists of parameters like this the time difference won't be much. I found this SO question from 6 years ago (and the results may have changed since Ariel's answer as PHP internals have changed but likely not by much).

I tried to find some online posts comparing switch statements with array lookups. The first couple results I see in Google are 6-9 years old:

TechnoSophos: Microbenchmarking PHP: Switch Statements are Slow
DevShed: PHP: The Switch Statement and Arrays ("can they not indent??")
ExceptionsHub: In PHP what's faster, big Switch statement, or Array key lookup

The general consensus is that the array lookup is faster. And typically it can require fewer lines of code. There is a quote somebody said (I can't remember who, so if you know who to give credit please let me know): "The easiest line to debug is the line you didn't write".


As far as I can see you are not using user input in your queries so there really isn't any security issue. When using user input in queries always make sure it's through prepared statements.


Convert String to Integer (calculator app)

You had the right idea to use to encapsulate the variables and operations in a class object or struct, rather than using the global scope. It was not clear why this did not work for you.

To make things easy you can declare the object in the same file as the view controller.

E.g.

// Declare a struct to encapsulate the x and y variables.
// Perform the add and subtract operations using the instance variables.
// This code can be moved into Arithmetic.swift
struct Arithmetic {
   let x: Int
   let y: Int

   // Create a convenience initialiser for code which can be reused.
   init(x: String, y: String) {
       self.x = Int(x) ?? 0
       self.y = Int(y) ?? 0
   }

   // Use encapsulation to perform the operations.

   func add() -> Int {
       return x + y
   }

   func subtract() -> Int {
       return x - y
   }
}

class ViewController: UIViewController {

    // You correctly defined the IBOutlets as weak to prevent retain cycles.
    // Property names should begin with lower-case.
    @IBOutlet weak var displayX: UITextField!
    @IBOutlet weak var displayY: UITextField!
    @IBOutlet weak var resultat: UILabel!

    @IBAction func performAddition(_ sender: UIButton) {

        // Use a guard condition to unwrap the variables.
        // Doing this avoids crashes when you force unwrap a nil.
        guard let x = displayX.text, let y = displayY.text else {
            return
        }

        let a = Arithmetic(x: x, y: y)
        let r = a.add()
        resultat.text = "The result of addition is: \(r)"
    }

    @IBAction func performSubtraktion(_ sender: UIButton) {
        guard let x = displayX.text, let y = displayY.text else {
            return
        }

        let a = Arithmetic(x: x, y: y)
        let r = a.subtract()
        resultat.text = "The result of subtraction is: \(r)"
    }
}


Convert a dictionary of iterables into an iterator of dictionaries

Interesting question.

I decided to look only at itertools.product(*map(pair_iter_safe, <the_dict>.items())) and pair_iter_safe.

The way I look at it is from a theoretic memory usage perspective. Due to how you have defined it, all (key, value) pairs need to be in memory at the same time, which could take a bit of memory.

I would suggest the following:

def iter_safe(value):
    if isinstance(value, str):
        value = (value,)
    try:
        iter(value)
    except TypeError:
        return (value,)
    else:
        return value

And using it as follows:

def dict_combinations(d):
    keys, values_list = zip(*d.items())
    for values in itertools.product(*map(iter_safe, values_list)):
        yield dict(zip(keys, values))

To me this is cleaner, having separated out the iter_safe logic from the dicts.

Though merely theoretical, I think this should save on memory usage due to there not being as much key-value pairs in memory all the time.

Of course, if you still want pair_iter_safe, you should be able to do something like

def pair_iter_safe(kv_pair):
    key, value = kv_pair
    for v in iter_safe(value):
        yield key, v


Get the indices of a range elements by relative order of the values

Two thing I noticed I can do are:

use std::less<T> as a default comparator class
set a default value for the comparator parameter, using the default initializer of the comparator class

The combination of these two cuts code length by half without reducing legibility (!):

template<
    typename RAIterator,
    typename Size = size_t,
    typename Compare = std::less<typename std::iterator_traits<RAIterator>::value_type>
>
inline std::vector<Size>
sorted_indices(RAIterator first, RAIterator last, Compare compare = Compare())
{
    std::vector<Size> result(last - first);
    std::iota(result.begin(), result.end(), (Size) 0);
    auto lookup_and_compare = [&first, compare](Size lhs, Size rhs) {
        return compare(first[lhs], first[rhs]);
    };
    std::sort(result.begin(), result.end(), lookup_and_compare);
    return result;
}

template<
    typename Container,
    typename Size = typename Container::size_type,
    typename Compare = std::less<typename Container::value_type>
>
inline std::vector<Size> sorted_indices(Container& container, Compare compare = Compare())
{
    return sorted_indices<typename Container::const_iterator, Size>(
        std::begin(container), std::end(container), compare);
}

The downside is that you must then depend on <iterator> and <functional>; since I use them already for other things, I don't really mind.


Simplifying a Scrabble Word Finder - Python

The program is pretty good and clean so far, the docstrings are clear and it's easy to follow what's going on.

The scores dictionary is a constant, so it should be all uppercase.

Use a context manager to open the text file. This way you don't have
   to worry about the file not being closed, as the context manager does it for you.

def look_up():
    """Create the variable containing the master list of words."""
    with open('sowpods.txt', 'r') as f:
        return f.read().split('\n')

def calc_score(word):
    """Calculate the score of a given word."""
    word_score = 0
    for x in word:
        word_score += scores[x]
    return word_score

This can be rewritten using a list comprehension.

def calculate_score(word):
    """Calculate the score of a given word."""
    return sum([SCORES[letter] for letter in word])

As you can see, we don't need to initialize an empty variable. Python is a self-documenting language.x isn't really a descriptive name, so I took the liberty to change it to letter. This one is a nitpick really, but I also change the function name to calculate_score.

Staying on comprehensions, you can use a dictionary comprehension in dict_maker. Here, we create a list of letters using list comprehension and then return a dictionary containing the word and its score.

def dict_maker():
    """Create a dictionary of the words with their scores."""
    letters = [letter for letter in raw_input('Letters: ').lower()]
    return {word: calculate_score(word) for word in rack_check(letters)}

I'm a little short on time to look over the logic, so I will finish the rest later, but here's some quick observations.

In list_print you assigned a dictionary using dict as its name. This is fairly uncommon practice, as it shadows a builtin. More on builtins.
word_master = look_up() should be contained in rank_check function. Furthermore, you can even replace for item in word_master: with for item in look_up()


Avoid floating point
Actually I would advise the opposite of what @Xean said.  I would completely remove all floating point from your program, including any calls to pow and log.   I prefer your original loop to compute the number of digits.
The reason I don't like using floating point is that you might mysteriously get erroneous results due to roundoff errors.  For example, on my computer, when I do this:
val = pow(9, 17);

I get this result, which is off by one:
16677181699666568 (actual value should be one higher)

For your program, you could either write a simple function to compute the powers of ten you need, or even hardcode the four values you need since you are only using powers 12, 13, 14, and 15.


For only 2 or 3 instances, I may use multiple return statements, but only in the case of if-else chains or switches. Returns within a try catch block can be done, but also can become complicated when you start mixing in finally with it. In the case of try-catch blocks or several possible 'return' paths, I use a variable and set it as necessary, and return it at the end. If you want an early return to bypass some code, I tend to take that code and wrap it up in a separate method, and use an if statement with my value to return to determine whether to execute that method.

public static void main(String[] args) {
        System.out.println(getState() ? "successful" : "failed");
}

public static boolean getState() {
        boolean success = false;
        SAXBuilder builder = new SAXBuilder();
        File xmlFile = new File("tile.xml");
        Set<String> set = new TreeSet<String>();
        try {
            Document document = (Document) builder.build(xmlFile);
            Element rootNode = document.getRootElement();
            System.out.println(rootNode);
            success = true;
        } catch (IOException io) {
            System.out.println(io.getMessage());
        } catch (JDOMException jdomex) {
            System.out.println(jdomex.getMessage());
        }

        return success;
}


Using app.use only in routes that start with /admin

From Express docs:

Path

// will match paths starting with /abcd
app.use('/abcd', function (req, res, next) {
  next();
})

Path Pattern

// will match paths starting with /abcd and /abd
app.use('/abc?d', function (req, res, next) {
  next();
})

// will match paths starting with /abcd, /abbcd, /abbbbbcd and so on
app.use('/ab+cd', function (req, res, next) {
  next();
})

// will match paths starting with /abcd, /abxcd, /abFOOcd, /abbArcd and so on
app.use('/ab*cd', function (req, res, next) {
  next();
})

// will match paths starting with /ad and /abcd
app.use('/a(bc)?d', function (req, res, next) {
  next();
})

Regular Expression

// will match paths starting with /abc and /xyz
app.use(/\/abc|\/xyz/, function (req, res, next) {
  next();
})

Array

// will match paths starting with /abcd, /xyza, /lmn, and /pqr
app.use(['/abcd', '/xyza', /\/lmn|\/pqr/], function (req, res, next) {
  next();
})


Checking for differences between two (large) files

There are some basic issues here, as well as some algorithmic complexities, and then some advanced suggestions.

Basic issues relate to Java code conventions, etc.

Basics

Use try-with-resources. You have code which may fail, and leave open files lying around to be garbage collected. Consider the following code:

try (FileInputStream fi1 = new FileInputStream(_File1);
    FileInputStream fi2 = new FileInputStream(_File2);) {

    // do stuff with the files - they will be auto-closed.

}

The next thing, is why open the files if they are different lengths?

FileInputStream fi1 = new FileInputStream(_File1);
FileInputStream fi2 = new FileInputStream(_File2);

byte[] fi1Content = new byte[step];
byte[] fi2Content = new byte[step];

if(_File1.length() == _File2.length()) { //Assumption 1

The code above, should be:

if(_File1.length() == _File2.length()) { //Assumption 1
    FileInputStream fi1 = new FileInputStream(_File1);
    FileInputStream fi2 = new FileInputStream(_File2);

    byte[] fi1Content = new byte[step];
    byte[] fi2Content = new byte[step];

Use the power of the force, ... I mean parameters, Luke... I mean Daniel.

Your method should take the two files as parameters, not as class-level fields. As it stands, your code is not "reentrant", and it should be. Your method is:

public boolean compareStream() ....

but it should be

public boolean compareStream(File filea, File fileb) ....

Algorithm

Since you are comparing two files byte-by-byte, the hashing will make no difference. If the two files were on different machines, and you have a slow network between them, and if you could run the hashing algorithm remotely, then it probably makes sense to hash the two files on each side, and then just compare the small, and easy to transfer, hash result. Something like SHA-256.

So, there's no need to hash, just do byte-by-byte comparisons.

For large files like yours, why have such a small step size? Use something much larger like 4MB, not 4KB. It will make it much faster.

Alternatives

File IO is always slower than you want. Java has the NIO framework for higher-performance IO using Channels and Buffers. This would be a great time to learn how to use them, because, a 4MB Memory-Mapped IO operation on the two files will likely give you the best performance.

See the MemoryMapped IO JavaDoc

I ran up a test using NIO, and produced the following code:

public static final boolean compareFiles(final Path filea, final Path fileb) throws IOException {
    if (Files.size(filea) != Files.size(fileb)) {
        return false;
    }

    final long size = Files.size(filea);
    final int mapspan = 4 * 1024 * 1024;

    try (FileChannel chana = (FileChannel)Files.newByteChannel(filea);
            FileChannel chanb = (FileChannel)Files.newByteChannel(fileb)) {

        for (long position = 0; position < size; position += mapspan) {
            MappedByteBuffer mba = mapChannel(chana, position, size, mapspan);
            MappedByteBuffer mbb = mapChannel(chanb, position, size, mapspan);

            if (mba.compareTo(mbb) != 0) {
                return false;
            }

        }

    }
    return true;
}

private static MappedByteBuffer mapChannel(FileChannel channel, long position, long size, int mapspan) throws IOException {
    final long end = Math.min(size, position + mapspan);
    final long maplen = (int)(end - position);
    return channel.map(MapMode.READ_ONLY, position, maplen);
}

Note, the guts could be rewritten more concisely too:

            if (!mapChannel(chana, position, size, mapspan)
                   .equals(mapChannel(chanb, position, size, mapspan))) {
                return false;
            }

On my laptop, this is comparing 1.5GB files in under 2 seconds. Obviously, your milage may vary, and my laptop is an unknown beast.... but things that may play in to the equation:

I have 16GB mem
it's a 4 year old laptop
it has an SSD
there is file-system encryption
it runs linux.


Review of three constructors for a String class

Your lengths are off by 1 everywhere. An empty string has length 0 not 1, "Hello" has length 5 not 6, etc.

Your constructor from the const char* can just assign every character in the loop (since we know the nlengthth character of input will be \0, right? Even better would be to use memcpy:

nlength = strlen(input);
nstring = new char[nlength + 1];
memcpy(nstring, input, nlength + 1);

Also you have to be careful on the copy constructor. What happens in this code?

string hello("hello");
hello = hello;


Function to split strings on multiple delimiters

There's no need to iterate using that while, a for is good enough.

Also string concatenation (+=) is expensive. It's better to use a list and join its elements at the end1.

def split(s, delim=" "):
    words = []
    word = []
    for c in s:
        if c not in delim:
            word.append(c)
        else:
            if word:
                words.append(''.join(word))
                word = []
    if word:
        words.append(''.join(word))
    return words

As Maarten Fabré suggested, you could also ditch the words list and transform the function into a generator that iterates over (yields) each word. This saves some memory if you're examining only one word at a time and don't need all of them in one shot, for example when you're counting word frequency (collections.Counter(isplit(s))).

def isplit(s, delim=" "):  # iterator version
    word = []
    for c in s:
        if c not in delim:
            word.append(c)
        else:
            if word:
                yield ''.join(word)
                word = []
    if word:
        yield ''.join(word)

def split(*args, **kwargs):  # only converts the iterator to a list
    return list(isplit(*args, **kwargs))

There's also a one-liner solution based on itertools.groupby:

import itertools

def isplit(s, delim=" "):  # iterator version
    # replace the outer parentheses (...) with brackets [...]
    # to transform the generator comprehension into a list comprehension
    # and return a list
    return (''.join(word)
            for is_word, word in itertools.groupby(s, lambda c: c not in delim)
            if is_word)

def split(*args, **kwargs):  # only converts the iterator to a list
    return list(isplit(*args, **kwargs))

1 From https://wiki.python.org/moin/PythonSpeed: "String concatenation is best done with ''.join(seq) which is an O(n) process. In contrast, using the + or += operators can result in an O(n**2) process because new strings may be built for each intermediate step. The CPython 2.4 interpreter mitigates this issue somewhat; however, ''.join(seq) remains the best practice".


Picking the top 5 results for each individual

This is a solution using data.table and without loops.

require(data.table)

pred <- fread("/home/djhurio/Downloads/2023bd19b880.csv")

pred[, id := 1:.N]

# Melt to long format
data_long <- melt(pred, id.vars = "id", measure.vars = names(pred)[2:13],
                  variable.name = "country")

# Order data by id (A) and value (D)
setorderv(data_long, c("id", "value"), order = c(1, -1))

# Numerate records for each id
data_long[, i := 1:.N, by = id]

# Select top 5
data_long <- data_long[i < 6, .(id, country)]

data_long


Recording user response times for a quiz

Just some simple stuff,
a common.php file for common code used by both files. DRY don't repeat yourself.

Writing a script like you have is fine, the points i have noted will help you if you come back to maintain it in a year or so, and have forgotten how it works.

The bulk of programming jobs are about maintaining a code base, not creating new stuff, so if you can learn how to make maintenance easier, it will be beneficial for you in the long run. (I wish i had learnt this stuff much earlier on)

I have added inline comments explaining the changes i made

<?php
/* common.php */
require 'classes/Database.php';

session_start();
date_default_timezone_set("UTC");

?>

<?php
/* get_game_data.php
 *
 * user clicks button to start game
 * and triggers ajax request sent to this file
 */

require 'common.php';

// moved into common.php
// session_start();

if($_SERVER['REQUEST_METHOD'] === 'GET')
{
    if(isset($_GET['gamesettings'])){///check certian user defined game options are set

        // moved into common.php
//        require 'classes/Database.php';

        // moved into common.php
//        date_default_timezone_set("UTC");

        $_SESSION['app_start'] = new DateTime('NOW');////store time at which game/first question starts
        $_SESSION['app_index'] = 0;

        // warning if $_GET['app'] not set this will get a warning notice, we can never trust GET/POST data
        // if($_GET['app'] === 'aural') {
        if(isset($_GET['app']) && $_GET['app'] === 'aural') {

            $db = new Database();

            $gameData = getGameData($db);///just an example
            //etc...
            //query database for game data, i.e. the questions,

            // i prefer to do my internal logic before i output data. this way if something fails i can handle it prior to responding to the user
            $_SESSION['right_answers'] = $gameData['answers'];///store the right answers to varify against user answers later

            echo json_encode($gameData['questions']);//then send back to browser

        }

    }
}
?>

<?php
/* post_game_data.php
 *
 * user answers question in a textbox etc.
 * then clicks a submit button which posts the answer to
 * this file via ajax again
 */

require 'common.php';

// moved into common.php
//session_start();

// moved into common.php
// date_default_timezone_set("UTC");

if($_SERVER['REQUEST_METHOD'] === 'POST')
{
    // what you have done is not bad, i just prefer to have all user supplied data handled in one place, POST/GET
    // so i know that everything beyond here has been sanitized
//    if(
//       isset($_POST['user_answer']) &&
//       isset($_SESSION['app_index'])
//    )

    $userAns = isset($_POST['user_answer']) ? $_POST['user_answer'] : null;

    // good variable names can also help reduce the need for comments
    // which of these two following variable names are easier to understand

    // $index = $_SESSION['app_index'];///current question in the game
    $current_question_index = isset($_SESSION['app_index']) ? $_SESSION['app_index'] : null;

    if($userAns != null && $current_question_index != null)
    {

        // same here with variable naming
        // if you are going to maintain these scripts over time, you need to make it easier to remember what is going on

        // $len = count($_SESSION['words']);///number of questions in the game
        $num_questions = count($_SESSION['words']);

        // handled above, no need to repeat
        //      $userAns = $_POST['user_answer'];

        $rightAns = $_SESSION['right_answers'];

        // why use a comment here that could change over time when you can make an easily understandable function name instead
        // if(isset($_SESSION['app_start']))////if this is the first question
        if (is_first_question())
        {
            $responseTime = getTimeTaken($_SESSION['app_start']);
            unset($_SESSION['app_start']);

            // $_SESSION['question_start'] = new DateTime('NOW');
            start_question_timer();
        }
        // else if(isset($_SESSION['question_start']))///not the first question
        else if(is_question_started())///not the first question
        {
            $responseTime = getTimeTaken($_SESSION['question_start']);

           // $_SESSION['question_start'] = new DateTime('NOW');
            start_question_timer();
        }

        // which of these two is going to be easier to understand next year when you come back to maintain your script
        if ($current_question_index < $num_questions) {
    //    if($index < $len)
        {
            $crtAns = $rightAns[$current_question_index];

            // this is probably overkill in this case, but again why write a comment when you can write a nice function name
            // $mark = ($userAns == $crtAns)?1:0;///check user answer against correct answer
            $mark = mark_user_answer($userAns, $crtAns);

            // easy function names to make the code more understandable
            // $_SESSION['app_index']++;
            move_to_next_question();

            // given your if {} elseif {} statement above, $responseTime may not have been set, as there is no default case
            // this should be handled properly
            echo json_encode(array($crtAns, $mark, $responseTime));////send right answer to broswer with mark and response time
        }

    }

}

// move functions below main code as what is most important should come first
// perhaps this function could be called elapsedTimeInSeconds,
// get infers you are getting a value, and there is no indication what the return type might be
function getTimeTaken($startDTO) {

    // good variable naming, easy to understand what is happening
    $endDTO     = new DateTime('NOW');
    $timeDiff   = $startDTO->diff($endDTO);
    $timeTaken  = $timeDiff->format('%s');

    return $timeTaken;
}

function is_first_question() {
    return isset($_SESSION['app_start']);
}

function is_question_started() {
    return isset($_SESSION['question_start'];
}

//
function mark_user_answer($user_answer, $correct_answer) {
    return ($user_answer == $correct_answer) ? 1 : 0;
}

function move_to_next_question() {
    $_SESSION['app_index']++;
}

function start_question_timer() {
    $_SESSION['question_start'] = new DateTime('NOW');}
}

?>


Picking a random state from a set based on probabilities

There could potentially be millions of states, since each distinct word in the text I scan will be become a state. And they'll never change once calculated. I'm going to scan over a book, calculate the probabilities, then serialize the state/probability map to use later.

Given this, there are a couple more efficient approaches, depending on how much preprocessing you want to do. There's a great article, Darts, Dice, and Coins, that outlines this further and ends with an O(1) algorithm, Vose's alias method.

I think the most straightforward, though, is a binary search tree-based approach ("roulette wheel selection"). Same basic idea as your current code, fill [0, 1) with proportional sections corresponding to your state probability map:

[  :a  | :b |   :c   |:d|  :e  )
0    0.25  0.4     0.76 0.8    1

but then instead of looping over a list, use something like a TreeMap that is designed to answer these kinds of queries in O(log n).

(defn states->treemap
  "Builds a navigable map of `partial sum -> state`"
  [states]
  (->> states
    (reduce (fn [[entries sum] [k v]]
              (let [sum' (+ sum v)]
                [(conj entries [sum' k]) sum']))
            [[] 0])
    first
    (into {})
    (java.util.TreeMap.)))

(defn random-state [^java.util.NavigableMap nm]
  (.getValue
    (.ceilingEntry nm (rand))))

That's not "pure Clojure", obviously, but we're on the JVM and it's pretty idiomatic to pull from Java as needed. Otherwise, your Clojure looks fine to me, but definitely check out that article for further depth.


Here is a suggestion:

var tosCheckbox = $('.tos-checkbox');
var checkBoxValidation = (function(label, checkbox, errorDisplay) {
    var checked = checkbox.is(':checked');
    return function(e) {
        if (e.type == 'submit' && !checked) e.preventDefault();
        tosLabel.toggleClass('tos-is-checked', checked);
        formError.toggleClass('tos-error', !checked);
    }
})(tosLabel.closest('label'), tosCheckbox, formError.closest('label').find('.form-error'));

tosCheckbox.change(checkBoxValidation);
tosLabel.closest('form').submit(checkBoxValidation);

Baiscally I tried to make the code dependent/related to tosCheckbox, finding both label, error and form from that element. This avoids pointing to the wrong thing like '.form-error' which I see more than one in the page. This way only the one inside the label will receive the class.

DRYed also the event listener callbacks, the class add/remove and added a check to prevent the form submit event. Not sure you need this, but its a heads up in case you are not stoping the submit in case of error.

Hope it helps.


Starting with some Java API documentation:

  public class NoSuchElementException
  extends RuntimeException

  Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.

This is not an Enumeration and you have not called nextElement().  This is not an appropriate exception

sort() should really take a list as a parameter and return a sorted list.  Give it a list as a parameter; if a null is passed, Java will do you a nice NullPointerException, free of charge.  If the given list is simply empty, return an empty list.  Being asked to sort an empty list is not an exceptional error situation.  It's no more an error than being asked to sort a list with 1 element, which you do show you can do.

Which brings me to the more important stuff...

Method and object conflated and confused.

You've combined a sorting algorithm with the (hand-rolled) list to be sorted.  It would be better to have a properly usable list class and either a mergeSort method on that class or a static helper class with a MergeSort method that can act on any list object.  Then you could create a list, examine it to show that it was a well-functioning and populated list, create a mergeSort()-ed version, check that this was a valid list, that it still had all the right elements (none missing, none added or substituted) and that they were in the desired order.  You'd have something useful you could do more with.

List object cannot be tested/examined.

This is part of the problem created by the previous issue.  There's no way to get at the list data.  You print it out on the screen, but it's inaccessible to the rest of your code.  What use was the sort?  Did it even work?  How is this validated except by the naked eye?  Since you don't print the unsorted version out on the screen, how does the viewer know you did anything?

Make the list fully usable.  Provide a way to traverse and inspect it.  Then your code can verify the sort (and do something useful with the sorted data afterwards, if you like).

Printing directly from within the merge class.

Don't do this.  Have your class methods return useful values which can be inspected and tested.  Print out the results in your main method if you want, but don't litter your classes with println statements.

Final, what?

What do you think you are gaining with those final keywords?  Those local variables are going to evaporate when that tiny method returns, so what have you achieved?

I should go on to examine the actual sorting algorithm but I think I'll leave that to somebody else - it's late and I'm tired.


Avoid explicitly writing base class state in a derived class. Suggestions for my method

I think this is the right way to do it. If you have some code that should be used from the base class and all its derived classes, it should be in the base class. Which is exactly what you're doing.

But I would make a modification in your code. You don't need to use ref. In C#, classes are reference types, which means that the values in the object will change, even if you don't use ref. And if you remove the ref, you won't need the baseSettings variable anymore, making the code shorter:

protected void WriteBaseFooSettings(FooSettings settings)
{
    // set the properties, same as before
}

…

public override FooSettings WriteSettings()
{
    var settings = new BarSettings();

    WriteBaseFooSettings(settings);

    // Write derived/local settings
    settings.d = d;

    return settings;
}


It is very, very unlikely that running multiple files in parallel will go any faster than running them all sequentially (your bottleneck will be 'internet' bandwidth regardless).

Is there something wrong with doing something like:

#!/bin/bash

SCPCMD="scp \"\$@\" root@host:/data/tmp"
# echo The scp command is: $SCPCMD

cat ${FLIST} | tr '\n' '\000' | xargs --null bash -c "${SCPCMD}"

The above script will convert newlines to null characters in the input list, then copy the files to the server.

You can add the -n 10 argument to xargs to do 10 files are a time, or whatever works for you. I like the -t argument as well which echos the xarg command to stderr before it runs it.

The above will copy only one stream at a time, but, it will do the files in bulk operations, and you will likely be limited by your network bandwidth, not the parallelism of your copies.

EDIT:

If you want to run the scp's in parallel, you can add the -P xx (--max-procs)argument to xargs, which will run as many as xx scp's in parallel for you. So, for example, if you have hundreds of files, you can scp them in 5 parallel streams, 5 files at a time, with:

cat ${FLIST} | tr '\n' '\000' | xargs --null -P 5 -n 5 bash -c "${SCPCMD}"


Decorator to measure execution time of a function

I'd recommend the timeit module when measuring the execution time of functions. AFAIK, timeit disables the garbage collector for the duration of the test, which might give you better results overall.

From here:

  timeit is more accurate, for three reasons:

  it repeats the tests many times to eliminate the influence of other tasks on your machine, such as disk flushing and OS scheduling.
  it disables the garbage collector to prevent that process from skewing the results by scheduling a collection run at an inopportune
  moment.
  it picks the most accurate timer for your OS, time.time or time.clock, see
  timeit.default_timer.

On the other side, a timing decorator is really useful because you can use annotations to sprinkle the timing around your code rather than making your code messy with timing logic everywhere. So yes, related to one of your questions, the code is useful.

Now, on the pythonic question, IMO:

you have too many comments which unfortunately didn't add any value to your code. Remove them.
your inner function could also be renamed to something more intuitive like wrapper.
function is also not the best choice when it comes to naming conventions as it might shadow the built-in function
use 2 newlines between imports and methods
the indentation should be a multiple of 4 (spaces)
use triple double quotes for your module docstring

In Python, there're already some useful modules to help you with this. For example, in functools you have the wraps decorator. This takes a function used in a decorator and adds the functionality of copying over the function name, docstring, arguments list, etc. And since wraps is itself a decorator I guess it'll make things a lot easier.

Code:

from functools import wraps
from time import time

def timing(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        start = time()
        result = f(*args, **kwargs)
        end = time()
        print 'Elapsed time: {}'.format(end-start)
        return result
    return wrapper

Usage:

@timing
def f(a):
    for _ in range(a):
        pass

print(f(2000000))

Result:

  Elapsed time: 0.0971460342407


Populating dropdown lists, using SQL vs. using expression trees and reflection

I'm going to start off by saying I didn't test this code.  There might be some issues but I didn't setup EF and an In Memory Provider.

First I would load all the types right away and cache them and do some filtering to make sure they have the two properties we care about.

You didn't save what your class name is so I'm going with DropDownLookUp

public class DropDownLookUp
{

    private DbContext _context;

    private readonly static IDictionary<string, Type> Mappings;
    private readonly static MethodInfo WhereMethod;
    private readonly static MethodInfo SelectMethod;

    static DropDownLookUp()
    {
        // Load up all the types and cache them making sure they have the properties we need
        Mappings = typeof(State).Assembly.GetLoadableTypes()
            .Where(x => x.GetProperty("IsApproved")?.PropertyType == typeof(bool) &&
                   x.GetProperty(x.Name + "Name")?.PropertyType == typeof(string))
                   .ToDictionary(x => x.Name, x => x);

        Func<IQueryable<object>, Expression<Func<object, bool>>, IQueryable<object>> whereMethod = Queryable.Where;
        WhereMethod = whereMethod.Method.GetGenericMethodDefinition();

        Func<IQueryable<object>, Expression<Func<object, object>>, IQueryable<object>> selectMethod = Queryable.Select;
        SelectMethod = selectMethod.Method.GetGenericMethodDefinition();
    }

We do a one time load of the LoadableTypes and have a type safe way to grab the method infos for the Queryable Select and Where clauses.

Type load I got from StackOverFlow it's like this

public static class AssemblyExtensions
{
    public static IEnumerable<Type> GetLoadableTypes(this Assembly assembly)
    {
        if (assembly == null)
        {
            throw new ArgumentNullException("assembly");
        }
        try
        {
            return assembly.GetTypes().Where(x => x.IsPublic);
        }
        catch (ReflectionTypeLoadException e)
        {

            return e.Types.Where(t => t != null && t.IsPublic);
        }
    }
}

Now we don't want to drop down into IEnumerable until we have to.  We want to stay in ExpressionTrees and build up an IQueryable.

private Expression CreateSelectExpression(Expression source)
{
    var param = Expression.Parameter(source.Type);
    var project = Expression.Property(param, $"{source.Type.Name}Name");
    var selector = Expression.Lambda(typeof(Func<,>).MakeGenericType(source.Type, typeof(string)), project, param);
    return Expression.Call(SelectMethod.MakeGenericMethod(source.Type, typeof(string)), source, selector);
}

private Expression CreateWhereExpression(Expression source)
{
    var param = Expression.Parameter(source.Type);
    var filter = Expression.Equal(
        Expression.Property(param, "IsApproved"),
        Expression.Constant(true));

    var whereClause = Expression.Lambda(typeof(Func<,>).MakeGenericType(source.Type, typeof(bool)), filter, param);
    return Expression.Call(WhereMethod.MakeGenericMethod(source.Type), source, whereClause);
}

These methods now call the Queryable.Select and Queryable.Where.    If you want you could cache these methods per Type but I find building Expressions isn't that taxing, where compiling them is, but it's worth testing to see if you want to add some cache to these methods.

For the main method we can just check the Mappings and if not found either return empty enumerable or throw.  We can still use the reflection on Set. If you really wanted you could build an expression tree to give you back the IQueryable when passing in a type.  I would base that on if you have performance issues or not.

public async Task<IEnumerable<string>> GetLookupOptions(string table)
{
    Type type;
    if (!Mappings.TryGetValue(table, out type))
    {
        // Or you can throw your choice
        return Enumerable.Empty<string>();
    }

    // Get the DbSet<T> for the <table>.
    IQueryable set = (IQueryable)_context.GetType()
        .GetMethod("Set")
        .MakeGenericMethod(type)
        .Invoke(_context, new object[0]);

    var query = set.Provider.CreateQuery<string>(CreateSelectExpression(CreateWhereExpression(set.Expression)));
    return await query.ToListAsync().ConfigureAwait(false);
}

We can use the IQueryable Provider to create a new Query based on the expressions we build - which should execute the where and select up on the server and we can now use the ToListAsync to make the method async again.


Algorithm
What you have implemented is called (linear) insertion sort. It is very old, sorry your method is not new or novel ;) It has average case O(n^2) time complexity which is basically unusable for anything with more than a few thousand/tens of thousands elements. I recommend that you study the classic algorithms: Bubble Sort, (Cocktail) Shaker Sort, Insertion Sort, Shell Sort, Merge Sort, Heap Sort, Radix Sort and Quick Sort.
There is a classic video from 1981 that is part of many CS curriculums called Sorting out Sorting which is very illustrative and a recommended watch.
Code
You never use type_contained remove it.
Once the unused type is removed you can change your template parameter to the iterator type directly and get rid of a lot of typing. This also allows template parameter deduction so that you don't have to explicitly state the container type as a template parameter.
Please don't reuse the argument beginning as a variable. It is hard to read when your iteration variable is named begin with another being original begin. Simply make a copy of begin, call it it for iterator or current.
Typically when two iterators are used to represent a range we use the names: first and last. To not confuse with begin() and end() and avoid a name collision when some one uses using namespace std;  (which you shouldn't!).
In general I'm not fond of your naming. For example check_back could simply be previous.
You don't need the inline specifier. You need a better algorithm. The compiler will automatically inline if it makes sense.
Bug
In the code here:
while (beginning <= end)
{
    if (*beginning > *(beginning + 1))

you will dereference the end iterator + 1 which is beyond the end of the range. Also note that typically one expects the first iterator to be inclusive and the second to be exclusive (as is returned from begin() and end() on containers). So when used as expected your code will go 2 elements outside of the range. This results in undefined behaviour.
Also here:
std::swap(check_back, --check_back);

you are swapping the iterators, not the values they point to. Which means that the code doesn't even work at all. It gets stuck in an infinite loop, always. Not only that, but the order in which the arguments are evaluated is undefined so this type of code might not work if the check_back variable is decremented first.
You would have noticed all of the above if you tried to use this code in any way before posting to review. For future reference, we only review working code and this question is actually off-topic due to it not working at all.
Cleaning it all up and fixing the bugs we get:
#include <iterator>
#include <algorithm>

template <typename Iterator>
void sort(Iterator first, Iterator last){
    auto it = first+1;
    while (it < last){
        auto prev = it;
        while (prev != first && *(prev-1) > *prev){
            std::iter_swap(prev-1, prev);
            prev--;
        }
        it++;
    }
}


Repeatedly partitioning an array equally as far as possible

The implementation of the algorithm, using a helper recursive method, is very clear. It is easy to see what the code is doing:

There are 2 base cases: there are only 0s, in which case the size of the array is the score, and the size is zero, in which case the score is 0.
Then, for all possible sizes, we keep the maximum of the score of the left array versus the right array when they have equal sum, adding 1.

There are simplifications possible, and improvements in terms of style and namings.

Namings

The first point to consider is naming: splitPossible is a terrible name for this method. It doesn't convey what it's doing. Rename it to getMaxScore, since this is what it does: gets the maximum score for the given array in the given bounds.

Also, consider "hiding" the recursive implementation inside a new method by creating a method passing the initial values:

public static int getMaxScore(int[] array) {
    return getMaxScore(array, 0, array.length - 1);
}

private static int getMaxScore(int[] array, int start, int end) {
    // rest of code
}

This way, the caller just needs to invoke getMaxScore(array), without worrying about the initial value of the recursive algorithm; and it gives you the possibility to update the code in the future (to an iterative method for example) without changing the calling code.

Style

You should always reformat your code in order to have proper indentation. Right now, it isn't the case and makes the code harder to read for no reason.

int sum = 0;

is unused in the program, so you should remove it.

if (sumOfArray(array, start, start + i) != sumOfArray(array, start + i + 1, end)) {
  continue;
} else {
  count += 1;
  return count + Math.max(getMaxScore(array, start, start + i), getMaxScore(array, start + i + 1, end));
}

is the logic for the recursive calls. In this case, there is no need to use a continue statement: those can sometimes help understanding the logic when there would be a lot of code in the else branch. They introduce a sort of early-return inside the for loop. But in this case, it clutters up a bit, and you can simply have:

if (sumOfArray(array, start, start + i) == sumOfArray(array, start + i + 1, end)) {
    count += 1;
    return count + Math.max(getMaxScore(array, start, start + i), getMaxScore(array, start + i + 1, end));
}

A couple of more comments here: count += 1; is more generally written count++ (or ++count), but in fact, there is no need for this as you can just add 1 to the result of the next line:

return 1 + count + Math.max(getMaxScore(array, start, start + i), getMaxScore(array, start + i + 1, end));

Arguably, this line is starting to become a bit crowded, so it is possible to store the two intermediate recursive results in temporary variables:

int leftScore = getMaxScore(array, start, start + i);
int rightScore = getMaxScore(array, start + i + 1, end);
return 1 + count + Math.max(leftScore, rightScore);

Improvements

You have an early return in case the size is 0, to return 0. While that can make the code easier to follow in certain situations, in this case, it's not needed at the rest of the code handles size = 0 just fine. Actually, the for loop is not entered, and we directly return the count, which is 0. Consider removing this special case (it also doesn't lead to performance improvements).

But why is there a count variable in the first place? It's initialized to 0, and in fact never changes. It's actually really unneeded: when making the recursive call, the total score is always the maximum score of the left and right split, plus 1. You can safely remove this count variable.

The first if, in case the array only contains 0, can be written more simply as well: start == 0 && end == array.length - 1 is equivalent to size == array.length.

The recursive method now looks like:

public static int getMaxScore(int[] array, int start, int end) {
    int size = end - start + 1;
    if (sumOfArray(array, 0, array.length - 1) == 0 && size == array.length) {
        return array.length - 1;
    }
    for (int i = 0; i < size; i++) {
        if (sumOfArray(array, start, start + i) == sumOfArray(array, start + i + 1, end)) {
            int leftScore = getMaxScore(array, start, start + i);
            int rightScore = getMaxScore(array, start + i + 1, end);
            return 1 + Math.max(leftScore, rightScore);
        }
    }
    return 0;
}

Finally, something can be done to simplify this first early-return. When all the elements in the array are 0, the recursive calls inside the for loop handle the case fine as well: they will increment the count by 1 each time, finally ending up with array.length - 1. But we can't get total rid of it: the way the algorithm is build, splitting each array into smaller chunks, the special case is when size == 1, and in this case, it is impossible to split it evenly, so the answer is 0. So we could have

if (size == 1) {
    return 0;
}

which avoids traversing the array entirely.

Further improvements

It might sound a bit strange to you, as it probably is to new developers, but a lot of APIs, for all programming languages, very often deal with ranges in an open-half manner: when asked for something in the range from start to end, it will generally be implied start inclusive to end exclusive (like Python slice, C++ APIs, and in Java, look at Random.nextInt, IntStream.range, List.subList or String.substring). The current code implies that the end is inclusive, which, actually, makes it that bit harder to follow for those accostumed to those practices. And switching to an exclusive end will make the code even easier:

// start inclusive, end exclusive
public static int getMaxScore(int[] array, int start, int end) {
    for (int i = 1; i < end - start; i++) {
        int split = start + i;
        if (sumOfArray(array, start, split) == sumOfArray(array, split, end)) {
            return 1 + Math.max(getMaxScore(array, start, split), getMaxScore(array, split, end));
        }
    }
    return 0;
}

// start inclusive, end exclusive
public static int sumOfArray(int[] array, int start, int end) {
    int sum = 0;
    for (int j = start; j < end; j++) {
        sum += array[j];
    }
    return sum;
}

There is no need to have special cases for a size of 0 or 1; the code handles them already.
There is a clear split index, which corresponds to where the left and right arrays are split.

All the test cases still pass after making those changes.


This looks great. Honestly, there isn't anything I'd change. You could make it more pointfree in some parts, but that's not going be more readable or maintainable.

Magic numbers

The only part I'd change are the static dimensions in main. Those are fine in a toy program, but a proper one will need some kind of configuration, so make sure that you use proper values from the beginning:

main :: IO ()
main = display FullScreen white . scale width height . pictures $ [
        color blue $ graph f (l, r, b, t) 0.001,
        color black $ Line [(origin, b), (origin, t)],
        color black $ Line [(l, origin), (r, origin)]
    ]
    where
        f :: Float -> Float
        f x = 1 / (x - 1)

        -- easy configurable:
        (l, r, b, t) = (-10, 10, -10, 10)
        width  = 20
        height = 20
        origin =  0

That way you can also exchange the values with proper command line interpretation

main :: IO ()
main = do
    (l, r, b, t) <- getDimensions
    let width = r - l
    let height = t - b
    let origin = ...
    display FullScreen white . scale width height . pictures $ [
...

After all, no magic numbers is a good practice in both imperative and functional languages.

Next, I'd introduce GraphBound as a type synonym, just to make graph's type signature easier on the eye:

-- | Graph boundaries, given in (left, right, bottom, top) order
type GraphBound = (Float, Float, Float, Float)

graph :: (Float -> Float) -> GraphBound -> Float -> Picture
graph f (l, r, b, t) dx = pictures $ map Line visible
    ...

You might even exchange GraphBound with a proper data type later which checks does not export its constructor to make sure that you don't end up with left = 20 and right = -10:

makeGraph :: Float -> Float -> Float -> Float -> Maybe GraphBound

However, that's an overkill, so let's not focus on that for too long.

List comprehensions vs. point-free

Now let's get back to your original query. Is it possible to make graph more point-free?

Sure:

graph :: (Float -> Float) -> (Float, Float, Float, Float) -> Float -> Picture
graph f (l, r, b, t) = pictures . map Line
                     . filter (all (\(_,y) -> b <= y && t >= y))
                     . (tail >>= flip (zipWith (\x y -> [x, y])))
                     . map (\x -> (x, f x))
                     . flip (enumFromThenTo l) r . (l+)

The point dx is completely gone from graph. However, the function is now unreadable. We went from a perfectly understandable function to a highly complex one. It gets a lot more readable if we use some helpers, but at that point we're almost back to your original function:

graph :: (Float -> Float) -> (Float, Float, Float, Float) -> Float -> Picture
graph f (l, r, b, t) = pictures . map Line . filter inGraph
                     . segments . points . ranged
   where
     inGraph (_,y) = fall (\(_,y) -> b <= y && t >= y)
     segments ps   = zipWith (\x y -> [x, y]) ps $ tail ps
     ...

That's not better than your original version, because your original version is already very good to begin with. The only change I could envision is a list comprehension in visible, but that's a matter of preference:

graph :: (Float -> Float) -> (Float, Float, Float, Float) -> Float -> Picture
graph f (l, r, b, t) dx = pictures lines
    where
        points = [(x, f x) | x <- [l,l+dx..r]]
        pairs  = zipWith (\x y -> [x,y]) points $ tail points

        lines = [Line segment | segment <- pairs,  all (\(_,y) -> b <= y && t >= y)) segment]

But you're the judge on which variant you want to use.

Other remarks

Thank you for using type signatures. Keep in mind that it's uncommon to use them in local bindings (where), as the outer function's signature should fix all types already. Inner type signatures can be a hassle if you change your outer type signature later, but they're sometimes necessary.


Workaround for unchecked cast of a deserialized Object to ArrayList

In general, the Java compiler knows the type of each variable, at every point during the execution. And when you operate on incompatible types, the program won't compile.

When you cast an object to ArrayList<Vehicle>, the Java runtime environment can only ensure that the cast to ArrayList<something> succeeds, but due to backwards compatibility (Java 1.4 from 2002), the cast will succeed, no matter if the arraylist contains Integer or String or Vehicle objects. Therefore, in this situation, the compiler warning tells you: Hey, you are doing something that cannot be checked, make sure you know what you are doing.

Your code that first deserializes the list as a raw type (ArrayList instead of ArrayList<Vehicle>) doesn't produce the compiler warning since the raw ArrayList is equivalent to ArrayList<Object>, and you won't get a surprising ClassCastException when working with this list.

If you are sure that the serialized list will only ever contain objects of type Vehicle, you can safely ignore that warning. In my code, I have written a utility function like this:

@SuppressWarnings("unchecked")
public static <T> T castToAnything(Object obj) {
    return (T) obj;
}

…

ArrayList<Vehicle> vehicles = castToAnything(in.readObject());

Another way is to not serialize the list, but to create a wrapper class:

public class SerializedData implements Serializable {
    public final ArrayList<Vehicle> vehicles = new ArrayList<>();
}

When you serialize this class and deserialize it, you still have to cast the type using (SerializedData) in.readObject(), but the warning goes away.

This still doesn't guarantee that the vehicles list contains only vehicles after deserialization, but that is an entirely different problem.