Process a list of instructions and output the max value reached

As the comment threads make clear, the mystery about global goes away when you recognize the difference between accessing a variable from an outer scope (like your did with __registers___ and assigning to a variable whose name happens to also exist in an outer scope (what happened with __max__)

You can simplify a good bit of this by exploiting exactly this behavior.  If you store your registers in a module-level dictionary, you can access that dictionary in any part of the code without having to pass it around. Since you don't assign the dictionary -- you just access it -- you don't need to declare it global.  So in you case you could eliminate the find() function because you'd just grab a register value out of the dictionary.

 REGISTERS = {'a': 0, 'b': 1}

 def increment(reg, val):
     REGISTERS[reg] += val

would be an example.  In this case we can be a bit lazy and use a dictionary comprehension -- a shorthand way to fill out a dictionary with keys from 'a' to 'z' and values of all zeros:

import string  # the string module has a builtin for the ascii alphabet
REGISTERS = {char: 0 for char in string.ascii_lowercase}

So you don't need a register class -- you just manipulate the values in the dictionary for each register.

To do the instruction parsing, you can simplify things a good bit by eliminating the regex and simply using Python's builtin string split() function, which will take a string like  'b inc 5 if a > 1' and turn it into ['b', 'inc', '5', 'if', 'a', '>', '1'] without any extra work (this would not be appropriate if any of your directives had spaces in them -- but they don't seem to in this example).  That gives you 7 tokens -- your comment here was very useful -- 3 describing the tests you want to apply and three describing the operation to perform in the test passes (#3, the if, is basically ignorable).

With everything already parsed out, you really don't need to use classes.  The Instruction class does only two things: it applies the test in the last three tokens, and if that test is true it uses the instructions in the first three tokens to change the register.  Python has a handy built-in way to do what you're trying to do -- capturing common operations like addition or comparison.  The operator module has a bunch of functions which correspond to the basic operations. For example 'inc' corresponds to operator.iadd which is basically a += b expressed as a function.  '>' becomes operator.gt, a function that returns true if the first of its arguments is greater than the second.

That would get rid of much of the logic in your Instruction class.  Another module level 'global' dictionary is an easy way to map the strings to the operator,  simplifying both the process of parsing -- no conditional checks, just dictionary lookups -- and of running the tests.  So, first a dictionary to do the mapping:

# match operator functions to string identifiers
OPERANDS = {
    'inc': operator.iadd,
    'dec': operator.isub,
    '>': operator.gt,
    '>=': operator.ge,
    '<': operator.lt,
    '<=': operator.le,
    '==': operator.eq,
    '!=': operator.ne
}

and with that in place the functions to use these operators are very simple. If you want to apply some operation to a register, you get the value from the REGISTERS dictionary, the operator from the OPERANDS dictionary, then call the operator with your value:

def apply_value(register, opstring, valstring):
    operator = OPERANDS[opstring]
    value = float(valstring)
    orig = REGISTERS[register]
    REGISTERS[register] = operator(orig, value)

doing the test ('is this larger than 5' or whatever) is equally simple:

def condition(register, teststring, testval):
    check = OPERANDS[teststring]
    value = float(testval)
    existing = REGISTERS[register]
    return check(existing, value)

So as you parse a line of instructions, you just run condition function on the last three tokens ("a > 5") and if it's true, run the apply_value function on the first three:

    with open(filename, 'rt') as fileread:
        for directive in fileread:
            tokens = directive.split()  # [3] is always 'if', so ignored
            if condition(tokens[4], tokens[5], tokens[6]):
                apply_value(tokens[0], tokens[1], tokens[2])

If you run that on all your directives you'll see the register values going up and down.  Python also has an easy built-in way to find the maximum value in a series -- so to get the largest register value it's just

    max_value = max(REGISTERS.values())

with no need for you to track the max value manually.

Putting it all together it might look like this:

import sys
import operator
import string

# match operator functions to string identifiers
OPERANDS = {
    'inc': operator.iadd,
    'dec': operator.isub,
    '>': operator.gt,
    '>=': operator.ge,
    '<': operator.lt,
    '<=': operator.le,
    '==': operator.eq,
    '!=': operator.ne
}

# REGISTERS is a dictionary with names as keys, initialized to 0's
REGISTERS = {char: 0 for char in string.ascii_lowercase}

def apply_value(register, opstring, valstring):
    operator = OPERANDS[opstring]
    value = float(valstring)
    orig = REGISTERS[register]
    REGISTERS[register] = operator(orig, value)

def check_condition(register, teststring, testval):
    check = OPERANDS[teststring]
    value = float(testval)
    existing = REGISTERS[register]
    return check(existing, value)

if __name__ == '__main__':
    filename = sys.argv[-1]
    with open(filename, 'rt') as fileread:
        for directive in fileread:
            tokens = directive.split()  # [3] is always 'if', so ignored
            if check_condition(tokens[4], tokens[5], tokens[6]):
                apply_value(tokens[0], tokens[1], tokens[2])

    max_value = max(REGISTERS.values())
    for name, value in REGISTERS.items():
        if value == max_value:
            print ("highest register:", name, value)

As with many problems in Python, the rich offerings in the standard library often let you get away with just simple functions instead of lots of custom classes.


Download the JSON from API and parse the data like Unique Voting Station Name and Councillors Name

First, you should stop using Python 2, if possible. It will stop being supported in a bit over a year. Switch to Python 3, it is better in many ways.

Now, let's start with year not in range(2013,2018,4). This is a very inefficient way to do this, because in Python 2, range just generates a list and in lookup in lists is \$\mathcal{O}(n)\$. Instead use a collection for which in is \$\mathcal{O}(1)\$, like set or `dict. This is a good habit to form, even though here this list has only two elements.

As a side note, this was such a common beginner's mistake that they made sure that the Python 3 implementation of range (which is a generator on steroids), is actually \$\mathcal{O}(1)\$.

Now, to come to the underlying problems of the code. It is currently a mix of global variables, global code, function definitions, which sometimes take arguments, but also use global variables, and all of which modify global state (even though some of hem also return something). And these functions are then called right away.

Instead, try to define pure functions, that is functions that take all they need as arguments and return their result, without modifying any global state. You can then use these functions in a main method that does all the work.

import json
import requests
CRED = '\033[91m'
CEND = '\033[0m'

URLS = {2013: "https://data.calgary.ca/resource/kqmd-3dsq.json",
        2017: "https://data.calgary.ca/resource/4wni-k3sg.json"}

WARDS = set(range(0, 14))

def ask_year():
    while True:
        try:
            year = int(raw_input("\nElection Year to Search {}:".format(sorted(URLS.keys()))))
            if year not in URLS:
                print "No data for that year!"
                continue
        except ValueError:
            print "Please enter a valid year!"
            continue
        return year

def ask_ward():
    while True:
        try:
            ward = int(raw_input("\nWard to Search:"))
            if ward not in WARDS:
                print "Ward does not exist in City of Calgary !"
                continue
        except ValueError:
            print "Invalid ward number!"
            continue
        return ward

def get_voting_stations(ward, data):
    for station in data:
        try:
            if station["wards"] == ward:
                yield station["voting_station_name"]
        except KeyError:
            continue

def print_ward_voting_stations(ward, data):
    vorting_stations = set(get_voting_stations(ward, data))
    if vorting_stations:
        print "\nThere were in total", len(vorting_stations), "unique voting stations in your ward"
        print "\nThe list of the Voting Station were as follows"
        for i, name in enumerate(vorting_stations, 1):
            print '{} {}'.format(i, name)
    else:
        print CRED, "\nCity of Calgary has no Data on voting stations for ward {} in year {}".format(ward, year), CEND

def get_councillors(ward, data):
    for ballot in data:
        if ballot["ward"] == ward and ballot["office"] == "COUNCILLOR":
            yield ballot["ballot_name"]

def print_ward_councillors(ward, data):
    councillors = set(get_councillors(ward, data))
    if councillors:
        print "\nThere were in total", len(councillors), "councillors in your ward"
        print "\nThe list of the Councillors were as follows"
        for i, name in enumerate(councillors, 1):
            print '{} {}'.format(i, name)
    else:
        print CRED, "\nCity of Calgary has no Data on this Ward for Councillors in year", year, CEND

if __name__ == "__main__":
    print " \nThis is Json Data Parser Program. \nThis program will print the Unique Voting Station Name from 2013 or 2017 City Elections from City of Calgary OpenData Portal"

    year = ask_year()
    print "You chose: {} year for Elections Results".format(year)
    ward = str(ask_ward())
    print "\nYou chose ward: {} for Elections Results".format(ward)

    data = requests.get(URLS[year]).json()
    print_ward_voting_stations(ward, data)
    print_ward_councillors(ward, data)

The major differences are: I used a dict to map from the year to the url of the json file. This automatically raises a KeyError if an undefined year is given. You also already ensure that what the user entered is a valid year, here I re-used the keys of that dictionary.

I used a set for the valid wards. Both the urls and the wards are constant, and therefore written in ALL_CAPS, as recommended by Python's official style-guide, PEP8.

I separated the filtering of the data for what you need and making it unique. For this I defined each one function for outputting a stream of the voting stations/the office the ballot was for. This is then consumed by set, which makes it unique (but removes the order, which I think is not important here). This once again removes the necessity to do e.g. i["voting_station_name"] not in wardstnresult, which is again \$\mathcal{O}(n)\$.

I also removed catching KeyboardInterrupt and EOFError. Catching these errors should be well motivated. The first one appears when the user presses Ctrl+C, which means they want to abort whatever you are doing. Ignoring that and telling them to please enter a valid year is almost passive aggressive. The same goes for the latter, which happens if the user presses Ctrl+D. This is used to denote that the input is finished (especially important for multi line input). I don't see any reason whay you would want to catch that here.

Instead I replaced these with an infinite while True loop, which continues asking the user until they enter a valid year/ward or press Ctrl+C, which kills the whole program.


First, use try/catch blocks around parts that can throw exceptions.  For example, what happens when an IOException is thrown by the file, perhaps because the data is corrupted and the file exists, but cannot be opened?

Second, I don't know what constitutes failure, but an app-closing failure is failure in my book:

if(!file.isFile()){
    System.err.println("ERROR: File does not exist.");
    System.exit(-1);
}

Third, @SirPython is right - use the built-in method for reading your number.  There are built-in functions provided for reading both doubles and ints, whichever your program needs.

Fourth, this will not necessarily help robustness, split your method logic up.  You are doing a lot of printing in your fileInput() method.  Do your printing in a dedicated method.  Do your input in a dedicated method.  Feel free to throw an exception when exceptional behavior happens, but be sure to handle the exception.  Split your logic up into bite-sized components and implement them separately - this will make reuse easy.

Fifth, recover from your errors.  If you need, start the entire input processes over, but do not close the program.  Closing the program because of an error will probably be counted as an error, and is unacceptable in many programs.


Golang keep installation status for multiple installations process

Overall this looks like a pretty sensible file. Some minor points you might want to consider follow.
Imports
logr is not imported in the file. I presume this is https://github.com/go-logr/logr. It's passed into the first function but not used. Perhaps remove it from the signature?
Discrete strings
overallStatus returns one of four strings. You could define these strings as constants like Siva mentioned. A step further is to introduce a type that groups these strings together. This

ensures the function returns one of the strings defined, and
makes it clear what strings can be returned from the function by looking at the signature.

type status string

const (
    statusUnknown   status = ""
    statusError     status = "error"
    statusInstalled status = "installed"
    statusReconcile status = "reconcile"
)


PHP Sort Associative Array first by relativity of value then by other value desc

You are not actually sorting on qt, only using it to separate two sets (positive qt coming first). Only within each set you are actually sorting (on sa). Therefore, the usort() comparator function could look like this:
usort($array, function($a, $b) {
    // split in positive and negative set
   if ($a['qt'] <= 0 && $b['qt'] > 0) return 1; // b before a
   if ($a['qt'] > 0 && $b['qt'] <= 0) return -1; // a before b

   // both a and b are in the same set. sort on `sa` descending
   return $b['sa'] - $a['sa'];
});


Instead of implementing consume() for each integer type separately,
you can implement a single generic method:

mutating func consume<T: FixedWidthInteger & UnsignedInteger>() throws -> T {
    let size = MemoryLayout<T>.size
    guard idx + size <= bytes.count else {
        throw Error.notEnoughBytes
    }
    defer { idx += size }
    return bytes[idx..<idx + size].enumerated().reduce(0) {
        $0 + T($1.element) << (8 * $1.offset)
    }
}

which can be used for all unsigned integer types UInt, UInt8, ..., UInt64, e.g.

let header: UInt8 = try buffer.consume()

and for the signed integer types via the bitPattern: initializer, e.g.

let word = try! Int16(bitPattern: buffer.consume())

Another option is to copy the bytes into a value of the desired type
instead of bit shifting and adding:

mutating func consume<T: FixedWidthInteger>() throws -> T {
    let size = MemoryLayout<T>.size
    guard idx + size <= bytes.count else {
        throw Error.notEnoughBytes
    }
    var value: T = 0
    bytes.withUnsafeBytes { _ = memcpy(&value, $0.baseAddress! + idx, size) }
    idx += size
    return T(littleEndian: value)
}

Instead of letting the compiler infer the return type from the context,
one can alternatively pass it as a parameter:

mutating func consume<T: FixedWidthInteger>(_: T.Type) throws -> T { ... }

which is then – for example – called as

let crc32 = try buffer.consume(UInt32.self)

I would probably call the method get() or read() instead of consume().

Defining a local enum Error type which conforms to the (global)
Error protocol is possible, but might be confusing to the reader.
I would use a different name for the concrete error type, for example:

enum ReadError: Error {
    case notEnoughBytes
}

Now let's have a look how an error would be reported.
The caller does not know the actual error type, so a typical calling
sequence is:

do {
    let someData = Data(bytes: [1])
    var buffer = ConsumableByteArray(data: someData)
    let crc32: UInt32 = try buffer.consume()
    print(crc32)
} catch {
    print(error.localizedDescription)
}

This produces the output:

The operation couldn’t be completed. (MyProg.ConsumableByteArray.ReadError error 0.)

This can be improved by adopting the LocalizedError protocol
(see for example How to provide a localized description with an Error type in Swift? on
Stack Overflow):

enum ReadError: Error, LocalizedError {
    case notEnoughBytes

    public var errorDescription: String? {
        switch self {
        case .notEnoughBytes:
            return "Not enough bytes in buffer"
        }
    }
}

Now the error output of the above program becomes

Not enough bytes in buffer

You can even store additional information about the error in associated
values:

enum ReadError: Error, LocalizedError {
    case notEnoughBytes(available: Int, needed: Int)

    public var errorDescription: String? {
        switch self {
        case .notEnoughBytes(let available, let needed):
            return "Not enough bytes in buffer (available: \(available), needed: \(needed))"
        }
    }
}

Then by throwing

 throw ReadError.notEnoughBytes(available: bytes.count - idx, needed: size)

an error message like

Not enough bytes in buffer (available: 1, needed: 4)

is produced.

Finally note that there is a ByteBuffer type as part of the
SwiftNIO framework,
which can do all this and more. Even if you decide not to use it,
having a look at its documentation and interface might be instructive.


So, let us see what you are doing.

You query your database for IEnumerable<RezeptBilder> and iterate over the enumeration where you are converting the items to Image and add it to a List<Image>.
Then you are converting the Image back to a Byte[] to write it into the response stream.

Byte[] -> Image -> Byte[] isn't really necessary.

As you don't use methods of the List<T> but rather of the interface IList<T> we will return an IList<T> as it is always better to code against an interface instead of an implementation.

public static IList<Byte[]> GetRezeptImages(int rezeptId)
{
    using (CookBookDataContext ctx = new CookBookDataContext(Resources.ResourceFile.DBConnection))
    {
        IEnumerable<RezeptBilder> bilder = from b in ctx.RezeptBilders where b.FKRezept == rezeptId select b;
        IList<Byte[]> imageList = new List<Byte[]>();

        foreach (RezeptBilder b in bilder)
        {
            imageList.Add(b.Bild.ToArray());
        }

        return imageList;
    }
}

and to be called

public void ProcessRequest (HttpContext context)
{
    int rezeptId = Int32.Parse(context.Request.QueryString["rezeptId"]);
    int imageId = Int32.Parse(context.Request.QueryString["imageId"]);

    IList<Byte[]> images = DBManager.GetRezeptImages(rezeptId);
    context.Response.ContentType = "image/png";
    context.Response.BinaryWrite(images[imageId]);
}

But this shouldn't fix your issue. Taking 28 seconds for accessing 1.3 MB comes down to about 48 Kbyte/s which is quit slow.

To check where the most time is used, you need to measure the time it takes to execute the call to GetRezeptImages().

Smaller images will for sure speed the whole thing up and therefor makes the user of the website happy.

General

What will happen if a user of the site is changing the image url inside the address bar like  ImageHandler.ashx?rezeptId=testForTryParse&imageId=0 ?

Your ProcessRequest() method would throw an exception. You should carefully validate the input. This can be done in this case by using Int32.TryParse() instead of Int32.Parse().

Also you will get an exception, if the requested imageId is greater than the count of the IList.

public class ImageHandler : IHttpHandler
{

    public void ProcessRequest (HttpContext context)
    {
        int rezeptId = 0;
        int imageId = 0;

        if( Int32.TryParse(context.Request.QueryString["rezeptId"], out rezeptId) &&
             Int32.TryParse(context.Request.QueryString["imageId"], out imageId))
        {

            IList<Byte[]> images = DBManager.GetRezeptImages(rezeptId);
            if (images.Count > imageId)
            {
                context.Response.ContentType = "image/png";
                context.Response.BinaryWrite(images[imageId]);
                return;
            }
        }
        // a proper defined error response here
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

Style

You should be consistent with your coding style. It is a matter of taste where to place the opening braces {. Most do it on a new line, some place it on the same line. But you should stick to it.


Generating a random alphanumeric string succinctly and efficiently

You could use
Array.new(8){[*'0'..'9', *'a'..'z', *'A'..'Z'].sample}.join

From the documentation for Array:

new(size=0, obj=nil) new(array) new(size) {|index| block }
Returns a new array. In the first form, the new array is empty. In the second it is created with size copies of obj (that is, size references to the same obj). The third form creates a copy of the array passed as a parameter (the array is generated by calling to_ary on the parameter). In the last form, an array of the given size is created. Each element in this array is calculated by passing the element’s index to the given block and storing the return value.

Perhaps it is better to create the array with the valid characters once in advance:
range = [*'0'..'9', *'a'..'z', *'A'..'Z']
Array.new(8){range.sample}.join

I made a Benchmark for the solutions.
require 'benchmark'
N = 10_000 #Number of Test loops

Benchmark.bmbm(10) {|b|

  b.report('Nat'      ) { N.times { ([nil]*8).map { ((48..57).to_a+(65..90).to_a+(97..122).to_a).sample.chr }.join } }
  b.report('tokland') { N.times { 8.times.map { [*'0'..'9', *'a'..'z', *'A'..'Z'].sample }.join } }
  b.report('knut'   ) { N.times { Array.new(8){[*'0'..'9', *'a'..'z', *'A'..'Z'].sample}.join } }
  b.report('Natinit') {
    range = ((48..57).to_a+(65..90).to_a+(97..122).to_a)
    N.times { ([nil]*8).map { range.sample.chr }.join }
  }
  b.report('knutinit') {
      range = ((48..57).to_a+(65..90).to_a+(97..122).to_a)
      N.times { Array.new(8){range.sample}.join }
  }

} #Benchmark

The result:
Rehearsal ---------------------------------------------
Nat         0.765000   0.000000   0.765000 (  0.765625)
tokland     2.172000   0.000000   2.172000 (  2.171875)
knut        1.953000   0.000000   1.953000 (  1.984375)
Natinit     0.063000   0.000000   0.063000 (  0.062500)
knutinit    0.078000   0.000000   0.078000 (  0.078125)
------------------------------------ total: 5.031000sec

                user     system      total        real
Nat         0.781000   0.000000   0.781000 (  0.781250)
tokland     1.953000   0.000000   1.953000 (  1.968750)
knut        1.922000   0.000000   1.922000 (  1.921875)
Natinit     0.063000   0.000000   0.063000 (  0.062500)
knutinit    0.078000   0.000000   0.078000 (  0.078125)

@Nat: Gratulation, your version is the fastest ;)
To analyze the fastest way to build the range I used the following benchmark:
Benchmark.bmbm(10) {|b|

  b.report('Natinit') {
    N.times { ((48..57).to_a+(65..90).to_a+(97..122).to_a) }
  }
  b.report('knutinit') {
      N.times { [*'0'..'9', *'a'..'z', *'A'..'Z'] }
  }
} #Benchmark

Result:
Rehearsal ---------------------------------------------
Natinit     0.093000   0.000000   0.093000 (  0.093750)
knutinit    0.250000   0.000000   0.250000 (  0.250000)
------------------------------------ total: 0.343000sec

    user     system      total        real
Natinit     0.094000   0.000000   0.094000 (  0.093750)
knutinit    0.219000   0.000000   0.219000 (  0.218750)


Since the char array sizes are fixed, you should make sure the inputs are of an appropriate size before continuing.  This should best be done with the function doing the reading.

Very important: gets() is unsafe as it has no knowledge of buffer size thus is vulnerable to buffer overflow.  Instead, use fgets(), which is safer as it takes a buffer size as an argument.
Consider hard-coding the 50 to make its intent clear.

#define MAX_LENGTH 50

Since you're already in main(), you can use return 1 instead of exit(1).
Unformatted strings like this:

printf("Please enter a string: ");

can instead be output using puts():

puts("Please enter a string: ");

Be aware that puts() automatically appends a newline at the end.  If you don't want this newline, then you can use fputs() instead:

fputs("Please enter a string: ", stdout);


I guess I'm just assuming that it's inefficient because it makes my macbook's fans spin up after maybe 10 seconds

That's not really a good measure of "efficiency". The browser is trying to render 60 frames per second. That's a frame every ~16ms. Of course that's going to cause your processor to churn.

Math.floor(i+Math.sin(t/10)*10)

You can use <number> | 0 to trim off the decimal places of your numbers. In some JS engines and certain versions of JS engines, bitwise operations are faster than your regular math functions.

2 * Math.PI

There is a very small penalty when accessing object properties and becomes evident when you use it all over the place. Since Math.PI is a constant value, it wouldn't hurt if you assigned it to a variable for direct access. In fact, 2 * Math.PI is also constant. Why not put the result in a variable and spare the engine a multiplication operation as well.

function animate() {
  ...
  requestAnimationFrame(animate)
}

The issue with depending on just the render loop is the time it takes between updates. requestAnimationFrame can run faster or slower depending on conditions. If your "tweening" is time-sensitive, you might want to update based on delta-time instead.


The type hints you're using for containers are too generic .i.e list, dict etc. You could make them more helpful using the types present in typing module.

from typing import Dict, List, Union

def format_line(len_dict: Dict[str, str], line: FstabLine) -> str:
def get_longest(lines: List[str]) -> Dict[str, str]:
def parse(content: List[str]) -> List[Union[str, FstabLine]]:

This could also be done for variables like parsed_content as well because Mypy currently throws error for it:

  error: Argument 1 to "append" of "list" has incompatible type
  "FstabLine"; expected "str"

parsed_content: List[Union[str, FstabLine]] = []


def input_value(input_name, prompt, min_num, max_num):

input_name is always a number - why are you calling it a 'name'? Also, there's no need to take it as an argument, since you never use its initial value in your function.

    while True:
        data = raw_input(prompt)
        if data:
            try:
                input_name = int(data)
            except ValueError:
                print 'Invalid input...'

Consider putting a continue here, for clarity. It isn't necessary, though.

            else:
                if input_name >= min_num and input_name <= max_num:

Python understands if min_num <= input_name <= max_num:

                    return input_name
                    break

You don't need break here, the return makes it unreachable.

                input_name = 'Please try again: '

Assigning a string to something that's otherwise always a number is odd, and this value is never used anyway. Nix this line.

        else:
            print 'Goodbye!'
            break

This will end up falling off the end of the function, and so returning None. The rest of your script will continue, but eventually fail horribly. This probably isn't what you want.

month = 0
day = 0
year = 0
century = 0

Only reason to initialise these to 0 is to pass them into input_value, but, as I said above, it never uses the zero values. So, you don't need this.

month = input_value(month, "Please enter the month (from 1-12, where March is 1 and February is 12): ", 1, 12)

March = 1 is an odd system. Consider inputting it as January=1 and then transforming it with:

# Weirdify month counting
month = month - 2 if month < 3 else month + 10

To not surprise your users.

day = input_value(day, "Please enter the day (from 1-31): ", 1, 31)
year = input_value(year, "Please enter the year (from 0 - 99, eg. 88 in 1988): ", 0, 99)
century = input_value(century, "Please enter the century (from 0 - 99, eg. 19 in 1988): ", 0, 99)

These lines are very long. You should wrap them per PEP8:

 year = input_value("Please enter the century (from 0 - 99, eg. 19 in 1988): ",
                     0, 99)

Also, you might consider inputting year and century as a single value ('1988') and separating it in the script.

A = month
B = day
C = year
D = century

Just use the long names throughout your formulae, eg X = year / 4.

W = (13*A - 1) / 5
X = C / 4
Y = D / 4
Z = W + X + Y + B + C - 2*D
R = Z % 7

birthday = "You were born on " + str(B) + "/" + str(A+2) + "/" + str(D) + str(C) + " which was a "

Use string formatting instead of concatenation:
    birthday = "You were born on {}/{}/{}, which was a {}{}".format(day, month+2,
                                                                    century, year)

if R == 0:
    print birthday + 'Sunday'
elif R == 1:
    print birthday + 'Monday'
elif R == 2:
    print birthday + 'Tuesday'
elif R == 3:
    print birthday + 'Wednesday'
elif R == 4:
    print birthday + 'Thursday'
elif R == 5:
    print birthday + 'Friday'
elif R == 6:
    print birthday + 'Saturday'

This can go into a list:

 days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday',
         'Thursday', 'Friday', 'Saturday']
 day_of_week = days[R]

And then that can go in the above string formatting instead of being concatenated on later.


Prepared statement inside function that then return results

To begin, your indentation is a little off at places, such as in the while loop in the second code block, or the return statement in the first.

It looks like you keep o.checkout as an integers like the = '0' suggests, but use strings, as the '' suggests. If you do measure solely in integers, you ought to change the database type.

WHERE
    o.username ='$user'

You should use bind_param() instead of straight injection, as it's safer for sanitisation.


Some comments.

It is safer to swap the order when compare - even if you have already checked for null:

else if ("".equals(s)) return "";

Even better 1-liner:

if (s == null || "".equals(s)) return s;

What if you have other separators then space - like tabs, new-lines, \r etc?

if (s.charAt(index) == ' ')

Use regex to match all white-spaces:

// global
Pattern p = Pattern.compile("\\s+");

Actually - just think about it - your solution is not working for such cases, maybe regex is not the best way either.

Regarding your questions:
split() is slower then charAt() because former is kind of a regex search in string, charAt is just similar to index access to array.

My opinion is that this "mambo-jumbo" with searching spaces and revering the rest of the string recursively is not worth any theoretical gains it possibly has.
Code is difficult to understand - it took me a minute to get the idea what you are doing here.

Why not just to split for all spaces and reverse iterate over tokens? This solution does not preserve spaces BTW, so maybe not good.
So question you should ask on interview - if spaces needs to be preserved on not.

I didn't read your link BTW - this maybe exactly what is proposed there - because the point is to comment on your code and not to compare with somebody else.


Given a digit sequence, print the possible decodings of the given digit sequence

A few hints :

compile your code with all warning enabled (calls doesn't seem to be used, does it ?)
write your code in such a way that it can easily be tested. This includes taking a well-defined input and returning a well-defined value (instead of printing it).
write tests.

An example of dynamic programming approach (but I do think it will be better for you if you try to rewrite your solution with tests first, at least you'll be able to compare results and performance): asuming you have a string s "dddddD1D2" (a string composed of any digits then digit D1 then digit D2) and you know the number of combinations for all strings "" (empty string), "d", "dd", "ddd", ..., "ddddddD1", how to you know the number of combinations for string s ?

You have two different options :

either D2 is to be converted on its own (if D2 is positive). So if D2 is positive, you have as many combinations like this one as you have combinations for "ddddddD1" which is a known value.
either D2 is to be converted with previous digit D1. This is possible if 1 <= 10*D1 + D2 <= 26. If it is the case, you have as many combinations as the number of combinations for "dddddd" which is a known value.

Well, I gave you a solution assuming you had a solution. How do you get such a thing working ? You just need to iterate over the string and for each string position, you keep track of the number of combinations that can be generated using characters up to that point :

0 character : 1 combination
1 character : it has to be converted on its own. Reuse the solution for 0 characters.
2 characters : reuse the solution for 0 and 1 characters
n characters : reuse the solution for n-2 and n-1 characters.

This is a classic example of algorithm where we can define the number of elements with a property without having to enumerate them.

You can either save the two last results as you progress or you can keep track of the result for each index in an array. This is up to you.

Reusing your exemples and adding more :

nb("") = 1
nb("1") = nb("") = 1
nb("12") = nb("1") + nb("") = 1 + 1 = 2
nb("123") = nb("12") + nb("1") = 1 + 2 = 3
nb("1234") = nb("123") = 3 because 34 cannot be converted to a letter.

Disclaimer : I haven't tried any of this but I think it kind of makes sense. You'll see if it works as you write tests and compare with the results from your current code.


First off, I see a couple of things that can be shortened to generator expressions, rather than full-blown for loops. For example, this section:

file_header = []
head_line = head.find_element_by_tag_name('tr')
headers = head_line.find_elements_by_tag_name('th')
for header in headers:
    header_text = header.text.encode('utf8')
    file_header.append(header_text)
file_data.append(",".join(file_header))

Can be shortened immensely  to the following:

head_line = head.find_element_by_tag_name("tr")
file_header = [header.text.encode("utf8") for header in head_line.find_elements_by_tag_name('th')]
file_data.append(",".join(file_header))

Finally, your other for loop can be shortened to a generator expression as well. For more on generator expressions, see PEP0289.


Is this a valid way of computing autocorrelation?

How about xcorr(y)?  The xcorr() function is part of the Signal Processing Toolbox.


1. Divisible function

It is perfectly fine to define a function like divisible to improve the reading of a program. In general, when defining a function that could be reused, it is a good practice to comment its meaning (and this is encouraged by the syntax of the language):

(defun divisible (a b)
  "a is evenly divisible by b"
  (zerop (mod a b)))

Note the idiomatic use of the predicate (zerop x) instead of (= 0 x).

2. Introduction of variables

The use of setf (or setq) to introduce new variables is wrong (you should have received a warning, something like In FIZZBUZZ: Undeclared free variable OUT). The setf and setq operators should be used only to modify them.

Instead, you can introduce local variables with the let syntax:

(let ((new-local-variable1 initial-value)
      (new-local-variable2 initial-value)
      ...)
  body-in-which-the-new-local-variables-are-bound)

So fizzbuzz could be redefined as:

(defun fizzbuzz (n)
  "return n or Fizz or Buzz or FizzBuzz"
  (let ((out (string "")))

    (unless (or (divisible n 3) (divisible n 5))
      (return-from fizzbuzz n))

    (when (divisible n 3)
      (setf out (format nil "~d~d" out "Fizz")))

    (when (divisible n 5)
      (setf out (format nil "~d~d" out "Buzz")))

  out))

The global variables are instead introduced by defvar, so you could write for instance:

(defvar 1to100 (range 1 100))
(defvar 1to100fb (map 'list #'fizzbuzz 1to100))

3. The algorithm

The function range actually builds a list of (max-min+1) elements, filled with the values min, min+1, min+2, ..., max. The use of map over 1to100 is quite an expensive way of performing a simple iteration from the integer min to the integer max! Others, much more efficient ways, exist. For instance, you could do a classical loop (think of a for in a C-like language):

(loop for i from 1 to 100
  do (format t "~d~%" (fizzbuzz i)))

Another possibility is to use the dotimes operator:

(dotimes (i 100)
   (format t "~d~%" (fizzbuzz (1+ i))))

that iterates from 0 to (but not included) 100 (so there is the need of use the 1+ function).

If, on the other hand, you want to go for recursion, here is a possible solution (which is tail-recursive, so compiled by most systems as an iterative loop):

(defun fizzbuzz-to (limit &optional (start 1))
  (when (<= start limit)
    (format t "~d~%" (fizzbuzz start))
    (fizzbuzz-to limit (1+ start))))

4. Types

In a format string, for a general printing ~a should be used instead of ~d, which mainly is used to print integer (decimal) numbers. It can be used also for strings, but this is due to the fact that in the specification it is said that:

  if arg is not an integer, it is printed in ~A format and decimal base.

What I do not like more, however, is the fact that the function fizzbuzz sometimes returns an integer, sometimes a string. The fact that Common Lisp has dynamic typing in some way hides this fact, but I think that the program would be more elegant (and in some sense more correct) if the result has always the same type.

One way is to redefine the function in this way:

(defun fizzbuzz (n)
  (cond ((divisible n 3)
         (if (divisible n 5)
             "FizzBuzz"
             "Fizz"))
        ((divisible n 5) "Buzz")
        (t (format nil "~d" n))))

For other solutions, you could for instance look at this CR question.


Inserting using multiple contexts into LocalDB

I'm not sure i understand exactly why you have multiple contexts. If you keep to one context you can do one SaveChanges(). That should save you some time in storing data.

Do all your SaveChanges() take equal amount of time?

You could add a timer inside the contexts to print out a console message with time to confirm how long a using statement takes to come to an end.

If you are relying on how long it takes to show in the view, i suggest using a tool like Glimpse or MiniProfiler to give you feedback on time spent rendering/servertime.


You could try to group the toggleClass inside one .hover, like this:

var $top=$("#top-page");             //save #top-page in $top var

$("#bottom-page").click(function () {
    $top.addClass("push");
}).hover(function(){                 //chain .hover to #bottom-page
    $top.toggleClass("nudge-right");
    if ($top.hasClass("push")) {     //if $top has the .push class then toggle .nudge-left
        $top.toggleClass("nudge-left");
    }
});

$top.click(function () {             //on $top click remove the .push and .nudege-left class
    $top.removeClass("push nudge-left");
});

http://jsfiddle.net/73MpU/1/


REST Server for Users using Restify and Mongoose

Few points to consider:
- Extract users CRUD logic to UsersService - this service will interact with mongoose and will be responsible for create, get, update and delete operations.
- Consider using Json Web Tokens instead of passing the password for every put request - it is an alternative for using sessions.

Overall for a newbie I consider this as a very good code.


Lambda to collect properties in a child object

First, you can use Stream.flatMap() to convert a Stream of ProductInvoice to ProductEntries.

Next, you just need suitable Collector implementations to sum all the quantities per product ID, and group by that...

Putting it all together:

Map<Long, Long> result = productInvoiceRepository
                            .findByProductEntries_ProductIdIn(productIds)
                            .stream().flatMap(v -> v.getProductEntries().stream())
                            .collect(Collectors.groupingBy(ProductEntry::getProductId,
                                    Collectors.summingLong(ProductEntry::getQuantity)));

BTW, you may want to consider a better method name for findByProductEntries_ProductIdIn() to remove the underscore...


clear all;
load('results.txt');
time = results(:,3) - 1238370000;

There's no need to plot all of the points if you're going to restrict the range to the past week. So I'd suggest you find the index where the time is less than a week ago and limit your plotting to that period to reduce complexity

firstTimeIndex = find(time >= (max(time) - 86400*7), 1);

Also note that you can use 'end' instead of 'size(results,1)'

results = results(max(1,firstTimeIndex-1):end, :);
clf;
h = plot(time,smooth(results(:,1)),':b');
hold on;

Line properties like linewidth can be specified at the time of plotting

plot(time, smooth(results(:,4)), 'r', 'linewidth', 2);
plot(time, smooth(results(:,5)), 'g', 'linewidth', 2);
plot(time, smooth(results(:,6)), 'm', 'linewidth', 2);
xlabel('Time');
ylabel('Emails');
xlim([max(time)-(86400*7) max(time)-1]);
ylim([0 80]);
set(gca,'XGrid','on');
set(gca,'XTickLabel',['Mon';'Tue';'Wed';'Thu';'Fri';'Sat';'Sun']);
title('Size of inbox over time (seven days)');

I'm not sure why you are setting the resolution to 3000 dpi? Maybe you could elaborate on what you're using this for, but if your goal is high resolution and low storage size then you might like to use -dmeta for a metafile on windows, or -deps for an encapsulated postscript on unix

print -djpeg inbox7day.jpeg;

I'm not sure what you are trying to achieve with the 'XTick' property, but the vector you're passing in is extremely large (~100 million elements) which is why the code is running so slow. I'm guessing that you don't want 100 million ticks?


Methods to search for a client in MySQL by ID or by phone

Nothing wrong with Cliente ObtenerCliente accepting the query text.

Suffers from non-deterministic.  You are only going to get the first but without an order by then SQL will just pick one for you.

using is a better approach in my opinion

For sure I don't like

  Static method that opens a connection

Create the connection and let it be properly disposed

private static Cliente ObtenerCliente(string query)
{
    using (Connection mySqlConexion = new Connection(conString))
    {
        try
        {
            //abrirConexion(); //Static method that opens a connection
            mySqlConexion.Open();
            using (cmd = new MySqlCommand(query, mySqlConexion))
            {
                using (MySqlDataReader dataReader = cmd.ExecuteReader())
                {
                    if (dataReader.Read())
                    {
                        return new Cliente(
                        Convert.ToInt32(dataReader["id_cliente"]),
                        dataReader["nombre_cliente"].ToString());
                    }
                    else
                    {
                        //dataReader.Close();  let the using dispose
                        return null;
                    }
                }
            }
        }
        catch (MySqlException e)
        {
            MessageBox.Show(e.ToString());
            return null;
        }
        finally
        {
             //cerrarConexion(); //Static method that closes the connection
        }
    }
}


Given an index return item from opposite end of list

If the entire goal is absolute performance of the AtBash() request, I would simply reverse the letters at startup. I'm speaking outside the context of this particular program and more towards your library where I am making the assumption that the AtBash() method calls vs. startup ratio is much higher to infinite.

If that's the case and we can eat some startup time, and you really want that per-access performance on AtBash(), simply eat a tiny bit of memory to get there:

static List<string> letters = new List<string> {
    "Aleph", "Beis", "Gimmel", "Daled", "Hei", "Vav", "Zayin", "Chies", "Teis",
    "Yud", "Chof", "Lamed", "Mem", "Nun", "Samech", "Ayin", "Pei", "Tzadik",
    "Kuf", "Reish", "Shin", "Taf"
};
static List<string> lettersReversed = letters.AsEnumerable().Reverse().ToList();
static string AtBash(int index) => lettersReversed[index];

Compare the IL in the initial accessor, letters[Math.Abs((index + 1) - letters.Count)]:

IL_0000:  ldsfld      UserQuery+Program.letters
IL_0005:  ldarg.0
IL_0006:  ldc.i4.1
IL_0007:  add
IL_0008:  ldsfld      UserQuery+Program.letters
IL_000D:  callvirt    System.Collections.Generic.List<System.String>.get_Count
IL_0012:  sub
IL_0013:  call        System.Math.Abs
IL_0018:  callvirt    System.Collections.Generic.List<System.String>.get_Item
IL_001D:  ret

To the improved accessor, letters[letters.Count - (index + 1)]:

IL_0000:  ldsfld      UserQuery+Program.letters
IL_0005:  ldsfld      UserQuery+Program.letters
IL_000A:  callvirt    System.Collections.Generic.List<System.String>.get_Count
IL_000F:  ldarg.0
IL_0010:  ldc.i4.1
IL_0011:  add
IL_0012:  sub
IL_0013:  callvirt    System.Collections.Generic.List<System.String>.get_Item
IL_0018:  ret

To the fastest accessor, lettersReversed[index]:

IL_0000:  ldsfld      UserQuery+Program.lettersReversed
IL_0005:  ldarg.0
IL_0006:  callvirt    System.Collections.Generic.List<System.String>.get_Item
IL_000B:  ret

Given your very minimal amount of actual memory in the example (which I don't think is likely to increase), I think this is a perfectly reasonable approach for any high-throughput library.

Feel free to benchmark this. The more accesses per startup, the better the payoff. You should already see payoff pretty quickly because sorting an array of a few dozen items is very fast and that's all the time we're adding to get the long-term benefits here. I wouldn't be surprised if your program even with trivial levels of access already performs better with this approach.


Generally camelCase is used for both locals and functions.
Both PEP 8 and Google style guide recommend underscore lower_caps for both.
camelCase isn't wrong in python, it's just sticking with global standards in more right.

Also some names could be more descriptive.
rBot could be bottom_row.
operator_list is more verbose than opList but it's name is now exactly what it is and there is no question of the programmers intention of the variable.

Initializing the demo command is done incorrectly despite it being functional code.
It shows a lack of understanding of how variables work in python.

demoCmd = defaultdict(list)
demoCmd = {
    'A': [mapOper.mapVal, 'Hello, World'],
    'B': [mapOper.mapSum, 0, 1, 2],
    'C': [mapOper.mapAss, 3, 4, 5],
    'D': [mapOper.mapProd, [mapOper.mapSum, 1, 0], 0, 1],
    'E': 5
    }

Variables work differently in python than in C-ish languages.
There are better explanations of it that I will link to later,
but for now this will suffice:
Variables in python are essentially C-pointers that can point to any object,
which is everything in python.

demoCmd = defaultdict(list)

creates a new defaultdict(list) and assigns demoCmd to it.

demoCmd = { ... }

was intended to modify the data in the defaultdict object, demoCmd.
However it reassigns the variable demoCmd to a new dict object ({} is equivalent to dict()).
This wasn't a problem because demoCmd never needed to be a defaultdict object in the first place.
However, if it needed to be, the data could be entered using member functions or operators like so

demoCmd = defaultdict(list)
demoCmd.add('A': [1, 2, 3])
demoCmd['B'] = [4, 5, 6]

Type checking with isinstance() is preferred over type() as isinstance() will match the specified class and all of it's sub classes,
while type() will only match the exact class.
More here.

Ergo,

def evalOpList(opList, fromSheet, row):
    if type(opList) is str:  # treat arg as a value
        return opList
    elif type(opList) is int:  # treat arg as index
        return fromSheet.cell(row, opList).value
    # ...

is more flexible as,

def evalOpList(opList, fromSheet, row):
    if isinstance(opList, str):  # treat arg as a value
        return opList
    elif isinstance(opList, int):  # treat arg as index
        return fromSheet.cell(row, opList).value
    # ...

The command dictionary has the structure of {key : [func , arg1, arg2, arg3, ...]}.
Separating the arguments from the function as a tuple,

{key: (func, (arg1, arg2, arg3, ...))}

may seem more verbose but it will make extracting the pair simpler,

else:  # its another function
    func, arg_list = operator_tuple
    args = [evalOpList(arg, fromSheet, row) for arg in arg_list]
    return func(*args)

Allowing nesting of functions in the map commands creates an unnecessary complexity to the code.
Dropping that ability allows evalOplist to be split into smaller functions.

def evaluate_command(command, from_sheet, row):
    if isinstance(command, (tuple, list)):
        return evaluate_func(func, val_list, from_sheet, row)
    else:
        evaluate_value(command, from_sheet, row)

def evaluate_value(val, from_sheet, row):
    if isinstance(val, int):
        return from_sheet.cell(row, val).value
    else:
        return command

def evaluate_func(func, val_list, from_sheet, row):
    args = [evaluate_value(val, from_sheet, row) for val in val_list]
    return func(*args)

Two problems still exist:

evaluate_value is not recursing into any sequences to replace indexes, which is needed for functions like sum.
evaluate_command is unnecessarily re-interpreting items in the mapping command for each row of the sheet.
Commands could be pre-emptively interpreted into functions that take the row values and return a value.

I could walk readers through how to completely redesign the structure to pre-interpret the commands, but that seems out of codereveiw's scope.  See here and here for those solutions.


The code has a bug: Since you are appending elements, you have to make sure that the array is empty in the beginning. So the cur_row = [] command should be inside the loop.

Also, the number of ways to reach origin from origin is 1. Hence pre_row should have all elements 1 initially. This means that you can just do pre_row = [1] * (ups+1) instead of appending.

Next problem is kind of aesthetic. You are building cur_row at each step and turning pre_row into it in the end. Then it makes sense to fill cur_row before the loop as well, and that will make sure that the code also works for rights == 0.

Once we do these, there is no longer the need to append to cur_row inside the loop. We are sure that the list has the correct size so we can just assign elements.

Finally just remove the if inside the loop.

Combining these we have

def grid_move(rights, ups):
    cur_row = [1] * (ups+1)
    for r in range(1, rights+1):
        pre_row = cur_row
        cur_row[0] = 1
        for u in range(1, ups+1):
                cur_row[u] = pre_row[u] + cur_row[u-1]

    return cur_row[-1]

These should make the code more readable and efficient, and make the recurrence relation clear.


Please remove all // TODO Auto-generated method stub comments. Your methods are implemented. You don't need those comments any more.
Indentation. If you're using Eclipse, select all code and press Ctrl + Shift + I to ident your code properly. If you're using NetBeans, press Alt + Shift + F. Your try-catch inside the blogShare method is incorrectly indented.
The correct spelling is validateField
user, pass and bloglink are only set within validateField and only read directly after that method invocation. Get rid of the validateField method (which currently doesn't do any actual validation so it's a poorly named method). Use local variables within the onClick method.
int viewid  = view.getId(); is IMO not needed to set as a variable, as you only check it once, use view.getId() directly.
setOnclickListenerRegister is only called once from onCreate and this method only contains one line, so what you have done is to extract one statement to it's own method and then call that method which were only called once. This extraction is not worth it. Remove this method and put login.setOnClickListener(this); back to the onCreate method where it belongs.
I totally agree with Marco that you should use AsyncTask. If you encounter any problems with orientation changes, deal with those correctly. Don't avoid using AsyncTask just because you're afraid that it will cause problems.


Computing huge Fibonacci numbers in Java

StringBuilder sb;

    if (fromAtoB) {
        // It looks like the result is in the listB. However, as the boolean
        // fromAtoB was flipped after the last add(list1, list2), the result
        // is actually in list A.
        sb = new StringBuilder(listA.size());

        // For efficiency, we grow the digit string such that the least
        // significant digits are in the lowest array positions. That way
        // we make sure that adding a new (most significant digit) always
        // runs in amortized constant time.
        for (int i = listA.size() - 1; i >= 0; --i) {
            sb.append(listA.get(i));
        }
    } else {
        // Result is in listB.
        sb = new StringBuilder(listB.size());

        for (int i = listB.size() - 1; i >= 0; --i) {
            sb.append(listB.get(i));
        }
    }

    return sb.toString();

Lots of fancy comments. Let's take em out so I can look at the actual code.

    StringBuilder sb;

    if (fromAtoB) {
        sb = new StringBuilder(listA.size());

        for (int i = listA.size() - 1; i >= 0; --i) {
            sb.append(listA.get(i));
        }
    } else {
        sb = new StringBuilder(listB.size());

        for (int i = listB.size() - 1; i >= 0; --i) {
            sb.append(listB.get(i));
        }
    }

    return sb.toString();

Seems all you do here is getting a string... from either listA or listB. I'd recommend putting this in a separate function...

public static String convertDigitListToString(List<Character> list){
    StringBuilder sb = new StringBuilder(list.size());

    for (int i = list.size() - 1; i >= 0; --i) {
        sb.append(list.get(i));
    }
    return sb.toString();
}

And then you can simplify your code a bit.

if (fromAtoB) {
    return convertDigitListToString(listA);
} else {
    return convertDigitListToString(listB);
}

Maybe even a ternary? I dunno about that, though. It's shorter, but a bit more harder to read.

return convertDigitListToString(fromAtoB ? listA : listB);

The real reason it's hard to read is because fromAtoB is a pretty bad description... in this case, you're looking for something like lastListUsed... but that doesn't really fit the description either.

    if (n < 0) {
        throw new IllegalArgumentException("n = " + n);
    }

You might want to give a more descriptive message, like "n must be positive", or "expected positive n, got ".


Longest sequence of same subsequent number in a square matrix

Let me start out by saying that your solution certainly is efficient enough. You only loop over the grid once to do the 4 checks. And don't check the same sequence twice. (like going left to right AND right to left).

Since this is codereview.stackexchange let's instead start by reviewing the code :)

First of all, there is a mistake in your solution. Diagonally is not the same as on the main diagonals. The simplest example that you won't find in your solution but what I believe does count as a normal diagonal sequence is the following:

  O X O
  O O X
  O O O

This looks like a sequence of lenght 2 to me.

I dissagree with you when you say:

  I chose to use numbers for now since they easier to work with.

We can just as well work with char:

char[][] grid = new char[n][n];
...
if(r == 1) grid[i][j] = 'X';
if(r == 2) grid[i][j] = 'O';
...
if(grid[i][j] == 'X')

Doing this also makes it explicit that you're only checking for the X without having to arbitrarily choose if the 'X' is represented by a 1 or a 2 in your grid.

You have put all the code inside the main method. Although it kinda works for this small problem, it's generally a better idea to split your code up into more manageable blocks.

A few easy ones to separate are a grid generator, and a method to print a grid. By splitting this up into 2 functions we can also provide a fixed grid and still print that grid as well.

Printing is easy. We take the same loops as you already have with the same System.out... calls. But without the random setting of the cell.

public static void printGrid(char[][] grid){
    for(int row = 0; row < grid.length; row++){
        for(int col = 0; col < grid[0].length; col++){
            System.out.print(grid[row][col]+" ");
        }
        System.out.println();
    }
}

Notice how I named the loop variables row and col to make it clear what we're looping over.

Randomly generating a grid isn't much harder. We use the same loops, but now we randomly choose one of 3 characters. I'm using _ to represent "emtpy".

public static char[][] generateRandomGrid(int size){
    char[][] grid = new char[size][size];
    for(int row = 0; row < grid.length; row++){
        for(int col = 0; col < grid[0].length; col++){
            // three nums are produced. there is 1/3 chance for each.
            int r = (int)(Math.random()*3);

            // both 'X' and 'O' have 1/3 chance to be produced.
            if(r == 0) {
                grid[row][col] = '_';
            }
            if(r == 1) {
                grid[row][col] = 'X';
            }
            if(r == 2) {
                grid[row][col] = 'O';
            }
        }
    }
    return grid;
}

Now for the actual checking of the sequences. This part of your code confused me. You have the outer loop with index i. Then depending on what you check the meaning of this i changes to the row/the column/something you ignore entirely.

Instead let's provide 4 specific methods, that each calculate the maximum sequence in a specific direction for a given grid.

The horizontal one is easy. It's basically what you already did:

public static int findMaxHorizontalSequence(char[][] grid){
    int max = 0;
    for(int row = 0; row < grid.length; row ++) {
        int currentSeq = 0;
        for(int col = 0; col < grid[0].length; col ++){
            if(grid[row][col] == 'X'){
                currentSeq ++;
                if(currentSeq > max){
                    max = currentSeq;
                }
            } else {
                currentSeq = 0;
            }
        }
    }
    return max;
}

The vertical check is almost the same, except the for loops are swapped.

public static int findMaxVerticalSequence(char[][] grid){
    int max = 0;
    for(int col = 0; col < grid[0].length; col++){
        int currentSeq = 0;
        for(int row = 0; row < grid.length; row ++){
            if(grid[row][col] == 'X'){
                currentSeq ++;
                if(currentSeq > max){
                    max = currentSeq;
                }
            } else {
                currentSeq = 0;
            }
        }
    }
    return max;
}

You might have noticed by now that I always use grid.length and grid[0].length. This is so that the functions will all work correctly even if the grid was a rectangular shape instead of a square.

For the diagonals we'll have to do a bit more work. The easiest is probably to split it up in 2 loops. One for each of the following lines of starting locations:

X X X ?        O O O O
O O O O        X O O O
O O O O        X O O O
O O O O        ? O O O

We can ignore the spots with a ?. Those diagonals are only 1 char long, so it will already be counted by the horizontal/vertical checks. No need to repeat this.

The code could look like this:

public static int findMaxDownRightSequence(char[][] grid) {
    int max = 0;
    for (int startRow = 0; startRow < grid.length - 1; startRow++) {
        int currentSeq = 0;
        for (int row = startRow, col = 0; row < grid.length && col < grid[0].length; row++, col++) {
            if (grid[row][col] == 'X') {
                currentSeq++;
                if (currentSeq > max) {
                    max = currentSeq;
                }
            } else {
                currentSeq = 0;
            }
        }
    }
    for (int startCol = 1; startCol < grid[0].length - 1; startCol++) {
        int currentSeq = 0;
        for (int row = 0, col = startCol; row < grid.length && col < grid[0].length; row++, col++) {
            if (grid[row][col] == 'X') {
                currentSeq++;
                if (currentSeq > max) {
                    max = currentSeq;
                }
            } else {
                currentSeq = 0;
            }
        }
    }
    return max;
}

But at this point I really start noticing that I'm copy-pasting a lot. This usually means that we should refactor some common code. The common part of the code that we're copy-pasting is the part inside the inner for loop:

if (grid[row][col] == 'X') {
    currentSeq++;
    if (currentSeq > max) {
        max = currentSeq;
    }
} else {
    currentSeq = 0;
}

We have to find how to make the for loop work for all cases.
This means: for( find initial values for row and col ; check if they are still within the bounds of the grid ; and find how they change each step. )

Let's write a method that gets all those parameters and figure out how to map the existing ones to this method. And let's also write a specific method to check if the row and col are within the bounds of the grid, because otherwise the for statement will become unreadable.

public static int maxSequence(char[][] grid, int startRow, int startCol,
                              int verticalDir, int horizontalDir){
    int currentSeq = 0;
    int max = 0;
    for(int row = startRow, col = startCol;
                checkBounds(grid, row, col);
                row += verticalDir, col += horizontalDir) {
        if (grid[row][col] == 'X') {
            currentSeq++;
            if (currentSeq > max) {
                max = currentSeq;
            }
        } else {
            currentSeq = 0;
        }
    }
    return max;
}

private static boolean checkBounds(char[][] grid, int row, int col) {
    return row > 0 && col > 0 && row < grid.length && col < grid[0].length;
}

Now we can rewrite our other methods. The outer for loops stay the same, but we replace the inner loops with a call to our new method:

public static int findMaxHorizontalSequence(char[][] grid) {
    int max = 0;
    for (int row = 0; row < grid.length; row++) {
        int rowMax = maxSequence(grid, row, 0, 0, 1);
        if(rowMax > max){
            max = rowMax;
        }
    }
    return max;
}

public static int findMaxVerticalSequence(char[][] grid) {
    int max = 0;
    for (int col = 0; col < grid[0].length; col++) {
        int colMax = maxSequence(grid, 0, col, 1, 0);
        if(colMax > max){
            max = colMax;
        }
    }
    return max;
}

public static int findMaxDownRightSequence(char[][] grid) {
    int max = 0;
    for (int startRow = 0; startRow < grid.length - 1; startRow++) {
        int diagMax = maxSequence(grid, startRow, 0, 1, 1);
        if(diagMax > max){
            max = diagMax;
        }
    }
    for (int startCol = 1; startCol < grid[0].length - 1; startCol++) {
        int currentSeq = maxSequence(grid, 0, startCol, 1, 1);
        if (currentSeq > max) {
            max = currentSeq;
        }
    }
    return max;
}

All that's left is to write a method for the other diagonal.

    public static int findMaxDownLeftSequence(char[][] grid) {
    int max = 0;
    for (int startRow = 0; startRow < grid.length-1; startRow++) {
        int diagMax = maxSequence(grid, startRow, grid.length, 1, -1);
        if(diagMax > max){
            max = diagMax;
        }
    }
    for (int startCol = 1; startCol < grid[0].length; startCol++) {
        int currentSeq = maxSequence(grid, ?, ?, ?, ?);
        if (currentSeq > max) {
            max = currentSeq;
        }
    }
    return max;
}

Since this site requires working code in the first place to review I didn't want to give you the full solution for the diagonals. So try to fill in the four ? in the last part to see if you fully understood the solution :)

To run the new code (and find out if you filled in the last part correctly) you can use the following main method:

public static void main(String[] args) throws Exception {
    char[][] grid = new char[][]{{'O', 'X', 'O'},
            {'X', 'O', 'O'},
            {'O', 'O', 'O'}};
    printGrid(grid);
    System.out.println(findMaxSequence(grid));
}

or you can replace the grid with

char[][] grid = generateRandomGrid(100);

To test it out on a random grid.

Fun fact: on my PC it takes between 3.5 and 4 seconds to find the solution of a randomly generated 10000 x 10000 grid. About the same time it takes to randomly generate the grid.

I doubt it can get much faster on a single thread solution. Since you're stuck with looping over the entire grid anyway.


Ordering colors into a multidimensional list

As far as performance goes, you definitely need to understand your bottlenecks - profile the code properly and try to see what takes the most time - querying the database, converting hex to rgb or something else.

Here are few observations though:

don't do exists() and then filter() - just do filter() right away - it will return an empty queryset if no results
I am not sure if there is much sense in making a numpy.array - see if removing it would make a positive impact on performance
you don't need to keep track of indexes and then append to different lists based on an index - what if you would just collect the current results and then append to the resulting list at the end (see what I mean in the code below)
if a color starts with # you probably don't need to query the database at all

At the end, you may get something along these lines:

def orderDimentionalRGB(list_of_colors):
    results = []

    for color in list_of_colors:
        current_result = []

        if color.startswith("#"):
            current_result.append(hex_to_rgb(color))
        else:
            db_result = Color.objects.filter(color=color)
            if db_result:
                db_colors = db_result.first().color_list.replace(',', '').split()
                current_result += [hex_to_rgb(db_color) for db_color in db_colors]

        if current_result:
            results.append(current_result)

    return results


1. Make a test case

The first thing to do is to establish the existence of the performance problem, so let's knock up some test data.

def make_test_file(filename, n, t, delta):
    """
    Write `n` lines of test data to `filename`, starting at `t` (a
    datetime object) and stepping by `delta` (a timedelta object) each
    line.
    """
    with open(filename, 'w') as f:
        for _ in xrange(n):
            f.write(t.strftime('%d-%b-%Y %H:%M:%S ').upper())
            f.write('important data\n')
            t += delta

>>> from datetime import datetime, timedelta
>>> make_test_file('data.txt', 10**5, datetime.now(), timedelta(seconds=1))

And then with the OP's code in the function aggregate1(filename, dlen):

>>> import timeit
>>> timeit.timeit(lambda:aggregate1('data.txt', 16), number = 1)
5.786283016204834

So on the real file (1000 times bigger) that would take an hour and a half on my machine (or longer, if the time complexity is worse than linear). So yes, there's a real performance problem.

2. Clean up the code

Let's try a bunch of obvious minor improvements and optimizations (mostly as suggested in other answers):

Convert dlen to an integer once (not every for every line).
Write day_string[:dlen] instead of str(day_string[0:dlen]).
Write pattern.match(line) instead of re.match(pattern, line).
There's no need for key = operator.itemgetter(0) because the sort will proceed on the first element of the pair in any case.
Rename DATA as count and day_string with s (it's really a date-time string, not a day string).
Use with to ensure that the file is closed in the event of an error.
Import the name strptime so it doesn't have to be looked up for every line.

Let's try that:

def aggregate2(filename, dlen):
    strptime = datetime.datetime.strptime
    dlen = int(dlen)
    pattern = re.compile(r'^\d{2}-[A-Z]{3}-\d{4} \d{2}:\d{2}:\d{2} important data')
    count = defaultdict(int)
    with open(filename, 'r') as f:
        for line in f:
            if pattern.match(line):
                d = strptime(line[:20], '%d-%b-%Y %H:%M:%S')
                s = d.strftime('%Y-%m-%d %H:%M:%S')
                count[s[:dlen]] += 1
    return sorted(count.iteritems())

>>> timeit.timeit(lambda:aggregate2('data.txt', 10), number = 1)
5.200263977050781

A small improvement, 10% or so, but clean code makes the next step easier.

3. Profile

>>> import cProfile
>>> cProfile.run("aggregate2('data.txt', 10)")
         2700009 function calls in 6.262 seconds

   Ordered by: standard name
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    6.262    6.262 <string>:1(<module>)
   100000    0.088    0.000    1.020    0.000 _strptime.py:27(_getlang)
   100000    2.098    0.000    4.033    0.000 _strptime.py:295(_strptime)
   100000    0.393    0.000    0.642    0.000 locale.py:339(normalize)
   100000    0.105    0.000    0.747    0.000 locale.py:407(_parse_localename)
   100000    0.119    0.000    0.933    0.000 locale.py:506(getlocale)
   100000    0.067    0.000    0.067    0.000 {_locale.setlocale}
   100000    0.515    0.000    4.548    0.000 {built-in method strptime}
   100000    0.079    0.000    0.079    0.000 {isinstance}
   200000    0.035    0.000    0.035    0.000 {len}
   100000    0.043    0.000    0.043    0.000 {method 'end' of '_sre.SRE_Match' objects}
   300001    0.076    0.000    0.076    0.000 {method 'get' of 'dict' objects}
   100000    0.276    0.000    0.276    0.000 {method 'groupdict' of '_sre.SRE_Match' objects}
   100000    0.090    0.000    0.090    0.000 {method 'index' of 'list' objects}
   100000    0.025    0.000    0.025    0.000 {method 'iterkeys' of 'dict' objects}
   100000    0.046    0.000    0.046    0.000 {method 'lower' of 'str' objects}
   200000    0.553    0.000    0.553    0.000 {method 'match' of '_sre.SRE_Pattern' objects}
   100000    1.144    0.000    1.144    0.000 {method 'strftime' of 'datetime.date' objects}

I've cut some of the output for clarity. It should be clear that the culprits are strptime (73% of runtime), strftime (18%), and match (9%). Everything else is either called by one of those, or negligible.

4. Pluck the low-hanging fruit

We can avoid calling both strptime and strftime if we recognize that the only things we are achieving by calling these two functions are (a) to translate the months from names (AUG) to numbers (08), and (b) to reorder the components into ISO standard order. So let's do that ourselves:

def aggregate3(filename, dlen):
    dlen = int(dlen)
    months = dict(JAN = '01', FEB = '02', MAR = '03', APR = '04',
                  MAY = '05', JUN = '06', JUL = '07', AUG = '08',
                  SEP = '09', OCT = '10', NOV = '11', DEC = '12')
    pattern = re.compile(r'^(\d{2})-([A-Z]{3})-(\d{4}) (\d{2}:\d{2}:\d{2}) '
                         'important data')
    count = defaultdict(int)
    with open(filename, 'r') as f:
        for line in f:
            m = pattern.match(line)
            if m:
                s = '{3}-{0}-{1} {4}'.format(months[m.group(2)], *m.groups())
                count[s[:dlen]] += 1
    return sorted(count.iteritems())

>>> timeit.timeit(lambda:aggregate3('data.txt', 10), number = 1)
0.5073871612548828

There you go: a 90% speedup! That should get you down from three hours to 20 minutes or so. There are a few more things one might try (for example, doing the aggregations for all the different values of dlen in a single pass). But I think this is enough to be going on with.


Pass service to view model or leave thin controller as is

I would suggest having a separate class for doing this processing and mapping.
It will be a service or mapper class takes your Service object in the constructor and has a method which return WelcomeAnalyzeViewModel object.

Also you can do it all through the method, by passing your Service object to this method and return the WelcomeAnalyzeViewModel, this will make your controller very thin something like that:

public PartialViewResult Analyze()
{
        var viewModel = Mapper.GetWelcomeAnalyzeViewModel(Service);
        return PartialView("Analyze", viewModel);
}

public class Mapper
{
  public WelcomeAnalyzeViewModel(ServiceType service)
  {
      return new WelcomeAnalyzeViewModel
        {
            IsDrugsPanelVisible = !Service.IsMDStandalone(),
            IsDevicesPanelVisible = Service.IsSubscribedToMedTech(),
            IsCompaniesPanelVisible = !Service.IsCTStandalone(),
            IsCountriesPanelVisible = !Service.IsCTStandalone() || (Service.IsCTStandalone() && Service.HasImsAddOn()),
            IsFinancePanelVisible = !Service.IsCTStandalone()
        };
  }
}

And i will put this mapper class in the ViewModels project if you have a separate project for them.


Evaluate mathematical expression in reverse Polish notation in C

Early returns are OK.

if (args < 4) {
    printf(....);
    return;
}
....

emphasizes where the business logic is.
The condition (c = **++argv) != '\n' looks sort of strange. It is indeed possible to embed a newline in an argument, but it doesn't warrant a special case. It is just one way to malform an argument, and there are plenty of them.
c = d; does nothing. The very first statement after goto DOWN1 overrides c.
Avoid gotos. I don't see the compelling reason to have them here. Just move the code under DOWN1 label to where it belongs, and see the gotos disappearing. Better yet, factor it out into a function.
There is no reason to copy the rest of the argument into s. You may directly pass it to atof. I understand the desire to sanitize the argument, but the way you do it is incorrect. It allows multiple dots, and misinterprets some well-formed floats (those with exponents, like 1e2). Let atof do its job correctly. Better yet, use strtod, and check where it stopped parsing.
Avoid globals. The bullet above eliminates s. To eliminate global sign, don't cramp everything to calc. Just compute the number, and push it. Let calc only deal with operators.
All error messages should go to stderr.


Simplifying parsing command-line arguments

Your function should have args=None as default. This way you can use it to parse the command-line arguments as well as pass in a list of arguments to parse.

For your mutual exclusive options you should use...mutual exclusive groups. However, this only works properly for your mode, because adding a group of not mutually exclusive options (your --id-begin and --id-end) to a mutually exclusive group seems to no be supported at the moment, even though there was some activity on that a few years back: http://bugs.python.org/issue10984

# modes
action = parser.add_mutually_exclusive_group(required=True)
action.add_argument(
    '--validate', help='Enables "validate only" mode', action='store_true')
action.add_argument(
    '--apply', help='Enables "apply" mode', action='store_true')

With the above code, you can remove all checking you currently do on the modes. It requires that exactly one of the modes is activated.

Also note that the default behavior of action='store_true' is to have default=False, so you can just do:

parser.add_argument('--verbose', help='Enables "verbose" reporting mode',
                    action='store_true')


Instantiate multiple classes in another class, invoke method from multiple classes

Recording Subclasses
As of Python 3.6, there is an easy way to gather all your subclasses together, without having to risk the error-prone method of manually creating an AllAlerts subclass and listing all of the subclasses in it.  The key is object.__init_subclass__(cls).  It is called when a subclass is defined.
class BaseSource:
    subclasses = []

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        cls.subclasses.append(cls)
        print("Registered", cls)

Now, whenever a subclass of BaseSource is defined, that subclass will be added to the BaseSource.subclass list.
Of course, AllAlerts did more than this.  It created one instance of each source subclass and passed the same arguments in the constructor of each.  We'll have to do that in a @classmethod of the base class.  It also used itertools to chain together all of the alerts from each of those source instances, so we'll have to record those source instances, and provide a @classmethod for getting that chain of alerts.
from itertools import chain

class BaseSource:
    subclasses = []

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        cls.subclasses.append(cls)
        print("Registered", cls)

    @classmethod
    def init_all(cls, db, args):
        """
        Create one instance for each subclass, constructed using the given
        'db' and 'args' values.
        """
        cls.sources = (subclass(db, args) for subclass in cls.subclasses)

    @classmethod
    def all_alerts(cls):
        """
        Return an iterable of all alerts from all subclass sources
        """
        return chain.from_iterable(src.alerts() for src in cls.sources)

    def __init__(self, db, args):
        self.db = db
        self.args = args

    def alerts(self):
        """
        Return an iterable of alerts for this class
        """
        raise NotImplementedError()

With this base class, you just need to define the source subclasses, as many as you like.  There is no need to remember all of the classes; the base class does that for you:
class NagiosSource(BaseSource):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        print("Constructed Nagios Source")

    def alerts(self):
        yield "Alert 1"
        yield "Alert 2"

class ZabbixSource(BaseSource):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        print("Constructed Zabbix Source")

    def alerts(self):
        yield "Alert A"
        yield "Alert B"

After all of the subclass definitions have been read in, you will have to initialize them with the appropriate db and args, like you created an AllAlerts instance, which created all of the source objects.  And then you can request all alerts from the base class:
BaseSource.init_all("mydb", (1, 2, 3))

print(list(BaseSource.all_alerts()))

Output of above:
Registered <class '__main__.NagiosSource'>
Registered <class '__main__.ZabbixSource'>
Constructed Nagios Source
Constructed Zabbix Source
['Alert 1', 'Alert 2', 'Alert A', 'Alert B']
>>>

Raise objects, not classes
Your BaseSource had the method:
    def alerts(self):
        raise NotImplementedError

This appears to be raise a class instead of an instance of a class.  You should write:
    def alerts(self):
        raise NotImplementedError()

Using instances allows you to have arguments, which helps describe the error.  What does "Not Implemented" mean?  Does it mean "Not Implemented Yet", as in a later version of the library is expected to provide an implementation?  No!  We need subclasses to provide the implementation.
    def alerts(self):
        raise NotImplementedError("This method must be overridden in derived classes")

Public methods need docstrings
You provide docstrings for _data() and _raw_data(), but not for alerts().  This is backwards.
The leading underscore represents private methods.  An external caller does not need to know how to call them, because they are private.
On the other hand, public functions (without the leading underscore) are expected to be called by external callers.  And someone writing the code which uses these Source objects may want to know how to call the methods.  So they may type:
>>> help(NagiosSource)

and would reasonable expect to get information about how to use the class and its public method.  The docstring for _data and _raw_data would not be provided, because of the leading underscore.
You may provide docstrings for private methods (the expectation is the public methods would all have been documented first), but code comments may be just as useful.


Your code is perfectly fine, except for a few nitpicks.

Use push instead of (setf x (conx y x)) for readability.

Use floor instead of rem + / for efficiency.

1st and 3rd loops are identical, so they should be abstracted into a local flet function.

Use nreverse instead of reverse for the return value.  Yes, you can avoid that by using collect combined with nconc but it makes little sense in your specific case.


Test a single-line file for punctuation and newline

\| is not a proper escape sequence.  To include the backslash in the string, it should be escaped using two backslashes, or you should use a “raw” string for the regular expression, so backslashes do not need to be escaped.

for x in range(0, len(context) - 1): does not check the last character of the string, since range(start, end) already does not include end.

if (context[x].isspace())==True: does not need the parentheses around context[x].isspace(), nor does it need the == True.

You can use enumerate() to loop over the contents of an iterable and get the index at the same time.  Also, a for ... else block can be used to detect if nothing was found.  With Python 3.6 or later, f-strings can be used to embed variables directly in strings.

for idx, ch in enumerate(context):
    if ch.isspace():
        print(f"spaces found in the file at {idx}")
        break
else:
    print("no space found")

It is strange to find a quotation mark, and declare that a new line has been found.  Are you sure you’ve got your logic correct?

PEP8 Guidelines:

spaces around all operators, like =, ==, -
use a space after each comma in argument lists
blank line after imports
longer, descriptive variable names (x is too short and not descriptive)


I won't repeat @victor's answer, but Python is a language that comes with batteries included; meaning that a lot of behaviour has already been bundled into modules, and is maintained for correctness and performance. You should really avoid to reinvent the wheel if it is not for learning purposes.

Python also comes with an official style guide: PEP8, which is advised to follow if you want your code to look like Python code to others.

Your code also rely heavily on variables defined globally. This kind of code is error prone and less reusable. Instead, define arguments for your functions and pass information as parameters.

Lastly, you should avoid keeping code at the top-level of the file, protect it with an if __name__ == '__main__' guard:

import os
import json

def delete_files(files):
    for filename in files:
        os.remove(filename)

def create_file(filename, data, created_files):
    try:
        os.makedirs(os.path.dirname(filename), exist_ok=True)
        with open(filename, "w+") as new_file:
            json.dump(data, new_file, indent=4)
    except:
        print("\nSomething went wrong")
        print("Deleting:", *created_files)
        print("\n")
        delete_files(created_files)
        raise
    else:
        filepath = os.path.relpath(new_file.name)
        created_files.append(filepath)
        print("Created", filepath)

def block_states(modid, block_name):
    return {
        'variants': {
            'normal': {
                'model': f'{modid}:{block_name}',
            },
        },
    }

def models_item(modid, block_name):
    return {
        'parent': f'{modid}:block/{block_name}',
        'textures': {
            'layer0': f'{modid}:items/{block_name}',
        },
    }

def models_block(modid, block_name):
    return {
        'parent': 'block/cube_all',
        'textures': {
            'all': f'{modid}:blocks/{block_name}',
        },
    }

def main(modid, block_name):
    created_files = []
    create_file(
            f'blockstates/{block_name}.json',
            block_states(modid, block_name),
            created_files)
    create_file(
            f'models/item/{block_name}.json',
            models_item(modid, block_name),
            created_files)
    create_file(
            f'models/block/{block_name}.json',
            models_block(modid, block_name),
            created_files)

if __name__ == '__main__':
    block_name = input("block name: ")
    modid = input("modid: ")
    main(modid, block_name)


Memoized implementation of change-making algorithm

I'd say the main issue with your code is that you're confusing what the inner function is supposed to do:

def inner(W, sol):
    if W == 0:
        return sol   ## return result so far?

    if W in d:
        return d[W]  ## return best result for W?

Those are two different kinds of values. If you're just returning "smallest tuple for weight W", then W == 0 should yield tuple(). And your recursive step should just be:

tmp.append(inner(w) + (coin,))

With that, I would rename tmp. It's not really a temporary variable, we're actually building up our next possible step. So really something like:

next_iteration = (inner(W - coin) + (coin,)
                  for coin in denoms
                  if coin <= W)

And for your key argument to min, you need a function taking one argument and returning a value. You had:

key = lambda x: len(x)

But lambda x: len(x) is the same as len. So I'd reduce the whole thing to:

d = {0: tuple()} # to avoid the special case of 0
def inner(W):
    if W in d:
        return d[W]

    next_iteration = (inner(W - coin) + (coin,)
                      for coin in denoms
                      if coin <= W)
    d[W] = min(next_iteration, key=len)
    return d[W]

return inner(W)

For memoize, sure, with one minor modification:

def memoize(f):
    cache = {}                 # why d?
    def inner(*args):          # <== *args, not args
        if args not in cache:
            cache[args] = f(*args)
        return cache[args]
    return inner

And then just:

@memoize
def inner(W):
    if W == 0:
        return tuple()

    next_iteration = (inner(W - coin) + (coin,)
                      for coin in denoms
                      if coin <= W)
    return min(next_iteration, key = len)

return inner(W)

That does seem nicer. I like it.


Multiple audio player - arrow keys & space

Determining the key pressed
The code contains this line:

switch ( event.keyCode ) {

Looking at the MDN documentation for keyCode we see:

Deprecated
This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

There is the related StackOverflow post .keyCode vs. .which from 2010 and the accepted answer has been updated with recent information about using code though browser support isn't complete so you should consider which browsers your users might use (e.g. IE?)
The VueJS documentation for Event handling even has a section about Key Codes.

The use of keyCode events is deprecated and may not be supported in new browsers.

Using keyCode attributes is also permitted:
<input v-on:keyup.13="submit">

Vue provides aliases for the most commonly used key codes when necessary for legacy browser support:

.enter
.tab
.delete (captures both “Delete” and “Backspace” keys)
.esc
.space
.up
.down
.left
.right

Those could be used in the template instead of the script section.
<player @keyup.space="pause" @keyup.right="audio.currentTime -= 2" ...>

Perhaps a method could be created to add (or subtract time) for the left and right arrow keys - e.g.:
methods: {
    addTime: function(delta) {
        audio.currentTime += delta
    }

Then that method can be used in the template:
<player @keyup.space="pause" @keyup.left="addTime(-2)" @keyup.right="addTime(2)">

Multiple handlers
If there is a need to have multiple players and a single event handler then an Event bus might be an ideal solution. There are multiple guides for creating an Event Bus (e.g. on digitalocean.com, medium.com, vuejsdevelopers.com) but I don't see one in the vueJS documentation.


I have embedded my comments straight in the code:

import java.util.Objects;

// 'Implementation' does not provide any more information on this class.
// Remove it, so less typing.
//public class DequeImplementation<T> {
public class Deque<T> {

    private QueueNode<T> first;
    private QueueNode<T> last;
    private int size;

    // You can add 'final' if you WANT:
    private static final class QueueNode<T> {

        private T val;
        private QueueNode<T> next;
        private QueueNode<T> prev;

        // You don't really need 'public' since the class is the inner private
        // static class:
        /*public*/ QueueNode(T val) {
            this.val = val;
            // Reference fields are 'null' by default:
            //this.next = null;
            //this.prev = null;
        }

        // Remove 'public' as well:
        /*public*/ T getValue() {
            return val;
        }

        /*public*/ void setNext(QueueNode<T> nextNode) {
            next = nextNode;
        }

        /*public*/ QueueNode<T> getNext() {
            return next;
        }

        /*public*/ void setPrev(QueueNode<T> prevNode) {
            prev = prevNode;
        }

        /*public*/ QueueNode<T> getPrev() {
            return prev;
        }

        // Here we need 'public'.
        public String toString() {
            // if (val == null) {
            //    return "null";
            //}
            //return val.toString();
            // Does exactly the same as above 3 lines:
            return Objects.toString(val);
        }
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public void offerLast(T val) {
        QueueNode<T> cur = new QueueNode(val);
        if (size == 0) {
            first = last = cur;
            size = 1;
            return;
        }

        last.setNext(cur);
        cur.setPrev(last);
        last = cur;
        size++;
    }

    public void offerFirst(T val) {
        QueueNode<T> cur = new QueueNode(val);
        if (size == 0) {
            first = last = cur;
            size = 1;
            return;
        }

        cur.setNext(first);
        first.setPrev(cur);
        first = cur;
        size++;
    }

    public T peekLast() {
        if (isEmpty()) {
            return null;
        }
        return last.getValue();
    }

    public T peekFirst() {
        if (isEmpty()) {
            return null;
        }
        return first.getValue();
    }

    // No reason to return a node since everything the user can do with it is
    // to ask its value; return the value:
    // public QueueNode<T> pollFirst() {
    public T pollFirst() {
        if (isEmpty()) {
            return null;
        }

        QueueNode<T> cur = first;
        first = first.getNext();
        if (first != null) {
            first.setPrev(null);
        }
        size--;
        return cur.getValue();
    }

    // Same argument as in 'pollFirst':
    public T pollLast() {
        if (isEmpty()) {
            return null;
        }

        QueueNode<T> cur = last;
        last = last.getPrev();
        if (last != null) {
            last.setNext(null);
        }
        size--;
        return cur.getValue();
    }

    public void clear() {
        size = 0;
        first = null;
        last = null;
    }

    // This is a matter of taste, yet I don't quite like your idea to prepend
    // and append the output with 'null'. Think what the user sees if he really
    // has null values in the deque..a
    @Override
    public String toString() {
        if (size == 0) {
            return "[]";
        }

        StringBuilder sb = new StringBuilder("[");
        sb.append(first.getValue());
        QueueNode<T> node = first.getNext();

        while (node != null) {
            sb.append(" -> ").append(node.getValue());
            node = node.getNext();
        }

        return sb.append("]").toString();
    }

    public static void main(String[] args) {
        Deque<Integer> dq = new Deque<>();
        System.out.println(dq.size());
        System.out.println(dq.pollLast()); //returns null
        System.out.println(dq);
        dq.offerLast(100);
        dq.offerFirst(10);
        dq.offerFirst(1);
        System.out.println(dq.pollFirst());
        System.out.println(dq);
        System.out.println(dq.size());
        System.out.println(dq.peekLast());
        System.out.println(dq.pollLast());
        System.out.println(dq);
        System.out.println(dq.size());
        System.out.println(dq.pollFirst());
        System.out.println(dq.pollLast()); //returns null
        dq.clear();
        System.out.println(dq.size());
    }
}

Hope that helps.


I think that Heslacher is right and you don't strictly need this class, but as you've written it I'd like to point out a couple of things:

Many people, myself included, don't like to use regions. They just add noise - especially on such a small class
SetAttributeIfExists is one step too far IMO. The method name isn't accurate either, you're setting the value if it exists or not.
The exception message is really odd if you specify a property without the attribute:

[TestMethod]
public void AttributeFound_WhenCalledAfterCheckAttributeAndPropertyDoesntHaveAtrribute_ReturnsNull()
{
    // ARRANGE
    Type testType = typeof(TestObject);
    PropertyInfo property = testType.GetProperty("Name1");

    // ACT
    NameAttribute actual = new PropertyNameAttributeFinder(property)
        .CheckForAttribute()
        .AttributeFound;

    // ASSERT
    Assert.IsNull(actual);
}

I would get an exception saying this:

  No attribute type was found so cannot be returned. Hint: Use HasFoundAttribute first.

That's not a good hint - I've already called HasFoundAttribute. The message could also be more specific as you didn't find a NameAttribute not any old attribute type. The point is you've extended 1 line of code to an entire class for no benefit.


I'd do this:

#!/bin/bash

backuppath=/var/mysql_backup
mkdir -p "$backuppath"

shopt -s nullglob

# Remove old compressed archive
backups=( "$backuppath"/*.gz )
if [[ ${#backups[@]} -gt 0 ]]; then
    stat -c "%Y %n" "${backups[@]}" |
      sort -rn |
      sed -e '1,7d' -e 's/^[0-9]\+ //' |
      xargs -r rm
fi

# Compress all the logs
logs=( "$backuppath"/*.sql )
if [[ ${#logs[@]} -gt 0 ]]; then
    gzip "${logs[@]}"
fi

/usr/bin/mysqldump -u db_user -p'password' --single-transaction --all-databases \
    > "$backuppath/"$(date "+%Y.%m.%d-%H.%M.%S")_dump.sql

Notes:

don't use ALLCAPSVARS -- leave those for the shell. I've seen people accidentally do PATH=... and then wonder why their script is broken.
don't parse ls -- I'm using arrays to hold the results of the glob expansion, and checking how many elements are in the array.
always quote variables, except when you know exactly why not. See https://unix.stackexchange.com/q/171346/4667
I'm assuming you want to compress any log.sql file, not just the first found
I'm assuming you want to keep 7 compressed logs and remove any older ones.
I'm assuming you have the GNU coreutils (xargs -r, those stat options)


I'm sorry, this is not an answer to your question, but it is a partial review of your code.

It seems you've got a serious problem with choosing your names. They don't actually tell me what the purpose of the methods is, or the content of the variables.

Your method getDocument() can do two things: Return the path or the folder of the document. The name doesn't tell me that. It should be something like getDocumentPathOrFolder(). The argument $documentName doesn't contain a document name. It's a boolean. The only way to find out, what really is contained in this argument, is to read the code in the method. It seems to decide whether a path or folder should be returned. A better name would have been $addNameToFolder. Still not ideal.

To make matters worse you have a method called getPath() which, you've guessed it, doesn't return a path. By now I no idea what is actually returned by this method.

If I'm allowed to completely rewrite your code, with a better structure and better names, it would look something like this:

class Document
{

    public function getDocumentName()
    {
        return $this->documentName;
    }

    public function getDocumentFolder()
    {
        return storage_path("app/{$this->stream->token}/{$this->unique_id}/");
    }

    public function getDocumentPath()
    {
        return $this->getDocumentFolder() . $this->getDocumentName();
    }

}

I assume that storage_path() is part of Laravel, and cannot be changed. The long argument to storage_path() should probably be split into its seperate parts, especially if you also use it elsewhere, but please, spent some time to choose good names.

References:

Ten tips to help you choose good names

Writing Good Method & Variable Names

The importance of naming in programming