REST call helper function returns empty response on timeout errors

General Remarks

Avoid catching Exception, catch a specific exception instead to avoid silencing errors.
Don't return the empty list as an indication of failure. Either return None or (preferably, in case of failure) raise an exception.
It's nice to see you adopt typing as an important part of your code. I recommend being more consistent with it in places where you already use it, and using it even more. For example, two of the parameters in your function were not annotated, neither was the return value. Use type aliases to describe non-trivial types, such as input and output data of your requests (i.e., type of data and return type). A final example I'll show in the code is the use of enums instead of strings, which can prevent you from making mistakes.
I'm not going to say the function is "too complex". Yet. But if it grows to handle more HTTP methods (say, PUT, HEAD, ...), or the handling of the existing HTTP methods grows, you should seriously consider decomposing it into multiple functions or by incorporating object-oriented design.
Good job on the documentation attempt, but try to follow a set style in the future. Examples include PEP 287, NumPy, Google. A general guideline is given in PEP 257. This includes advantages such as consistency and automated generation of HTML docs using e.g. sphinx-doc.
Some of the control flow is a bit confusing. I've made edits to improve it (see below) and noted some explanations of the issues. I generally recommend you to investigate these further while writing the code.
I highly recommend you to read a style guide and stick to it, if you haven't already. I also suggest installing a linter so that you can be warned of dubious code style and possible bugs while writing the code. I'm fairly sure a linter would've complained about quite a bit of the remarks I'll give below. I'll give a concrete recommendation for a linter at the end of this answer.

Further recommended reads:

The Zen of Python (PEP 20).
PEP8 style guide (PEP 8), although you can occasionally find me diverging from the guidelines.

To apply a couple of quotes from PEP 20:

  Errors should never pass silently.

Your except Exception as err: guard would catch most of the exceptions that exist in Python, and thus also catches a potential AttributeError that may occur in your code. See my comments in the code for more details.

  In the face of ambiguity, refuse the temptation to guess.

I've had to guess multiple times to come to a purpose for some parameters, either because non-descript names, or because of missing type information. E.g., without looking at the function body, can I know whether I can pass a list as the data parameter? What is the branch parameter?

Personal Remarks

A couple of personal pet peeves related to your code:

Work on your variable names. I personally dislike names like data or resp since they don't really give much information. Similarly, the retry parameter is a bit misleading. Ideally, variable names should give me all the information required to understand their purpose (although this is often not possible when keeping them brief). Additionally, I'd like better names for err, but I name my caught exceptions exc too often so I'm not in a position to critique that :)
Don't spam the user with info logs that should be debug logs. The user doesn't care that your function is doing this or that. I suspect these may be debugging statements (use a debugger!), so use logger.debug so you don't have to change it later. Definitely never use print, since disabling that is non-trivial.

I've left a bunch of comments in your code while I was reading through it, and I've also rewritten a couple snippets to illustrate the difference.

"""Modules should always start with a docstring describing their exports.

Since this is just a snippet of one function, I'm assuming your module has one.
If not, write one.
"""
from typing import Any, Optional

import enum
import os
from json.decoder import JSONDecodeError

import requests
from requests.exceptions import HTTPError, RequestException, Timeout

# COMMENT: If I left these here, ignore these, they are just to make the code
# run.
class Logger:
    """Logging stub for review."""

    def debug(self, msg: str) -> None:
        print(msg)

    def info(self, msg: str) -> None:
        print(msg)

    def warn(self, msg: str) -> None:
        print(msg)

    def exception(self, msg: str) -> None:
        print(msg)

logger = Logger()
envs = os.environ

# COMMENT: Prefer custom data types for enumerated data instead of simple
# string literals such as 'get', 'post', ... This way, mistakes can be caught
# early by static analysis tools such as mypy, e.g. misspelling 'post' as
# 'psot'.
class RequestMethod(enum.Enum):
    """Enumeration of various request methods."""

    GET = 1
    POST = 2
    # PUT, DELETE, OPTION, HEAD, ...

ResponseType = Any  # TODO: Update the response type.

# COMMENT: PEP8 dictates line length to be limited to 79 characters. I,
# personally, feel like this is too short, yet this serves as an example of a
# possible method of breaking up your function signatures in case of overly
# long lines. This allows you to specify your types and default values so that
# they stand out immediately. Parameters are indented at two increments in
# levels, and the return type indented at the same level as the function name.
# This way, you can not confuse the return type signature, the parameter list,
# or the body of the function.
def use_service(
        branch: str,
        relative_url: str,
        # COMMENT: Nitpicky, but the correct terminology is "request method",
        # not "request type": https://tools.ietf.org/html/rfc7231#section-4
        # Both are pretty much used interchangeably though.
        request_method: RequestMethod = RequestMethod.GET,
        # COMMENT: Try to annotate all of your parameters, even those with
        # default values. Especially for `data`, which has a default value of
        # `None`, a type hint can be useful documentation. Additionally, mypy,
        # the state-of-the-art static type checker for Python, is sometimes
        # unable the parameter type, even if there are default values.
        # COMMENT: Give your parameters descriptive names. `data` is too
        # generic of a word. `retry` is less generic, and from just looking at
        # the name, I can get an idea of its purpose, but explicitly calling it
        # "number of tries" makes it immediately clear what the full purpose
        # is without reading the documentation.
        post_data: Optional[Any] = None,
        num_tries: int = 1
        # Always document your return types. mypy WILL complain about it if run
        # in strict mode.
) -> Optional[ResponseType]:
    """Perform a request and retry if it failed.

    Perform a request of type ``request_type`` to the given ``relative_url``
    and return the parsed JSON response. If the request fails for any reason,
    retry it until ``num_tries`` tries have been performed. For ``POST``
    requests, the sent data is to be supplied by the ``post_data`` parameter.

    .. todo:: Document the purpose of the ``branch`` parameter.

    :param branch: ???
    :param relative_url: The relative URL to be submitted.
    :param request_type: The type of request being submitted.
    :param post_data: The data to be submitted with the request, if necessary.
    :param num_tries: The number of times the request should be tried before
                      giving up.
    :returns: The parsed JSON response, or `None` if the request failed after
              all tried attempts.

    """
    # COMMENT: Documentation is often overlooked but vital, both for you as
    # well as your colleagues. In my opinion, good documentation for a function
    # contains three things:
    #   1. A brief description of what the function does.
    #   2. An overview of the parameters I should/can give it, as well as their
    #      purpose.
    #   3. A description of what I can expect to receive from the function as
    #      a return value.
    # See PEP257 for docstring conventions.
    # I've rewritten the documentation into a more machine-readable format,
    # reST. It can be parsed and used to generate HTML documentation by tools
    # such as sphinx-doc. Very useful when writing an API.
    # Documentation often also includes type information on the parameters and
    # the return type. This is vital. However, I've emitted this from the
    # docstring since such information is already available as type hints.
    # Sphinx has plugins to extract type information from type hints.
    # COMMENT: This should really be a debug statement rather than info. Also,
    # I'm assuming the logger is imported/constructed somewhere outside of the
    # snippet provided.
    logger.debug(f'getting data from {relative_url}')

    # COMMENT: What is `envs`? If it's just accessing environment variables,
    # consider using `os.environ` instead, especially if its a third-party
    # package.
    # COMMENT: The `url` variable can get a name improvement, IMO.
    url = envs.get(branch, '') + relative_url
    # COMMENT: These variables are now useless. They could've also used a
    # better name.
    # resp = {}
    # status = False

    # COMMENT: Although this loop works, it would ALWAYS retry, regardless of
    # there being any exceptions. If the request was fine, it would do it again
    # if `num_tries` is high enough. I've renamed the parameter to `num_tries`
    # instead of `num_retries` so that a `num_tries` value of 2 will try twice.
    # For a parameter named `num_retries` given value 2, I would expect the
    # request to be performed at most 3 times: Once initially, and two REtries.
    # COMMENT: We don't use variable `x` anywhere in the loop. Use an
    # underscore instead so that it is not tied to a variable.
    for _ in range(num_tries):
        try:
            # COMMENT: Because we use an enum, we can now compare literally,
            # which is more efficient than string comparisons and decreases
            # the change of misspellings.
            # COMMENT: Since these handlers are short, I'll allow it, but if
            # you get more options and longer code, consider using classes
            # and polymorphism. E.g.:
            # req_maker = some_way_of_obtaining_an_object(req_method)
            # req_maker.perform(url)
            if request_method is RequestMethod.GET:
                # COMMENT: You changed these to prints in the edit, I changed
                # them back to logger calls. As a rule of thumb: Use a logger,
                # never print. Exceptions should be rare and only for small
                # personal scripts. I also changed them to debug logs, since
                # they're not informative to the user.
                logger.debug(f'GET call to {url}')
                # COMMENT: `resp` can get a better name, more descriptive of
                # its purpose. I'm assuming here you're contacting a REST API.
                api_resp = requests.get(url)
            elif request_method is RequestMethod.POST:
                logger.debug(f'POST call to {url}')
                if branch in envs.keys():
                    # COMMENT: In cases like these, indent your arguments with
                    # two levels, so that you don't confuse it for a new block
                    # in the body. Also, there's plenty of controversy over
                    # where to put the closing parenthesis in these cases,
                    # and whether or not to allow a comma after the final item.
                    # I'm personally not a fan, but that's just me.
                    api_resp = requests.post(
                            url,
                            json=post_data,
                    )
                else:
                    # COMMENT: Some style guides disallow the usage of string
                    # interpolation, I don't personally mind it.
                    logger.warn(
                            f'{branch} : Attempted to push data: {post_data}')
                    # COMMENT: You should really do *something* other than just
                    # logging here. In your original code, here, `resp` would
                    # not get defined, and thus the next line (`resp.ok`) would
                    # fail with an `AttributeError`, which would get caught as
                    # an "Unknown exception", and potentially retry the loop
                    # because of this bug.
                    # It seems like this is an unrecoverable problem with the
                    # input, so it's better to just return and stop the rest
                    # of the evaluation of the function. Even better: Raise an
                    # exception.
                    return None

            # COMMENT: I'm going to completely rewrite this part.
            # status = api_resp.ok
            # if api_resp.ok:
            #     resp = api_resp.json()
            #     print(f'{resp}')
            # else:
            #     resp.raise_for_status()

            # `raise_for_status` raises an exception if status != 2xx.
            # In your original code, you first check the status, and if the
            # status != 2xx, you call `raise_for_status`, which itself checks
            # if status != 2xx and raises. Why?
            api_resp.raise_for_status()
            # This may throw an exception. As you mention, the API "does not
            # ALWAYS return JSON", so you should expect exceptions. You should
            # expect parsing errors anyway if relying on external data.
            json_resp = api_resp.json()
            logger.debug(json_resp)
            # Return the data early instead of assigning to a variable
            # returning it at the end of the function. This breaks free from
            # the loop, thus immediately fixing the issue with too many tries
            # in the loop.
            return json_resp
        # Let's get to the exception handling...
        # COMMENT: It should come as no surprise now, I don't like `err`.
        # Either use something like `http_err` or just simply `e`, the standard
        # convention.
        except HTTPError as err:
            logger.exception(f'HTTP Error: {err}')
        except Timeout as err:
            logger.exception(f'Connection timed out {err}')
        except ConnectionError:
            # COMMENT: Don't use the `f` prefix if you're not interpolating.
            # COMMENT: Split the string for line length. Remember that this
            # works without requiring a `+`.
            logger.exception(
                    'A network problem has occured '
                    '(DNS failure, refused connection)')
        except RequestException as err:
            logger.exception(f'Other error occurred: {err}')
        # COMMENT: Don't catch Exception. Many style guides will discourage you
        # from doing this. `Exception` covers most of the possible exceptions
        # in Python programs, including `AttributeError`, which caused the bug
        # in the `else` branch of the POST request handler.
        # except Exception as err:
        #     logger.exception(f'Unknown Exception: {err}')

        # COMMENT: Explicitly catch JSONDecodeError so you can handle JSON
        # parsing errors explicitly.
        except JSONDecodeError as e:
            logger.exception(f'Failed to parse JSON: {e}')

    # COMMENT: When you have nothing meaningful to return from a function,
    # either don't return anything, or explicitly return `None`. Returning the
    # empty list is confusing: What if the response JSON was actually an empty
    # list? We'd have no way of discriminating a failure from an empty
    # response!
    # Better yet, we should raise an exception if all tries failed.
    return None

Wrapping Up

The improvements I've proposed definitely leave a lot of room for further improvement. Especially if you're planning on extending the functionality shown (which, likely, you will or even have to, given the nature of the code), I highly recommend to start decomposing now. For example, extract handling code for each of the HTTP methods into its own individual function, and perform some efficient dispatching by either putting the functions in a dict with keys corresponding to the HTTP methods, or implementing it using OO and polymorphism. The former is likely the better approach for this code, opting for the latter is a good idea if you plan on adding lots of functionality to these requests.

Bonus: Linter

If you want my recommendation for a Python linter, I run flake8 on my personal code with the following plugins:

flake8 --version
3.7.9 (aaa: 0.6.2, cohesion: 0.9.1, flake-mutable: 1.2.0, flake8-annotations-complexity: 0.0.2, flake8-annotations-coverage: 0.0.3, flake8-bandit: 2.1.2, flake8-blind-except: 0.1.1, flake8-broken-line: 0.1.1, flake8-bugbear: 19.8.0, flake8-comprehensions: <cached_property.cached_property object at 0x10e93d350>, flake8-docstrings: 1.5.0, pydocstyle: 4.0.1, flake8-eradicate: 0.2.3, flake8-pie: 0.2.2, flake8-print: 3.1.4, flake8-pyi: 19.3.0, flake8-string-format: 0.2.3, flake8-tidy-imports: 2.0.0, flake8-todo: 0.7, flake8-tuple: 0.4.0, flake8-variables-names: 0.0.1, flake8_builtins: 1.4.1, flake8_pep3101: 1.2.1, flake8_quotes: 2.1.0, import-order: 0.18.1, logging-format: 0.6.0, mccabe: 0.6.1, naming: 0.8.2, pycodestyle: 2.5.0, pyflakes: 2.1.1, rst-docstrings: 0.0.10, warn-symbols: 1.1.1) CPython 3.7.5 on Darwin

But there's a bunch of warnings that I tend to disable here as I see fit. Another option is wemake-python-styleguide, which is a very strict plugin for flake8 (too strict for me, even). mypy is also great as a static type checker to find type bugs early.


A couple of changes I would suggest.

To Struct or not to Struct:

Structs are useful for value equality situations. This is objects which require constant value equality checks or intend to be used as keys in Dictionaries. However what I see in use is more of an immutable class. While structs are considered to be best practice as immutable objects you can do the same with classes, but you get to sidestep the inevitable equality issue.

You see, if you were to use equality on your current Matrix object you will find it is slow to check. In fact structs can even end up using reflection to check equality in the worst case, which is seriously inefficient. see C# - Value Type Equals method - why does the compiler use reflection?

Because of this you should always overload equality when using structs, if only for speed reasons. See What needs to be overriden in a struct to ensure equality operates properly?  or one of the many other articles online about this.

Your use case doesn't seem to use or need equality, therefore I would suggest a class over a struct. As a general rule if you don't see yourself using the object as a dictionary key or for equality I wouldn't use a struct.

Var:

On a less important note I am always a strong advocate of using var in your code to make refactoring easier. In the following lines you are declaring the type twice:

int rowLength = matrices[0].RowLength;
int columnLength = matrices[0].ColumnLength;
double[,] matrix = matrices[0].AsArray();
for (int row = 0; row < rowLength; row++){...}

There are actually quite a few more places on top of this. This seems trivial but the usage of var over say double[,] or int (for the case of row) means that if you have to refactor the class into a float[,] or to return a long for a size, that your current code would still function with no effort on your part. Var tends to save on time typing long types and is indispensable for refactoring in looping. It can be a bit debatable, as each team has there own standards, but I can tell you on my team we have an "all var all the time" rule which has been a godsend for refactoring.

{'s:

You swap between style of whether you use a trailing set of {'s between lines. For your for loop you use them, but your if statement does not. While I would advocate always using them, even if you only have a single line in the statement, I would say it's more important to be consistent. If you are going to use the style without {'s for single line statements, do so everywhere. If not, which I generally suggest, do not. This is more of a taste issue, and certainly not a law of the land, but worth noting.

Otherwise this looks good. Hope this helps.


Music management app, mashing data from various APIs

Please add the following method do your code and print the runtime of every section of your code. As indicated by my comment I guess the foreach->simplexml_load_file("...") might take a while.

//PHP <5.0.0
function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

$start=microtime_float();
//...
echo microtime_float()-$start;

//PHP>=5.0.0
$start=microtime(true);
//...
echo microtime(true)-$start;


First of all, your benchmark is not really correct because it doesn't take into account any VM warmup and has only a single iteration.

Using JMH 1.11.3, I rewrote your benchmark: two integer arrays of length 10.000, 100.000, 1.000.000 and 10.000.000 are created with random values and then sorted with your implementation and Arrays.sort. The results are (Windows 10, JDK 1.8.0_66 64 bits, i5-3230M CPU @ 2.60GHz):

Benchmark            (length)  Mode  Cnt     Score    Error  Units
SortTest.arraysSort     10000  avgt   30     0,557 ±  0,015  ms/op
SortTest.arraysSort    100000  avgt   30     7,369 ±  0,267  ms/op
SortTest.arraysSort   1000000  avgt   30    86,435 ±  3,273  ms/op
SortTest.arraysSort  10000000  avgt   30  1039,120 ± 49,706  ms/op
SortTest.customSort     10000  avgt   30     0,905 ±  0,029  ms/op
SortTest.customSort    100000  avgt   30    11,152 ±  0,391  ms/op
SortTest.customSort   1000000  avgt   30   132,986 ±  5,581  ms/op
SortTest.customSort  10000000  avgt   30  1530,132 ± 42,771  ms/op

This shows that while Arrays.sort is indeed a little faster, your implementation has a very good performance, for small and large arrays.

I find your code is really good and easy to read. Only a few remarks if you intent to keep this code around:

The method sort(int[] array, int fromIndex, int toIndex) does not do any sanity checks on fromIndex and toIndex. This is well understandable because it introduces another level of complexity. You should then consider making that method private instead of public: this way, you ensure that no out of bounds exception can occur through the public API.
Consider perhaps renaming the utility class IntQuicksort to make it clear that is operates on primitive int array and not Integer objects. Also, since this is a utility class, consider making it final and adding a private constructor.
Regarding the code itself, I would add a swap method to refactor the code a little

private static void swap(int[] array, int firstIndex, int secondIndex) {
    int tmp = array[firstIndex];
    array[firstIndex] = current;
    array[secondIndex] = tmp;
}

and use it like

if (current > pivot) {
    ++rightPartitionLength;
    swap(array, toIndex - rightPartitionLength, index);
} else if (current < pivot) {
    swap(array, fromIndex + leftPartitionLength, index);
    ++index;
    ++leftPartitionLength;
}

Code of benchmark for completeness:

import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;

@Warmup(iterations = 10, time = 700, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 10, time = 700, timeUnit = TimeUnit.MILLISECONDS)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Fork(3)
public class SortTest {

    @State(Scope.Benchmark)
    public static class ArrayContainer {

        @Param({ "10000", "100000", "1000000", "10000000" })
        private int length;

        private int[] array;
        private int[] arrayToSort;

        @Setup(Level.Iteration)
        public void setUp() {
            ThreadLocalRandom random = ThreadLocalRandom.current();
            array = random.ints(length).toArray();
        }

        @Setup(Level.Invocation)
        public void cloneArray() {
            arrayToSort = array.clone();
        }

    }

    public static void sort(int[] array) {
        sort(array, 0, array.length);
    }

    public static void sort(int[] array, int fromIndex, int toIndex) {
        if (toIndex - fromIndex < 2) {
            return;
        }

        int pivot = array[fromIndex];
        int leftPartitionLength = 0;
        int rightPartitionLength = 0;
        int index = fromIndex;

        while (index < toIndex - rightPartitionLength) {
            int current = array[index];

            if (current > pivot) {
                ++rightPartitionLength;
                int tmp = array[toIndex - rightPartitionLength];
                array[toIndex - rightPartitionLength] = current;
                array[index] = tmp;
            } else if (current < pivot) {
                int tmp = array[fromIndex + leftPartitionLength];
                array[fromIndex + leftPartitionLength] = current;
                array[index] = tmp;

                ++index;
                ++leftPartitionLength;
            } else {
                ++index;
            }
        }

        sort(array, fromIndex, fromIndex + leftPartitionLength);
        sort(array, toIndex - rightPartitionLength, toIndex);
    }

    @Benchmark
    public int[] customSort(ArrayContainer container) {
        sort(container.arrayToSort);
        return container.arrayToSort;
    }

    @Benchmark
    public int[] arraysSort(ArrayContainer container) {
        Arrays.sort(container.arrayToSort);
        return container.arrayToSort;
    }

}


Efficient implementation of comparison operators for cards in a poker simulation

There are a couple choices, but the best is to record the value's index on Card creation:
self.order = value._member_names_.index(value.name)

Then your comparison can use self.order directly:
return self.order < other.order

_member_names_ is a supported attribute and won't be going away.


Some issues with your code

The biggest is that you are creating a
new ArrayList with each interruption of your server.  You probably
want to allocate that array outside the loop that is creating the clients and then add each future to that look as they are created.

I'd avoid the "sync" in the for loop waiting for things to
get done.  If you need to wait for them to complete, attache a
promise listener to each of the futures with a little lambda
function to do whatever it is you need done when the clients are
finished.

I'd pass shutdown gracefully a time limit rather than just
waiting forever.

Without more of your code, its hard to say what else you have
overlooked.


To calculate the total CPU usage as a percentage

There are a few problems you have here. The first, is the concept of getting the usage at a point in time, which is not possible. But, you can get it for a span of time. You are using top -bn 1 which will get the usage for the span of a second.

Since you are accessing the /proc system to get the number of CPU's, you may as well use the right /proc file for what you want:

cat /proc/stat:

 ~ $ cat /proc/stat
cpu  177206 161827 1274669 3582291272 144435 154779 0 0 0 0
cpu0 32170 48533 914773 894903107 30650 69784 0 0 0 0
cpu1 52790 41088 180295 895685563 76035 14410 0 0 0 0
cpu2 18745 40955 49422 895959636 11295 2234 0 0 0 0
cpu3 73500 31249 130178 895742965 26454 68350 0 0 0 0
intr 339571688 48 10 0 0 0 0 2 0 1 0 0 0 152 0 0 8750527 0 322394 40428015 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
......
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
ctxt 660707018
btime 1401123121
processes 196075
procs_running 1
procs_blocked 0
softirq 322202763 0 136092603 1792784 40737199 4701209 0 6 133008518 51951 5818493

With the above file, I would calculate it manually.... (also using the documentation here: http://www.mjmwired.net/kernel/Documentation/filesystems/proc.txt#1212 )

I have taken the liberty of programming it myself.... since the recommendation is sucha  deviation from your solution, it makes sense:

#!/bin/bash

#CORECOUNT=$(grep cpu /proc/stat | grep -v 'cpu ' | wc -l)
#echo $CORECOUNT cores not needed for calculation though

DELAY=${1:-1}

function getstat() {
    grep 'cpu ' /proc/stat | sed -e 's/  */x/g' -e 's/^cpux//'
}

function extract() {
    echo $1 | cut -d 'x' -f $2
}

function change() {
    local e=$(extract $ENDSTAT $1)
    local b=$(extract $STARTSTAT $1)
    local diff=$(( $e - $b ))
    echo $diff
}

#Record the start statistics

STARTSTAT=$(getstat)

sleep $DELAY

#Record the end statistics

ENDSTAT=$(getstat)

#http://www.mjmwired.net/kernel/Documentation/filesystems/proc.txt#1236
#echo "From $STARTSTAT"
#echo "TO   $ENDSTAT"
#     usr    nice   sys     idle       iowait irq    guest
#From 177834 168085 1276260 3584351494 144468 154895 0 0 0 0
#TO   177834 168085 1276261 3584351895 144468 154895 0 0 0 0

USR=$(change 1)
SYS=$(change 3)
IDLE=$(change 4)
IOW=$(change 5)

#echo USR $USR SYS $SYS IDLE $IDLE IOW $IOW

ACTIVE=$(( $USR + $SYS + $IOW ))
TOTAL=$(($ACTIVE + $IDLE))
PCT=$(( $ACTIVE * 100 / $TOTAL ))

echo "BUSY $ACTIVE TOTAL $TOTAL $PCT %"


C++ Read istream into string with exceptions

Streams are awful. Don't use them. (Joking, but I wish I had a viable alternative to recommend for basic file input. C++ is pathetic in this area.)

[code:] tellg() returns a signed type, with -1 as an error value. You might like to check that, and then static_cast it before using it in reserve().
[code:] Using std::string::resize() and std::istream::read() to copy from the stream might be faster than using std::string::append() with std::istreambuf_iterators.
[design(bug?):] Seeking to the end of the file like that may not work. On Windows, for example, if a file is opened in text mode, the ctrl-z (alt026) character is treated as the end of the file (even though it isn't). As I understand it, you have to use ignore() to find the real end of the file instead.
[design:] I doubt it's worth it to create a function to append a string directly. Loading into a string, then appending is probably fast enough. (What if you want to prepend or insert... suddenly you need more functions that basically do the same thing).
Write unit tests! Something like this needs a whole bunch of tests that save a string to a file, then load a string and compare the results (binary mode, text mode, special characters, etc.).

The whole article in the link above is useful, but the summary section at the end describes 3 reasonable alternatives for reading from a file stream:

Put the istream's rdbuf into a stringstream, then use the .str() function to get a string. This involves extra copying, but is simplest, and should be quick enough.
Use .ignore() to find the end of the file, then read the whole thing at once. No extra copies in memory (good for large files), but involves reading the file twice.
Read chunks into a std::deque and then copy. Works where it's not possible to seek in the stream.


Linux HDD/CPU Temperature Logging Bash Script to run every minute in crontab

Here is my revision. I changed it that instead of hardcoding the user's home directory the script can just get that from env. Also, I would run this directly as a root account chron task rather than configuring sudo to be able to run shutdown and hddtemp. Finally, instead of using if -z to check for a file's existance, I would use test -f or something. Anyway, not bad at all for a 'noob', I'd give yourself more credit! Here is my version:

#!/bin/bash
# Check HDD Temps, CPU temp.. shut down server if any exceed acceptable limit
# Using hddtemp to check HDD temps, sensors command to check CPU temp.
date=$(TZ='America/Los_Angeles' date)
# Consider running as root directly instead of requiring sudo (unless you want \
# to configure a nonroot user to be able to use `hddtemp` and `shutdown`) \
# which would work, but since you're running as chron, I would just run \
# it as a root cron job
test $(id -u) == 0 || {echo 'This script must be run as root'; exit 1}
HDD1=$(hddtemp /dev/sdb | cut -d":" -f1,2)
HDD2=$(hddtemp /dev/sdc | cut -d":" -f1,2)
T1=$(sudo hddtemp /dev/sdb | cut -d":" -f3 | cut -d" " -f2 | cut -c1-2)
T2=$(sudo hddtemp /dev/sdc | cut -d":" -f3 | cut -d" " -f2 | cut -c1-2)
CPU1=$(sensors | grep "Core" | head -1 | cut -d"+" -f2 | cut -d"." -f1)
CPU2=$(sensors | grep "Core" | tail -1 | cut -d"+" -f2 | cut -d"." -f1)
logdir="/home/$USER/templogs"
base_file="${logdir}/temp1.log"
file="${logdir}/temp"
log='.log'
error='.error'
test -d $logdir||mkdir $logdir 2>/dev/null

find_lowest_file_num() {
        local lowest_file_num=$(ls ${logdir}/ | grep temp | cut -d"p" -f2 | cut -d"." -f1 | sort -rn | tail -1)

        if [ -z "$lowest_file_num" ]
        then
                touch $base_file
                echo 1
        else
                echo $lowest_file_num
        fi
}

find_highest_file_num() {
        local highest_file_num=$(ls ${logdir}/ | grep temp | cut -d"p" -f2 | cut -d"." -f1 | sort -rn | head -1)

        # How about using `test` instead of ` if -z`?

        test -f "$highest_file_num" || { >"$highest_file_num" ; echo 'Created temp file' ;} && echo "highest_file_num is present"

}

highest_file_num=$(find_highest_file_num)
lowest_file_num=$(find_lowest_file_num)

get_curr_highest_file() {
        local h=${file}${highest_file_num}${log}
        echo $h
}

get_curr_lowest_file() {
        local l=${file}${lowest_file_num}${log}
        echo $l
}

curr_file=get_curr_highest_file

echo "HDD1: ${HDD1}  Temp:${T1}C     ${date} " >> $curr_file
echo "HDD2: ${HDD2}  Temp:${T2}C     ${date} " >> $curr_file
echo "CPU Core 1 Temp:${CPU1}C     ${date} " >> $curr_file
echo "CPU Core 2 Temp:${CPU2}C     ${date} " >> $curr_file

#if files get bigger than 1000k, make a new one
if [ $(du -k $curr_file | cut -f1) -gt 1000 ]
then
        let "highest_file_num++"
        touch $(get_curr_highest_file)
fi

if [ $(du -k $logdir | cut -f1) -gt 100000 ]
then
        rm -f $(get_curr_lowest_file)
fi

if [ $T1 -gt 50 ] || [ $T2 -gt 50 ] || [ $CPU1 -gt 80 ] || [ $CPU2 -gt 80 ]
then
        echo "HIGH TEMPS DETECTED!!! HDD1 Temp: ${T1}C    HDD2 Temp: ${T2}C     ${date}" >> ${curr_file}${error}
        echo "CPU1: ${CPU1}C, CPU2: ${CPU2}           ${date}" >> ${curr_file}${error}
        echo "Shutting down..." >> ${curr_file}${error}
        shutdown now # I would run this as root directly
else
    echo "Temps ok: HDD1: ${T1}, HDD2: ${T2}, CPU1: ${CPU1}, CPU2: ${CPU2}"
fi


Does this generic query follow good OOP standards?

Your binding of parameters will help in preventing SQL injections.

You need to sanitize your data first though.
You need to treat everything that comes from a user (passed from the client machine) as 'dirty' and not allow it into your system before it's been 'cleaned'. Your first step would be to clean it - converting all HTML tags and special characters into their HTML entities htmlspecialchars() htmlentities() (well as long as HTML isn't allowed). This will help prevent cross-sight scripting (XSS). Typically then you would move on to validating the data - making sure it's in a format you expect. Then if it's not you return it to the user with an error.
This is also assuming that you've checked the user has permission to run this function, if relevant.


Looking for a better way to define and use constants

You should create an ScmCommands interface like this:

public interface ScmCommands {
    public String[] getRevisionCommand();

    public List<String[]> getDiffCommand();

    public List<String[]> getCodebaseInfoCommand();
}

and two implementations: SvnCommands, GitCommands.

It would improve type safety a lot. (With a Map<String, Object> you usually have to cast the values which is error-prone). Furthermore, it eliminates the magic constants. It's easy to call Map.get() with a mistyped key. With the interface the compiler warns you if the method name is wrong.

Edit: I've changed the return types. Sample implementations are the following:

public class GitCommands implements ScmCommands {

    private static final String GIT_COMMAND = "git";

    public GitCommands() {
    }

    @Override
    public String[] getRevisionCommand() {
        return new String[] { GIT_COMMAND, "rev-parse", "HEAD" };
    }

    @Override
    public List<String[]> getDiffCommand() {
        final List<String[]> result = new ArrayList<String[]>();
        result.add(new String[] { GIT_COMMAND, "diff", "HEAD" });
        result.add(new String[] { GIT_COMMAND, "diff", "HEAD", "--no-prefix" });
        return result;
    }

    @Override
    public List<String[]> getCodebaseInfoCommand() {
        final List<String[]> result = new ArrayList<String[]>();
        result.add(new String[] { GIT_COMMAND, "branch", "-v" });
        result.add(new String[] { GIT_COMMAND, "remote", "-v" });
        result.add(new String[] { GIT_COMMAND, "log", "--max-count=1" });
        result.add(new String[] { GIT_COMMAND, "status" });
        return result;
    }
}

public class SvnCommands implements ScmCommands {

    private static final String SVN_COMMAND = "svn";

    public SvnCommands() {
    }

    @Override
    public String[] getRevisionCommand() {
        return new String[] { SVN_COMMAND, "info" };
    }

    @Override
    public List<String[]> getDiffCommand() {
        final List<String[]> result = new ArrayList<String[]>();
        result.add(new String[] {SVN_COMMAND, "diff"});
        return result;
    }

    @Override
    public List<String[]> getCodebaseInfoCommand() {
        final List<String[]> result = new ArrayList<String[]>();
        result.add(new String[] { SVN_COMMAND, "status" });
        return result;
    }

}

It fits well to ProcessBuilder but I'd consider extracting out all SCM related methods to an interface (for example Scm), and move the code to SCM-specific classes which implement the Scm interface, like GitScm, SubversionScm etc. Calling command line executables doesn't smell good, maybe it would be better to use native Subversion and Git Java libraries.


As mentioned by @Cyrille fOf is not a good method name.

I disagree with the use of more comments, if you name your function well enough, you shouldn't need comments.  Comments should be used to explain hard to understand or confusing code, not describe what is going on.

In java the opening { is usually placed at the end of the line where the code block starts.  i.e.

if (somethingIsTrue) {

You can get rid of the else in your fOf function.  It is implied with the return in the if.

You don't need to specify the default constructor.  It does nothing, so it is just clutter.

I'm also not happy with having the System.out.println in your class.  Off of the top of my head, I would create an reporting structure, which would include an interface and at least one class.  Something like

interface Reporter {

    void reportLine(string message);
}

Then you could implement it like

public class ConsoleReporter implements Reporter {

    void reportLine(string message) {
        System.out.println(message);
    }

}

and your implementation.  Notice the constructor now does something, so my point about removing it is not valid in this case.

class RecursiveMethods {

   private Reporter reporter;

   RecursiveMethods(Reporter reporter)          //default constructor
   {
       this.reporter = reporter;
   }

   public int fOf(int x)
   {
       if (x <= 10)                        //the base case
       {
           reporter.reportLine(x + " <= 10, therefore ... f(" + x + ") = -5");
           return -5;
       }

       reporter.reportLine(x + " > 10, therefore ... f(" + x + ") = f(" + x + " - 3) + 2 = f(" + (x -3) + ") + 2");

        return fOf(x-3) + 2;
   }
}

public static void main(String[] args)
{
    Reporter reporter = new ConsoleReporter();
    int x;
    RecursiveMethods rMethods = new RecursiveMethods(reporter);

    // Change all System.out.writeLn to reporter.reportLine
}

Doing this will allow you to output to different mediums, for instance, you could create FileReporter, which would output to a file, or StreamingReporter, which would output to a stream of some sort.  It just makes your code more versatile.  You could also add a method like reportString, which would write an entire formatted string.


I'm going to assume this question is in the context of quality interview code, not quality production code. Websites like GeeksForGeeks (https://practice.geeksforgeeks.org/problems/jumping-caterpillars/0)
don't grade you based on production code quality.

Your failure to correctly spell the most important word in the problem domain (Caterpillar) would put me off to a sour start. To me, that suggests an inattention to detail. In software development, little details can make a big difference.

You're doing a lot more work than you need to. The basic algorithm here should be - for each leaf, if it can be evenly divided by any of the caterpillar numbers, it gets eaten and you should move on. If none of the caterpillars eat it, increment the uneaten count and continue.

In idiomatic Java,
whitespace is placed between a control flow keyword (if, else) and the open paren
there is no whitespace before a semicolon
binary operators, including -, == and -, should have whitespace on both sides.
opening curly braces belong on the same line, not a newline

You should use try-with-resources blocks to handle closeable resources such as Scanner.

testcase is not a good variable name because it doesn't correctly explain what it's pointing to. numberOfTestCases would be better. scanner is also better than sc, because I don't have to assume what it holds.

You can also look for more opportunities to break out methods. A method with as much nested code as you have is hard to read and understand. Maximize readability until you have a known performance bottleneck.

If you were to rewrite your code using all these suggestions, it might look more like the untested code below:

import java.util.Arrays;
import java.util.Scanner;

public class Caterpillar {

    public static void main(String[] args) {
        try (Scanner sc = new Scanner(System.in)) {
            int numberOfTestCases = sc.nextInt();

            for (int testCase = 0; testCase < numberOfTestCases; testCase++) {
                int numberOfLeaves = sc.nextInt();
                int[] caterpillars = readCaterpillarsFrom(sc);
                int uneatenLeaves = 0;
                for (int leaf = 1; leaf <= numberOfLeaves; leaf++) {
                    if (isLeafUneaten(leaf, caterpillars)) {
                        uneatenLeaves++;
                    }
                }
                System.out.println(uneatenLeaves);
            }
        }
    }

    private static int[] readCaterpillarsFrom(Scanner scanner) {
        int[] caterpillars = new int[scanner.nextInt()];
        for (int j = 0; j < caterpillars.length; j++) {
            caterpillars[j] = scanner.nextInt();
        }

        /* You're more likely to get a hit on smaller numbers, so the sort helps you leave earlier in some cases.
         * This is arguably a premature optimization, and may be a performance loss if the there are many
         * caterpillars and few leaves.
         */
        Arrays.sort(caterpillars);

        return caterpillars;
    }

    private static boolean isLeafUneaten(int leaf, int[] caterpillars) {
        for (int caterpillar : caterpillars) {
            if (leaf % caterpillar == 0) {
                return false;
            }
        }
        return true;
    }

}


Given two sorted arrays, add the elements of the second array into the first

Both are equivalently readable, I'll nitpick on some details though :)

Both solutions will fail with null elements.

The generic type would be better named T instead of Type, as Type has another definition already.

numElementsInArray() as a function looks a little odd because it is undefined, instead consider passing in the information you need as part of the method definition.

When modifying in place you do not want to return the array because presumably you are trying to skimp on memory allocations and are just going to look for the result in the first array that was passed in.


Your implementation is elegant, clean, easy to read.

The other is less so, but there is a significant difference between the two: your version returns a new array of unique values, the other removes duplicate values, modifying the input array.

Both algorithms are \$O(n^2)\$. Your implementation includes one redundant comparison per element: when the indexOf call reaches the current element, it compares it to itself, which is a redundant comparison for your ultimate intent of finding unique values. The other implementation optimized this with the var j = i + 1; step: it compares the current element to all subsequent element, never to itself.

In the end, the performance difference will come down to the implementation of splice and new array creation of the given JavaScript engine. I don't think such comparison will be very useful, except in very rare extreme cases. Also keep in mind that premature optimization is the root of all evil. And once again, there's also the matter of the different behavior of the implementations (return new unique array or mutate the parameter in-place), which makes comparisons problematic.

For what it's worth, in cases when an \$O(n^2)\$ solution to this problem is good enough (as opposed to an \$O(n)\$ solution using \$O(n)\$ extra space), I would go for your version, because it's intuitively easier to read.


The first thing I observe is that the dropWhile function argument is:

\x -> (not . indentChar) x || '(' == x

The comparison to '(' cancels out that same comparison in indentChar -- so the following definition of toCoordinate is identical in meaning:

toCoordinate = dropWhile (not . isAlpha) >>> takeWhile (/= ' ')

You did state that you need to use indentChar elsewhere -- but not using it here makes your code clearer.

Additionally, rather than use arrows, the above definition seems clearer to me when using function composition -- I would write it as:

toCoordinate = takeWhile (/= ' ') . dropWhile (not . isAlpha)


Project Euler #82 - path sum: three ways

To solve the Project Euler challenge, you'll have to handle a large matrix from a file.  Therefore, your function should accept the matrix as a parameter.

You used size to represent both the number of rows and the number of columns.  I would use two variables to avoid hard-coding the assumption that the input is a square matrix.

Your dynamic programming algorithm is sound.  I would use the min() function to avoid finding the minimum by iteration.  Also, setting best all at once instead of mutating the elements of column avoids having to copy column into a temporary variable.

def euler82(matrix):
    nrows, ncols = len(matrix), len(matrix[0])
    best = [matrix[row][0] for row in range(nrows)]

    for col in range(1, ncols):
        column = [matrix[row][col] for row in range(nrows)]

        best = [
            # The cost of each cell, plus...
            column[row] +

            # the cost of the cheapest approach to it
            min([
                best[prev_row] + sum(column[prev_row:row:(1 if prev_row <= row else -1)])
                for prev_row in range(nrows)
            ])
            for row in range(nrows)
        ]

        #print(best)

    return min(best)


The running time is not \$ O(n^2) \$. It is \$ O(n \log n) \$. Why?
$$ T(n) = O \bigg( { n - 2 · 2 \over 2 } + { n - 2 · 3 \over 3 } + \dotsb + { n - 2 · { n \over 2 } \over { n \over 2 }} \bigg) = O(n \log n). $$ This is very similar to the sum of a harmonic series. So it is pretty good in terms of time complexity.

It is possible to optimize the code a little bit:

divisors_count = [2] * limit
divisors_count[0], divisors_count[1] = 0, 1
min_divisor = 2
max_divisor = len(divisors_count) // 2
for divisor in range(min_divisor, max_divisor + 1):
    for multiple in range(divisor * 2, len(divisors_count), divisor):
        divisors_count[multiple] += 1
return divisors_count

I changed the loop over the enumerated list to a loop over a range of divisors and removed the if statement inside the loop's body. In my opinion, it also makes the logic more clear because we do not need a list itself in the outer loop. It is also sufficient to iterate only up to len(sieve) // 2, because otherwise range(number * 2, len(sieve), number) is empty.

I also gave the variables more meaningful names: divisor instead of number and so on to make the code easier to understand (but the initial version is rather clear, too, in my opinion).

But either way, this code shows a good scalability: it runs for about 1.8–1.9 seconds with my optimizations, and 2.1–2.2 seconds without them, for limit = 10 ** 6.


Help me condense a series of lengthy javascript conditional arrays

Assuming the variables you're using aren't needed later, you can condense it down to this:

var messages = [
    'Find a location…',
    'Try searching by zip code, like 90012…',
    'Know your location ID? Find it like so: #xxxx',
    'Search locations by type, like apartment, office, or retail...',
    'Search locations by area, like downtown, Pasadena, or Hollywood...',
    'Search locations by style, like art deco, tudor, or industrial...',
    'Search locations by feature, like fireplace, pond, or tiled floors...',
    'Modify your search…',
    'Modify your search by zip code, like 90012…'
], messageSets = [
    [3, 4, 5, 6, 7, 8],
    [0, 1, 2, 3, 4, 5, 6],
    [0]
];

var s = messageSets[$('.filters').length ? +/^\/locations\/?$/.test(location.pathname) : 3];
$('#s').val(messages[s[Math.random() * s.length | 0]]);
inputReplace();

Ideally the first var statement would be at a higher level, so it would only be run once, not every time the function is executed.

You could shorten it even further by using ranges instead of sets, but that could get complicated if you want to add more messages later. On the flip side, if you are planning to add a lot more messages, it would probably be clearer to make messages and messageSets objects (= dictionaries), so that you can name each message and set.

edit: here's how you would do the same thing using objects instead of arrays. The only difference is that each message, and set, has a name instead of a number, which makes references to it clearer to read.

var messages = {
    default: 'Find a location…',
    zip: 'Try searching by zip code, like 90012…',
    id: 'Know your location ID? Find it like so: #xxxx',
    type: 'Search locations by type, like apartment, office, or retail...',
    area: 'Search locations by area, like downtown, Pasadena, or Hollywood...',
    style: 'Search locations by style, like art deco, tudor, or industrial...',
    feature: 'Search locations by feature, like fireplace, pond, or tiled floors...',
    modify: 'Modify your search…',
    modify_zip: 'Modify your search by zip code, like 90012…'
}, messageSets = {
    locations: 'default zip id type area style feature'.split(' '),
    filters: 'type area style feature modify modify_zip'.split(' '),
    default: ['default']
};

var s = messageSets[$('.filters').length ?
    /^\/locations\/?$/.test(location.pathname) ? 'locations' : 'filters' :
    'default'
];
$('#s').val(messages[s[Math.random() * s.length | 0]]);
inputReplace();

Note that this has the additional advantage of making the order of the objects not matter: you could add alert: 'Enter something!', directly under the first line and it wouldn't break anything.


Here are some things that may help you improve your code:

Simplify the algorithm

Although it would take more space to store, a simpler algorithm would be to simply use minLoc as the current minimum.  If you did so, then getMin() would simply be return minLoc.back();

Eliminate redundant variables

Even if you don't care for that particular algorithm, you can remove the variables min, current and minCurrent and also simplify the code:

void push(int num)
{
    stack.push_back(num);
    if (minLoc.size() == 0 || num < stack[minLoc.back()])
        minLoc.push_back(stack.size()-1);
    print();
}

void pop()
{
    // Check if the number to be popped is the current lowest
    if(minLoc.size() && minLoc.back() == stack.size()-1)
        minLoc.pop_back();
    stack.pop_back();
    print();
}

int getMin() const {
    return minLoc.size() ? stack[minLoc.back()] : 0;
}

Use const where possible

The getMin function doesn't (and shouldn't) modify the underlying stack, so it should be declared const.  The same is true for the print function.

Avoid using index variables

Rather than using an index variable i in the print routine and then calling at() for each iteration, use iterators instead.  For example, you could use this:

std::copy(stack.cbegin(), stack.cend(),
          std::ostream_iterator<int>(std::cout, ", "));

Omit empty strings

The current code for print includes this line:

std::cout<<""<<stack.at(i)<<", ";

There's no need for the empty string in that line.

Use whitespace to improve readability

To take the previously quoted line as an example, rewriting it with more whitespace makes it easier to read:

std::cout << stack.at(i) << ", ";

Don't use std::endl when '\n' will do

Using std::endl emits a \n and flushes the stream.  Unless you really need the stream flushed, you can improve the performance of the code by simply emitting '\n' instead of using the potentially more computationally costly std::endl.

Take care with signed versus unsigned

The code includes this line in the print function:

for (int i=0;i<stack.size();i++)

However, stack.size() is unsigned and i is signed.  For consistency, it would be better to declare i as std::size_t which is the type returned by size().

Consider the user of the code

The std::vector::pop_back() returns void but provides a member function back() to allow a user of the code to access the last member before removing it from the vector.  You might consider either returning the popped value in your implementation of pop or implementing a back function such as the one std::vector supplies.


First of all you should document the fact that your code does not work with numbers above 9999.

Then I think your code will become a bit simpler, if you add a fourth row to your d2r_table for the thousands. To avoid repetition you can use a list comprehension:

d2r_table = [
    ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'],
    ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'],
    ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'],
    ['M' * i for i in xrange(0,10) ]]

This allows you to not treat the thousands as a special case. So instead of:

thousands, hundreds, tens, units = match.groups()
result = 1000 * len(thousands)
result += d2r_table[2].index(hundreds) * 100
result += d2r_table[1].index(tens) * 10
result += d2r_table[0].index(units)

you can write:

thousands, hundreds, tens, units = match.groups()
result =  d2r_table[3].index(thousands) * 1000
result += d2r_table[2].index(hundreds) * 100
result += d2r_table[1].index(tens) * 10
result += d2r_table[0].index(units)
return result

Now you can easily notice the common pattern here: For each number from 0 to 3 you're taking the ith row of d2r_table, calling index on it with the 3-ith element of groups as the argument, then multiplying it with 10**i and lastly summing the results. You can abstract the common pattern like this if you want:

def value_for_group(i):
    group = match.groups[3-i]
    return d2r_table[i].index(group) * 10**i

return sum(value_for_group(i) for i in xrange(0,4))

You can also replace the magic numbers 3 and 4, with something more meaningful:

num_rows = len(d2r_table)

def value_for_group(i):
    group = match.groups[num_rows - 1 - i]
    return d2r_table[i].index(group) * 10**i

return sum(value_for_group(i) for i in xrange(0, num_rows))

This way your code will work without modification if you ever change d2r_table to account for extended roman numerals.

In your dec2roman function you're using integer arithmetic to iterate over the digits of the number. I think it'd be easier and clearer to just convert the number to a string and iterate over the digits with a for loop. By reversing the d2r_table, you can use zip to iterate over the table and the digits in parallel without any index based loops. This way your dec2roman function would look like this:

result = ''
# Make digits four digits long so it has the same number of digits
# as d2r_table has rows, then convert each digit to an int
digits = [int(digit) for digit in "%04d" % dec]

for digit, d2r_row in zip(digits, reversed(d2r_table)):
    result += d2r_row[ digit ]

return result

You can also use join with a generator expression instead of updating result imperatively:

digits = [int(digit) for digit in "%04d" % dec]
table = reversed(d2r_table)
return ''.join( d2r_row[ digit ] for digit, d2r_row in zip(digits, table) )

Again you might also want to replace the 4 in %04d with len(d2r_table), so your code will automatically adapt to a longer d2r_table.


Calculating the circumference and area of a circle

Is it customary in Java to place a function call inside of a println(), or is it better to put the returned value into a separate variable and then display that?

This is something I would say is primarily opinion based. For this little app, I think it's fine to put the function method call inside a println.

When it comes to more complex things, it is usually better to do the calculation separately from the output (or most importantly logging), because you don't want your program behavior to change when you remove a System.out.println or logging statement.

  Should I consider implementing input-validation for practice as this is a toy program?

I don't see any need to use input-validation when you're using nextInt on the Scanner. Perhaps you'd want to avoid a negative size, and either throw an exception or show an error message to the user, but that's probably it.

  Am I correct in making the calculation functions static?

Yes, absolutely. I see no reason for why they should not be static. Given the usefulness of them, it is a good idea to have them public as well (which you have).

Feature-request: You're currently not prompting for any input which might make the user confused. A simple System.out.println("Enter radius:"); would be nice to have.

Overall, your code looks perfectly fine. A minor minor minor nitpick is that you're writing one space more than necessary here:

System.out.println("Circumference: ");
System.out.println("Area: ");

Another minor nitpick is that your Scanner variable could be named either scanner or input instead. (Even though sc is a quite normal variable name for a Scanner) #perfectionist-naming.


Object-Orientedness

I find your object-oriented design deficient.  Basically, it's a bunch of procedural code that has been thrown into a class.  But what can you do with the GameOfLife object that you instantiate?  Nothing!

I would split the functionality into a Board class and a GameOfLife class.  The Board should be able to provide its own string representation, report the contents of a cell, set the contents of a cell, check if a coordinate exists, clone itself, and perhaps load from or save to a file.  The GameOfLife class would be a generator; each time you call life.next() it would produce a new board.

Your main() function should look like this:

board = Board.load('boardFile.dat')
game = GameOfLifeGenerator(board)
for _ in range(11):
    print(board)
    board = game.next()

Alternatively,

from itertools import islice

board = Board(15)
board.fill(row=7, col=7)
for state in islice(GameOfLifeGenerator(board), 11):
    print(state)

Naming

You shouldn't be using double-underscore variables.  If you want to suggest that an instance variable is private, use a name with a single underscore.

You use cell to mean column number, which is confusing terminology.  A "cell" should refer to one of the points on the grid; a cell has row and column coordinates.  (In contrast, I don't object as much to using row as shorthand for the coordinate of a row.  English is just weird that way.)

In __countSurrounding(), the SURROUNDING list shouldn't be all caps.  I'd consider that to be a variable rather than a constant.  (You could define it as SURROUNDING_OFFSETS = ((-1, -1), (-1, 0), ...) instead, which would be a constant.)  Also consider laying out the code this way for quick visualization:

surrounding = ((row - 1, col - 1), (row - 1, col), (row - 1, col + 1),
               (row    , col - 1),                 (row    , col + 1),
               (row + 1, col - 1), (row + 1, col), (row + 1, col + 1))

Miscellaneous

In __isInRange() and __nextGeneration(), you use len(__board[0]) as the width.  I would prefer that you use len(__board(row)) instead.

The __str__() function could be implemented more succinctly as

def __str__(self):
    return "\n".join(
        [''.join(
            ['#' if cell else '.' for cell in row]
         ) for row in self._board]
    ) + "\n"

or

def __str__(self):
    return "\n".join(
        map(lambda row: ''.join(
            map(lambda cell: '#' if cell else '.', row)
        ), self._board)
    ) + "\n"


Your code looks fine except for two points:

a Dispose() method should never throw an exception but yours will likely throw one if it is called twice. This can be avoided by having a private bool disposed variable which is checked by an if condition.
an event based method OnXXX is usually either private or protected and used to actually raise the event. A simple rename to ClipboardChanged will be sufficient to handle that issue.


Split a data file into files for each time step

IO operations

Your code for each line of "DEPTH.dat" first open file in append mode, next write one line and finally close file. You may reduce open() and close() calls only to lines when 'SCALAR' line appears.

def split_less_io_operations(src_filename):
    idx = 1
    with open(src_filename, 'r') as inp:
        outfile = open("TS_before_first_SCALAR.dat", 'w')
        for line in inp:
            if line.startswith('SCALAR'):
                outfile.close()
                outfile = open("TS_{}.dat".format(idx), 'w')
                idx += 1
            outfile.write(line)
        outfile.close()

if __name__ == "__main__":
    split_less_io_operations('DEPTH.dat')


a + b^2 + c^3 + d^4 <= S
  For above equation ,I need to count possible solutions.

  I tried following approach.

Integer inp=Integer.parseInt(br.readLine());
      // get maximum possible value of b,c,d which satisfy equation
      int b=(int) Math.sqrt(inp);
        int d=(int) Math.sqrt(b);
        int c=(int) Math.cbrt(inp);
        int count=0;

  ...

If I were the interviewer, I would already have marked you down heavily for your choice of variable names. The problem statement defines a, b, c, d, S. The natural choice of variable names for those values are a, b, c, d, S. Using b, c, d for something else almost looks as though you were deliberately trying to make the code unmaintainable.

                        if(total<=inp) {
                            count++;
                        }

Enumerating items one by one is nearly always the wrong way to count something.

If I asked you to count solutions to \$a \le S\$ would you write a loop? I hope not, because you can do it without any loop or any mathematical operations.

Now, how about \$a + b^2 \le S\$? This can be done with one mathematical expression. Hint: start from $$\sum_{b=0}^{\sqrt{S}} \textrm{countA}(S - b^2)$$

Cubes already grow quite fast, so

for (int c = 0; c <= maxC; c++) {
    for (int d = 0; d <= maxD; d++) {
        count += countAB(S - c*c*c - d*d*d*d)
    }
}

would be reasonably efficient. If you really want to microoptimise you can eliminate the multiplications in favour of some accumulators and addition, but that's probably not necessary for an interview question. They might ask about it in a follow-up.


Loop could be removed. Replace with collection or array with each button choice. Remove the element clicked from collection. Use Random to choose an index or key of another remaining button.

Instance variable could retain which button last clicked.

Cast of v2.getParent and the ViewManager could instead be held as references in instance variables and quickly retrieved from a collection.

If Swing, could look at using awt directly for increased performance.


Renaming numbered files for proper sorting

Here are several tips that might help write better/cleaner code. Note that my tips or help might not be perfect but it gives you an idea on how to write better code.

Naming you variables

Using variable names like k and n are very bad practice. Not only will other people not understand your code, if you haven't looked at your code for a while, you might have forgotten what each variable does/stands for. Give your variables a meaningful name. So after applying this, your code looks like this:

string currentName = fi.Name.Replace(fi.Extension, "");
int nameAsNumber = Int32.Parse(currentName);
string newName = nameAsNumber.ToString("D4");
newName = newName + fi.Extension;

string targetFile = Path.Combine(fi.DirectoryName, newName);
File.Move(fi.FullName, targetFile );

Over-creating variables

Storing operations/calculations on variables in new variables can be handy and even necessary in certain situations. But in this situation where you take a string, parse it to an int and make it a string again, I suggest you do this in one line. You can even add the extension in the same line:

string currentName = fi.Name.Replace(fi.Extension, "");
string newName = int.Parse(currentName).ToString("D4") + fi.Extension;

This does not mean you have to write all your code in one line, this an example of doing too much in one line:

string targetFile = Path.Combine(fi.DirectoryName, int.Parse(Path.GetFileNameWithoutExtension(fi.FullName)).ToString("D4") + fi.Extension);

The above line does exactly the same but it's not easy to read and/or maintain.

Re-inventing the wheel (part 1)

Why create methods/functions/lines of code that do something that's already been made for you. If you want to get the filename without the extension, use the Path.GetFileNameWithoutExtension() method.

string currentName = Path.GetFileNameWithoutExtension(fi.FullName);

Re-inventing the wheel (part 2)

Remember, the .NET framework contains classes and methods for almost anything. And this also goes for adding zeros (or other characters) to a string when they do not yet meet a desired length. This is done with the Pad() method, and in your case the String.PadLeft(Int32, Char) method. You simply provide the desired length and the character that will be put in place. Your code will become:

string currentName = Path.GetFileNameWithoutExtension(fi.FullName);
string newName = currentName.PadLeft(4, '0') + fi.Extension;

Your complete inside-loop code will now look like:

string currentName = Path.GetFileNameWithoutExtension(fi.FullName);
string newName = currentName .PadLeft(4, '0') + fi.Extension;
string targetFile = Path.Combine(fi.DirectoryName, newName);
File.Move(fi.FullName, targetFile);

I hope this helps! :)


Getting table cell contents in a row and displaying them as a concatenated tooltip on each cell

As far as making the code "secure from exploits", that might be tough to do with JavaScript, unless you take tactics like minification/obfuscation, etc. The suggestions below should allow the code to be more robust.

Naming

elem, elem1 and elem2 aren't very descriptive. Better names might be nameElement, populationElement1, populationElement2, etc.

Additionally, the variable in the for loop (i.e. i) is not declared using var so it is put into the global namespace.

Allow number of population columns to be dynamic

Currently the code only allows two columns of populations, and hard-coded to years 2000 and 2005. The table headers could have a class added:

Name
Population (2000)
Population (2005)

Then those population headers can be fetched from the DOM using document.getElementsByClassName() and stored in a variable:

var populationHeaders = document.getElementsByClassName('populationHeader');

Then the function placeTitle() can iterate over those titles and add the title attributes to the elements using the iterator variable, eliminating the need for elem1 and elem2:

for (var k = 0; k < populationHeaders.length; k++) {
    var populationCell = row.children[k+1];
    populationCell.title = nameElement.textContent + '\n' + populationHeaders[k].textContent+':' + populationCell.textContent;
}

Setting the titles on mouseover?

Why call placeTitle() when the use mouses over each row? This can lead to calling the function hundreds of times when it really only needs to be called once. So instead of the following:

for (i = 0; i < trLen; i++) {
    hoverRow[i].setAttribute("onmouseover","javascript: placeTitle(this);");
}

It would be better to just call placeTitle() once per row (instead of on every mouse over event):

for (i = 0; i < trLen; i++) {
    placeTitle(hoverRow[i]);
}

Or this could be done with the function approach - using Array.forEach():

hoverRow.forEach(placeTitle);

Duplicate function

Your code has two functions called placeTitle(). The first gets overwritten by the second, thus making it useless. Make sure your function names are unique.

var hoverRow = document.querySelectorAll("#table1 tbody tr"),
  trLen = hoverRow.length;

var place = document.getElementById('placeName');
var populationHeaders  = document.getElementsByClassName('populationHeader');

function placeTitle(row) {
  nameElement= row.children[0];
  nameElement.title = nameElement.textContent;
  for (var k = 0; k < populationHeaders.length; k++) {
    var populationCell = row.children[k+1];
    populationCell.title = nameElement.textContent + '\n' + populationHeaders [k].textContent+':' + populationCell.textContent;
  }
}

for (i = 0; i < trLen; i++) {
  placeTitle(hoverRow[i]);
}

      Name
      Population (2000)
      Population (2005)

      San Antonio
      3,420
      3,572

      Green Valley
      1,409
      1,222

Functional approach to iterating over the headers

In the snippet below, the headers are iterated over using Array.forEach(). That way there is no need to index into the array of population headers. document.getElementsByClassName() returns a HTMLCollection interface (different than an array) so the spread syntax (i.e. ...) is used to put the elements into an array.

var hoverRow = document.querySelectorAll("#table1 tbody tr"),
  trLen = hoverRow.length;

var place = document.getElementById('placeName');
var populationHeaders = document.getElementsByClassName('populationHeader');

function placeTitle(row) {
  nameElement= row.children[0];
  nameElement.title = nameElement.textContent;
  [...populationHeaders].forEach(function(populationHeader, index) {
    var populationCell = row.children[index + 1];
    populationCell.title = nameElement.textContent + '\n' + populationHeader.textContent + ':' + populationCell.textContent;
  });
}
hoverRow.forEach(placeTitle);

      Name
      Population (2000)
      Population (2005)

      San Antonio
      3,420
      3,572

      Green Valley
      1,409
      1,222

For more tips on interacting with the DOM via Javascript, check out this article. I know it is a few years old but still relevant*.

*at the time of writing


Eliminate redundancy from session authentication

Your two queries are essentially the same, except the second query is also joining to the users table.  This suggests that you might be able to remove the first query and simply execute the second query.

OUTER JOIN

Since you've said that it is possible for a client to have an active session, but no user associated with it, then you would need to to use an outer join, which mysql seems to support, to connect to the users table.  The explanation in the documentation isn't overly easy to follow, but essentially, when you do a normal join results are only returned if all the join criteria are met.  If you do an outer join, then results from the outer joined table (users) will be returned if present, otherwise columns from that table will be returned as null.

You can then determine if a user has a session (a row is returned) and if they're logged on (users columns have values) from a single query.


Getting last and this monday as Unix timestamp in JavaScript

I would suggest you use a date library like moment.js for this. That way, you don't have to do this all over again. With that library, it's just a few subtraction calls.

<script type="text/javascript">

By default, the browser executes JS. type is not required. The only time type is every used is if you want to tell the browser that it contains something not JS, preventing it from executing as JS.

24*60*60*1000

60 * 60 * 24 * 7 * 1000

These are constants. I suggest you use const with the convention of uppercase and underscores. If you can't use const, var will have to do but the naming convention stays.

new Date().getTime()

Use Date.now(). It's the same as new Date().getTime() without the Date object that it generates. Also, your code uses a lot of Date objects when the operation can be done with millisecond manipulation. Try avoiding the creation of objects when necessary.

setHours mutates the date object hours using local time. This means the hours you set are midnight local time. Unless this is something you intended or something UI only, this may cause issues with timekeeping.

In some regions, weeks start on a Sunday. "This Monday" may refer to the Monday that comes after that Sunday. "Last Monday" may also refer to this week's Monday that already passed. This makes the phrase "This Monday" and "Last Monday" vague.

Anyways, here's my take on it. Not much of a departure, but there's some notable changes.

(function() {
  'use strict'

  const WEEK_IN_MS = 604800000;
  const DAY_IN_MS = 86400000;
  const DAY_MONDAY = 1;

  function getDateThisMonday() {

    // start with today's midnight
    let today = new Date();
    today.setHours(0, 0, 0);

    // We start the week with Monday, we assign 7 when its a Sunday (0)
    let dayToday = today.getDay() || 7;

    // Calculate milliseconds elapsed since Monday
    let msSinceMonday = ((dayToday - DAY_MONDAY) * DAY_IN_MS);

    // Subtract today midnight with the diff to get midnight of the Monday
    let mondayTime = today.getTime() - msSinceMonday;

    return mondayTime;
  }

  // This is pretty much the same except we subtract an additional week.
  function getDateLastMonday() {
    return getDateThisMonday() - WEEK_IN_MS;
  }

  document.write('Last Monday: ' + new Date(getDateLastMonday()));
  document.write('This Monday: ' + new Date(getDateThisMonday()));

}());


How to refactor the following sql statement?

You could just use OR:

  SELECT CASE WHEN COUNT(RoleID) > 0 THEN 1 ELSE 0 END AS isExists
  FROM Roles
  WHERE RoleDescAR='Arabic Name' OR RoleDescEN='English Name'


I see a number of things that may help you improve your program.

Gather constants together

The relationship among the numerical values that determine which unit is used and the divisor and the actual unit name is contained within a single function, which is good, but it could be more clear if expressed as a structure.  For example, one could use this:

struct Units {
  int limit;
  double divisor;
  std::string name;
};
static const std::array<Units,4> units;

Then outside of the class, we supply the values:

const std::array<my_length::Units,4> my_length::units = {{
  { 10, 1, "mm" },
  { 1000, 10, "cm" },
  { 1000000, 1000, "m" },
  { 0, 1000000, "km" },
}};

This brings things into much closer proximity so that it can be more easily seen and understood.  We can do a little better with C++17 by using std::string_view instead of std::string for the unit name.

Isolate concerns

It's usually better to have each function just do one thing.  So insted of deciding on units and also printing, I'd suggest splitting those into two, using a private member function:

const Units& selectUnit() const {
  auto ret{units.cbegin()};
  if (fmt_auto) {
      while (ret->limit && v >= ret->limit) {
          ++ret;
      }
  }
  return *ret;
}

Now the operator<< looks like this:

friend std::ostream &operator<<(std::ostream &out, const my_length &l) {
  const Units u{l.selectUnit()};
  return out << l.id << "/" << l.name << " : "
      << l.v/u.divisor << u.name;
}

Use standard algorithms

The test code starts with this:

std::vector<my_length> lengths;
my_length l{0, "a", 1};
lengths.push_back(l);
uint64_t val = 17;
for (int i=1; i<10; i++) {
    my_length l{i, std::string(1, 'a'+i), val};
    lengths.push_back(l);
    val *= 10;
}

I'd suggest that one could use std::iota instead.  I'll leave it to you to create the details of that.

Reconsider the design

Once constructed, there is no capability to do anything with the my_length object except to print it.  If all that's needed is printing, then it may be better to use a freestanding function in a namespace instead of an object, as suggested in the comments.  If not, then it makes sense to provide those other operations within the class.


Excessive perens in your ternary - they don't help with readability, scrap em...

$showAdminPanel = hasPerms($_SESSION['users_perms'], $_SESSION['role_perms'], 8) ? "
Admin Panel
" : "";

For long ternary lines I sometimes like to put a line break and a tab before the ? and :.

$showAdminPanel = hasPerms($_SESSION['users_perms'], $_SESSION['role_perms'], 8)
    ? "
Admin Panel
"
    : "";

The second ternary operator contains invalid HTML.
 must be a child of
 or
, not another
.

Using strcmp seems like overkill in the scandir loop. it would be faster to just use an == operator. Also, it's generally better practice to creatte and append to an array than to a string. Every time you add to taht string in that loop, the entire string has to be loaded into memory all over again. It's much quicker to use a buffer liek this...

$themes = array();
foreach(scandir($assetsDir."themes/") as $file) {
    if($file == "." || $file == "..") continue;
    $themes[] = '
'.substr(ucfirst($file),0,-4).'
';
}
// Turn the buffer into a string
$themes = implode('', $themes);

There is no reason for a heredoc here since you're at the end of the script. Just close the php tag and put the stuff after that (replacing the curlies with <?php= and ;?>), that way you don't have the PHP interpreter interpreting things it doesn't need to interpret.


@vnp has already given an excellent review of your algorithmic problems. I'm not going to duplicate their work. I'm just going to review the code itself.

using namespace std;

Avoid doing the above. It may save you a few keystrokes in a small program like this one, but can turn into a major maintenance headache for a codebase that you need to support. See this question.

long long  int n,x,a,b,sum=0,s=1;

Never declare multiple variables on a single line. It's very easy to screw up the syntax and get some surprising bugs. Declaring each variable on its own line does not make the code slower.
Don't declare variables until they're needed. You need n right away, but you don't use a or b until over 50 lines later.
Give variables descriptive names. In a problem like this, you can get away with using names like n, a, and b because they're the names in the problem. But what is x? I don't even see it being used at all? Is it vestigial from an earlier attempt at the problem?

On to the next lines....

long long int *size=new long long int[n];
long long int **arr=new long long int*[n];

Don't use naked new. Either use smart pointers or - in this case - containers. What you want here is std::vector. There is absolutely zero speed penalty for using a vector rather than allocating an array yourself with new.

You don't free any of the memory you allocate. I don't know if that's tolerated in these coding competitions, but it is undefined behaviour in general. Here's a hot tip: If you are in a coding competition where it's okay to leak memory, and you want to save every cycle so you don't want to pay for freeing any memory, you can still use standard containers. All you need to do is define an allocator that doesn't delete. Which is just:

template <typename T>
struct leaking_allocator
{
    using value_type = T;
    auto allocate(std::size_t n) { return new T[n]; }
    auto deallocate(T*, std::size_t) noexcept { }
};

If you'd used a vector, you wouldn't need both size and arr. You would just need auto A = std::vector<std::vector<long long int>{};. You would read n then do A.resize(n);. Then for each array you would read s and do A[i].resize(s);, and read the next s values into A[i][0] to A[i][s - 1]. The size of any array would be A[i].size().

And, of course, your program wouldn't leak (unless you deliberately made it do so by using a leaking allocator).

for(int i=1;i<=n;i++)
{
    arr[i]=new long long int[n];
}

You have an out-of-bounds error here. You're lucky the program doesn't crash. I know the problem talks about 1-based arrays, but C++ arrays are 0-based. You need to do that conversion, either in your head or in the code.

So either:

for(int i = 0; i < n; ++i)
    arr[i] = new long long int[n];

or:

for(int i = 1; i <= n; ++i)
    arr[i - 1] = new long long int[n];

(Note: As Pete Kirkham points out, the above is still wrong. The allocation line should be moved to the next loop, after cin>>size[s];. And instead of allocating n elements, it should be allocating size[s]. The vector versions don't have this bug.)

In the next loop:

for(int i=1;i<=n;i++)
{
    cin>>size[s];

    for(int j=0;j<size[s];j++)
    {
        cin>>arr[i][j];
    }
    s++;
}

You have the same out-of-bounds error. But you also have a needless extra loop variable. Both i and s are doing the same thing here. And you never use s again after this loop. You could simplify this to:

for (int i = 0; i < n; ++i)
{
    cin >> size[i];

    for(int j = 0; j < size[i]; ++j)
        cin >> arr[i][j];
}

But of course, if you used vectors, both of the above loops could simplify to:

auto A = std::vector<std::vector<long long int>>{}; // or, possibly, use leaking allocators here

auto n = 0;
std::cin >> n;
A.resize(n);

for (auto i = 0; i < A.size(); ++i)
{
    auto s = 0;
    std::cin >> s;
    A[i].resize(s);

    for (auto j = 0; j < A[i].size(); ++j)
        std::cin >> A[i][j];
}

or even better and safer, using range-based loops:

auto A = std::vector<std::vector<long long int>>{}; // or, possibly, use leaking allocators here

auto n = 0;
std::cin >> n;
A.resize(n);

for (auto&& arr : A) // for each array in A
{
    auto s = 0;
    std::cin >> s;
    arr.resize(s);

    for (auto&& item : arr) // for each item in A[i]
        std::cin >> item;
}

On to the calculation loop....

while(m--)
{
    cin>>a>>b;
    for(int i=1;i<=size[a];i++)
    {
        for(int j=0;j<size[b];j++)
            sum=sum+fabs(arr[a][i]-arr[b][j]);
    }
    cout<<sum;
    cout<<endl;
    sum=0;
}

Once again, that first inner loop has an out-of-bounds error.

@vnp has already pointed out that you should be using std::abs(), not std::fabs(). But here are some more tips to increase speed and readability:

sum=sum+fabs(arr[a][i]-arr[b][j]);

can be simplified to:

sum += std::abs(arr[a][i] - arr[b][j]);

Because you've declared sum outside of the loop, you have to clear it on each iteration. That's a little brittle. It would be safer and more sensible to declare sum just before calculating the sum.

Also:

cout<<endl;

Never use endl. Especially in performance code. If you want a newline, just write a newline.

So the loop above becomes:

while (m--)
{
    std::cin >> a >> b;

    auto sum = 0LL;
    for (int i = 0; i < size[a]; ++i)
    {
        for (int j = 0; j < size[b]; ++j)
            sum += std::abs(arr[a][i] - arr[b][j]);
    }

    std::cout << sum << '\n';
}

And if you use vectors, the code is basically identical:

while(m--)
{
    std::cin >> a >> b;

    auto sum = 0LL;
    for (int i = 0; i < A[a].size(); ++i)
    {
        for (int j = 0; j < A[b].size(); ++j)
            sum += std::abs(A[a][i] - A[b][j]);
    }

    std::cout << sum << '\n';
}

or with range loops:

while(m--)
{
    std::cin >> a >> b;

    auto sum = 0LL;
    for (auto item_a : A[a]) // for each item_a in A[a]
                             // (don't need && because they're just
                             // long long int, and we're just
                             // reading them)
    {
        for (auto item_b : A[b]) // for each item_b in A[b]
            sum += std::abs(item_a - item_b);
    }

    std::cout << sum << '\n';
}

And finally:

return 0;

There's no need for this. main() returns zero automatically.

Summary

You have two critical problems in your code:

You leak every array you allocate. If this is deliberate, at least document it with a comment. This problem would go away if you used smart pointers and containers. (But if you really want to leak, you can still use smart pointers and containers. You'd just need to use leaking deleters and allocators.)
Many of your loops access out-of-bounds memory. The problem talks about 1-based arrays, but arrays in C++ are 0-based. You need to do that conversion.

You have one problem that will really hurt your efficiency:

Don't use endl.

And you have a few minor problems that are mostly stylistic:

Don't declare variables until right before they're needed.
Don't declare multiple variables all on one line.
Don't use manual memory management - don't use naked new/delete. Use containers and smart pointers. They are zero-cost abstractions.
Space out your code. It's hard to spot errors when each line is just a jumble of symbols.

Some of the above will give you small speed boosts, but as @vnp noted, the real thing that's killing your time is that you didn't think the problem through, and just tried to brute-force it.

However, you have some serious bugs that you should worry about fixing first, before worrying about speed.


Large table updates using AJAX in Internet Explorer 11

Searching a whole, large DOM for elements is a real performance killer. When possible, always try to search a fragment, or traverse the DOM relative to a known element.

With a little rearrangement of the HTML, "network", "boot" and "check_in" elements can be found within the corresponding "selector" element, similar to the way "util" and "workgroup" elements are currently found. This alone should give a significant performance boost.

HTML

There's a missing
 somewhere.
Move
 and
 inside the loop/if lines to give one tbody per computer block. (Hopefully tbodys will not mess up tablesorter).
Move id="{{computer.name}}" into the
 tag.
Give a class name to elements that need to be addressed :

For example, change :

{{ computer.active_drive.name }}

to:

{{ computer.active_drive.name }}

Then, if they are not required elsewhere, purge all IDs in the repeated block.

Javascript

The javascript can now be written to exploit the tbody wrappers.

function writeTableLines(tempRows) {
    /*
     This Function takes care of updating the text and coloring of required dynamic fields.
     All other values are not dynamically written.
    */
    var tempValues, $tbody, $name, $network, $boot, $check_in, $util, $workgroup,
        $connectionGrid = $('#connectionGrid');

    // Avoid creating so many strings in the loop by defining class names and selectors here.
    // This is more a memory consideration than speed.
    var clss = {
        'warning': 'warning',
        'issue': 'issue',
        'redline': 'redline'
        'redlineWarning': 'redline warning',
    };
    var selectors = {
        'network': '.network',
        'boot': '.boot',
        'check_in': '.checked_in',
        'name': '.name',
        'util': 'td.util a',
        'workgroup': 'td.workgroup'
    };

    for(i in tempRows) {
        tempValues = tempRows[i];

        // Find the container
        $tbody = $('#' + i); // This is the only element in each block that needs an ID.

        if($tbody.length == 0) return; // avoid unnecessary work if element is not found

        // Now find elements by class, within the container
        $network = $tbody.find(selectors.network);
        $boot = $tbody.find(selectors.boot);
        $check_in = $tbody.find(selectors.checked_in);
        $name = $tbody.find(selectors.name);
        $util = $tbody.find(selectors.util);
        $workgroup = $tbody.find(selectors.workgroup);

        // In all the code below, address tempValues properties with dot.notation, not associative['notation']

        $network.text(tempValues.network);
        if (tempValues.network_color) {
            $network.addClass(tempValues.network_color);
            $name.addClass(tempValues.network_color);
        } else {
            $network.removeClass(clss.warning);
            $name.removeClass(clss.warning);
        }

        $boot.text(tempValues.boot);
        if (tempValues.boot_color) {
            $boot.addClass(tempValues.boot_color);
            $name.addClass(tempValues.boot_color);
        } else {
            $boot.removeClass(clss.issue);
            $name.removeClass(clss.issue);
        }

        $check_in.text(tempValues.checked_in);
        if (tempValues.service_unresponsive) {
            $check_in.addClass(clss.redline);
            $name.addClass(clss.redline);
        } else {
            $check_in.removeClass(clss.redline);
            $name.removeClass(clss.redline);
        }

        $util.text(tempValues.util);
        if (tempValues.util_class) {
            $util.addClass(tempValues.util_class);
        } else {
            $util.removeClass(clss.redlineWarning);
        }

        if (($.trim(tempValues.workgroup)) != $.trim($workgroup.text())) {
            if (tempValues.workgroup != selected && selected != 'All') {
                $workgroup.addClass(clss.warning);
            } else {
                $workgroup.removeClass(clss.warning);
            }
        }
        $workgroup.text(tempValues.workgroup);

        toggle_links(i, tempValues);
        $connectionGrid.trigger('updateAll', [false]);
    }
}

Some of the code looks to be as little dodgy. For example, .addClass(tempValues.network_color) ... .removeClass('warning') means that any added class that is not warning will never be removed (unless by some other code). Contrast with .addClass('redline') ... .removeClass('redline'), which is guaranteed to add/remove the same class.

Aside: With the tbodys in place, you could consider styling them with eg a border that will expand/contract as the details are shown/hidden.

If performance is still poor, you'll need to investigate deeper to discover what's taking time. Though I'm not an expert driver, Chrome debug tools are very good for diagnosis.

Edit

Back to a single
 but with class="info network", class="info boot", class="info check_in", in place, try selecting as follows :

// Find the parent row
var $tr = $('#' + i); // A parent row

if($tr.length == 0) return; // avoid unnecessary work if element is not found

var $childRows = $tr.nextUntil(".parent"); // the parent's child rows

$network = $childRows.find(selectors.network);
$boot = $childRows.find(selectors.boot);
$check_in = $childRows.find(selectors.checked_in);

$name = $tr.find(selectors.name);
$util = $tr.find(selectors.util);
$workgroup = $tr.find(selectors.workgroup);

This will be slightly less efficient than finding elements within tbody containers but still better than finding by ID - and Tablesorter will still work.


Korean word segmentation using frequency heuristic

It will be much faster to use Python's in operator for your substring search rather than using your custom-built "contains" function.

In [15]: %timeit 'brown' in  'blah'*1000 + 'the quick brown fox'
100000 loops, best of 3: 2.79 µs per loop

In [16]: %timeit contains('brown','blah'*1000 + 'the quick brown fox')
1000 loops, best of 3: 870 µs per loop

Also I wonder if you could rewrite some of your custom functions as dictionary comprehensions, something like this:

for word in read_words(args.wordlist):
    combos = {k:v for k,v in corpus if k in word}
    results = {'Original': word,
               'Pois': list(combos.keys())
               'Makeup': combos.items()
               'Freq_Max_Delta': sum(combox.values())}

    print(results)


VBA function to extract worksheets with numeric names

Sheets(1).Columns(1).ClearContents

It's not a big deal in this case since the macro is always meant to work with the active workbook, but generally you want to preface a "Sheets" reference with an explicit reference to the workbook.

It's also generally not a good idea to refer to sheets by number. Using sheet names tends to be easier to read/debug.

My recommendation would be to add some parameters to the macro so that you can explicitly specify both a) the workbook whose sheets' names you want to check, and b) the worksheet on which to print the results. You can make the parameters optional if you'd like, and set them to "ActiveWorkbook" and "ActiveWorkbook.Sheets(1)" if they're missing from the call.

  Application.Transpose(sheetNumberArray)

Once again, this isn't a huge deal in this particular macro, but Application.Transpose has some significant limitations (it doesn't work with very large arrays) and should be avoided if possible. In your case, since you're eventually just writing the results of your routine to the worksheet, ideally you'd just make your array two-dimensional:

ReDim resultsArr(1 To wb.Sheets.Count, 1 To 1) As Double

But currently that won't work because you're using...

  ReDim Preserve sheetNumberArray(x)

Which brings me to my final recommendation: ReDim Preserve has high performance costs, and should be avoided if possible (especially uses like this in which it's called repeatedly). In your case, it's pretty easy to avoid, as you should be able to see in my revised code below.

Sub exampleMacro()

    'Checks sheets in specified workbook, prints to specified worksheet
    Call listNumberedSheets(ThisWorkbook, ThisWorkbook.Sheets("Results"))

    'Checks sheets in active wb, prints to Sheets(1) of active wb
    Call listNumberedSheets

End Sub
Sub listNumberedSheets(Optional wbToCheck As Workbook = Nothing, Optional resultsWS As Worksheet = Nothing)

    If wbToCheck Is Nothing Then
        Set wbToCheck = ActiveWorkbook
    End If

    If resultsWS Is Nothing Then
        Set resultsWS = ActiveWorkbook.Sheets(1)
    End If

    ReDim resultsArr(1 To wbToCheck.Sheets.Count, 1 To 1) As Double
    Dim i As Long
    Dim j As Long
    j = 1
    For i = 1 To wbToCheck.Sheets.Count
        Dim shtName As String
        shtName = wbToCheck.Sheets(i).Name
        If IsNumeric(shtName) Then
            resultsArr(j, 1) = shtName
            j = j + 1
        End If
    Next

    With resultsWS
        .Columns(1).ClearContents
        If j > 1 Then
            .Range(.Cells(1, 1), .Cells(j - 1, 1)).Value = resultsArr
        End If
    End With

End Sub

For maximum flexibility/reusability, I'd probably make it a function instead of a sub. That way it can either write the results to a worksheet OR return the results as an array. I'd also probably change it so that it could check multiple workbooks simultaneously. That definitely complicates the code a bit, but potentially makes it useful in more situations.

Sub exampleMacro()

    'Checks sheets in specified workbooks, prints to specified worksheet
    Call listNumberedSheets(Array(ThisWorkbook, Workbooks("Example workbook.xlsx")), ThisWorkbook.Sheets("Results"))

    'Checks sheets in specified workbook, returns 1d array
    Dim arr As Variant
    arr = listNumberedSheets(ThisWorkbook)

End Sub
Function listNumberedSheets(wbToCheck As Variant, Optional resultsWS As Variant) As Variant

    Dim wbArr As Variant
    If Not IsArray(wbToCheck) Then
        wbArr = Array(wbToCheck)
    Else
        wbArr = wbToCheck
    End If

    Dim sheetCount As Long
    Dim i As Long
    For i = LBound(wbArr) To UBound(wbArr)
        If Not TypeName(wbArr(i)) = "Workbook" Then
            MsgBox "Error: wbToCheck must be either workbook or array of workbooks"
            Stop
            Exit Function
        Else
            sheetCount = sheetCount + wbArr(i).Sheets.Count
        End If
    Next

    ReDim resultsArr(1 To sheetCount, 1 To 1) As Double
    Dim j As Long
    Dim counter As Long
    counter = 1
    For i = LBound(wbArr) To UBound(wbArr)
        For j = 1 To wbArr(i).Sheets.Count
            Dim shtName As String
            shtName = wbArr(i).Sheets(j).Name
            If IsNumeric(shtName) Then
                resultsArr(counter, 1) = shtName
                counter = counter + 1
            End If
        Next
    Next

    If IsMissing(resultsWS) Then
        If j = 1 Then
            listNumberedSheets = ""
        Else
            ReDim finalArr(1 To counter - 1) As Double
            For i = LBound(finalArr) To UBound(finalArr)
                finalArr(i) = resultsArr(i, 1)
            Next
            listNumberedSheets = finalArr
        End If
    ElseIf TypeName(resultsWS) = "Worksheet" Then
        If j > 1 Then
            With resultsWS
                .Columns(1).ClearContents
                .Range(.Cells(1, 1), .Cells(counter - 1, 1)).Value = resultsArr
            End With
        End If
    End If

End Function