Writing if..else construct without long condition checks to increase maintainability

Replace Temp variables with queries

It's a primary refactoring technique championed by Fowler in his book Refactoring. That as well as the second technique of extracting methods from complex/long code dramatically improves code readability. Please see below for examples:

public void Testc()
{
    // The code that you've suggested as the first option
    // makes the if statement more readable and it should be preserved
    // over the complicated code within the if statement IMO: i.e. if(userInstance != null && userInstance.Transactions > 0)
    // but it introduces the problem of temporary variables - which, when refactoring
    // should probably be replaced with a query, as Martin Fowler suggests,
    // unless you have cogent reasons to preserve them as a temporary variables
    // (i.e. for performance reasons). If that's the case, Fowler suggests
    // to still replace the temporary variable with a query, and further down the line
    // to THEN start thinking about optimisation. This might force you back to using temporary
    // variables.

    // Summary:
    // So Fowler suggests to replace the logic with a query. And Then to
    // start thinking about optimisation if required
    // so it would look something like this:

    if (UserInstanceHasTransactions())
    {
        //Processing logic here
    }
    else
    {
        //Some other processing here
    }
}

public bool UserInstanceHasTransactions()
{
    return userInstance != null && userInstance.Transactions > 0;
}

As Volundi points out sometimes the userInstance might itself be a temporary variable. if that's the case you might have to do something like this:

public bool UserInstanceHasTransactions(userInstance )
{
    return userInstance != null && userInstance.Transactions > 0;
}

And you could call it like this:

if (UserInstanceHasTransactions(userInstance))
{
    //Processing logic here
}
else
{
    //Some other processing here
}

Above all the important thing is to preserve readability, because your code will be read many more times than it is edited. If the userInstance is a temporary variable then you might want to consider refactoring all those instances as a query method and as Fowler suggests, if performance is not a problem.


Triaging items according to a time threshold

I tried linq but got lost.

LINQ stands for Language-INtegrated Query - and querying objects (or data) is not something that should have side-effects... and the very purpose of that loop is to have side-effects. In other words, using LINQ here would be abusing the language.

Your usage of var is inconsistent, and the naming is... dangerous - I like var, a lot. So I like that you're having it in your loop declaration. You see, I can guess that timeDiff is a TimeSpan just by looking at its name - and its assignment makes it pretty obvious what the type is as well. But I have no clue whatsoever what an o is, and all I know about s is that it's probably an IEnumerable<whatever-the-type-of-o-is>. Readable code is code that one can... read.

o.time and o.name are confusing, because they don't follow the typical PascalCase naming convention for public members. If they're public property getters, they should be o.Time and o.Name.

o._name is confusing at best, and a clear violation of encapsulation at worst. _name looks very much like a name for a private field - which shouldn't be accessible from this code. And if it's a public field, then you've broken encapsulation (because fields should never be public). And if _name isn't the backing field for the name property, then you have another problem: you clearly aren't writing code as if the next maintainer were a violent psychopath that knows where you live:

listA.Add(o.name);
...
listA.Add(o._name);

Another thing to note, is that the Boolean expression in an if condition doesn't need to involve a comparison against a Boolean value here:

if (f == false)

if f is a bool, then if (!f) is a Boolean expression... that would be perfectly clear if f had a meaningful name. By convention bool variable names start with is, or has:

if (!isHairyCode)

or

if (!hasBugs)


Text reading and string inputting program

I wonder if you even have tested this program:

This:

  while (!info.EndOfStream)
  {
    String tempstring = String.Empty;
    tempstring = reader.ReadLine();

    while (!reader.EndOfStream)
    {

will run forever because info is never read from and will never reach EOS.

In the context this:

   while (!info.EndOfStream)    {
     String tempstring = String.Empty;
     tempstring = reader.ReadLine();

is not understandable. Do you have the tempstring that is going to be written instead of the placeholders in the top of the structure.txt-file?

You open the same file twice:

public static void WriteToFile(string filePath)
{
  //create a string array to gather our text file information.

  StreamReader reader = new StreamReader(filePath);
  StreamReader info = new StreamReader("Structure.txt");

because the argument filePath is also "Structure.txt". Why open the same file more than once for the same operation?

StreamReader and StreamWriter implement IDisposable and should be disposed off like:

using (StreamReader reader = new StreamReader(filePath))
using (StreamWriter writer = new StreamWriter("helle.cs"))
{
   ...
}

You shouldn't hardcode string literals in a method but provide them as arguments:

public static void WriteToFile(string inputFile, string outputFile)
{
   ...
}

Instead of:

 while (!reader.EndOfStream)
 {

    temp = reader.ReadLine();

it is better to do:

string line = null;
while ((line = reader.ReadLine()) != null)
{
   ...
}

  StreamWriter writer = new StreamWriter("Hello.cs", true);

you set the append argument to true, but I'm quite sure you mean to overwrite the existing file?


Is it worth to compromise on speed to follow PEP 8 guidelines?

A reasonable question to ask, maybe not for a single instance but if you end up with extremely performance-sensitive code. Black formats the code like this:

enc = encoder.predict(
    np.array(
        [
            data[stock][4 * i : 4 * (i + 30)]
            for i in range(lens[stock] + days - 30)
        ]
    )
)


You should be able to simplify the definition of DEPS to

DEPS := $(OBJS:.o=.d)

For small projects that don't require complicated configuration schemes, it's often times easiest to get the list of source files by wildcard instead of manually maintaining an explicit list:

SRCS := $(wildcard $(SRCDIR)/*.c)
OBJS := $(patsubst $(SRCDIR)/%.c,$(OBJDIR)/%.o,$(SRCS))
DEPS := $(OBJS:.o=.d)

That way, you won't have to change the makefile when you add, delete, or rename source files.

Since all of your object files are going into the same output folder, you only need to create the output folder when it does not exist.  You are currently calling mkdir for every C file that gets compiled.  This won't break your build, but it's unnecessary overhead and doesn't scale well.  You should be able to simplify to something like this:

$(OBJDIR)/%.o: $(SRCDIR)/%.c
    #@echo " CC $<"
    $(SILENCER)$(CC) $(CFLAGS) -c -o $@ $<

$(OBJS): | $(OBJDIR)
$(OBJDIR):
    $(SILENCER)mkdir -p $(OBJDIR)

The second line of your recipe for "clean" should add the "-f" flag to avoid error messages when $(OBJDIR) doesn't exist.


Implementation of Prim's algorithm in C++

Code looks OK.

I would suggest you to do some class instead of Edge:

//typedef pair<pair<int, int>, int> Edge; //a, b, length
struct Edge{
   int a;
   int b;
   int length;
};

Also I suggest to have some predefined type for vector<Edge>

using EdgeContainer = vector<Edge>;

You have duplication near //find the shortest edge, you probably need Edge there

Here the_shortest is probably not initialized. Also you probably might use something from <algorithm> (but I will do it in same way as you).

    //find the shortest edge
    pair<pair<int, int>, int> the_shortest;
    the_shortest = edges_with_lengths.front();
    for(auto i: edges_with_lengths){
        if(the_shortest.second > i.second)
            the_shortest = i;
    }

Another probably micro optimization would be to write ++i in loops:

//for (int i = 1; i < number_of_nodes; i++)
for (int i = 1; i < number_of_nodes; ++i){
   // ...
}

Also in C++11 main() does not need to return 0;.


Project Euler #16 in Swift - Power digit sum

Let's start with a small note: The power parameter in

func powerDigitSum(x:Int, var power:Int) -> Int { ... }

need not be variable, so you can remove the var.

You use arrays to store "large integers", and the most significant digit is
stored in the first array element (at index 0). As a consequence, the arrays
are reversed in infMult() and the result is reversed again.

It would be easier to store the least significant digit at index 0 of the
arrays. This simply means that you remove all reverse() calls in
infMult() and intToIntArray().

This reduces the computation time slightly from 0.027 to 0.02 seconds on my
computer.

Another improvement would be to store more than one decimal digit in each
array element. On the OS X platform, Int is a 64-bit integer, so that
you can safely store 8 decimal digits in the array elements without
risking an overflow when multiplying two "large digits".

So you would define

let BASE = 100000000

replace all occurrences of 10 by BASE in your code, and change
powerDigitSum() to

func digitSum(var x : Int) -> Int {
    var result = 0
    while x > 0 {
        result += x % 10
        x /= 10
    }
    return result
}

func powerDigitSum(x:Int, power:Int) -> Int {
    let powerSum = infPow(x, power)
    let result = reduce(powerSum, 0) { $0 + digitSum($1) }
    return result
}

This reduces the computation time to 0.011 seconds.

The greatest performance improvement can be achieved by using a better
exponentiation algorithm in infPow(), such as Exponentiation by squaring (see also https://codereview.stackexchange.com/a/70197/35991
for a nice explanation).

In this context this would look like

func infPow(x:Int, var power:Int) -> [Int] {

    var result = [1]
    var square = intToIntArray(x)

    if power > 0 {
        if power % 2 == 1 {
            result = infMult(result, square)
        }
        power /= 2
    }
    while power > 0 {
        square = infMult(square, square)
        if power % 2 == 1 {
            result = infMult(result, square)
        }
        power /= 2
    }
    return result
}

This reduces the computation time to 0.0002 seconds.


Exporting data from PostgreSQL as CSV to S3 bucket

The code's straightforward enough at a glance, I wouldn't have worried
too much about the duplicate bits, especially since it's only double and
not multiple times for each part!  Overdoing abstraction can hurt readability too.  See below for some thoughts on how I'd approach this with that warning in mind.

First of I'd try and move some of the functionality out of the function.
The constants ... should be constants and not right in the middle of the
function body.  Plus, some of them look like constants, while some are
inline ('orders').  I can't tell why the distinction is made here,
maybe there was a reason.

Also consider making all of this not a class method, but a regular one,
then you could for example start creating helper objects beforehand
(like the s3 client) and/or pass in preconstructed ones, e.g. for
testing purposes (like with mock objects).

I'm not going to do these changes right here because you might have had
a reason for the @classmethod.

Instead, let's do a few different changes to make the flow a little bit
easier to comprehend for a reader not already familiar with the code
base:

Moving construction and usage of an object closely together will let
readers just continue reading while not having to jump up the block
again to find out where a particular name was defined ... unless
there are pressing reasons like failing early if no connection could
be made (c.f. the s3 client, though I'm guessing it doesn't actually
establish a connection until the upload_fileobj call is made).
Breaking out functionality into more functions (or even local helper
functions, no one's stoppiing you from creating more abstractions.
Alternatively, and I think that's better suited for this case, create
a new class to wrap things together that belong together.  The hint
for me here is event_data_... appearing with two suffixes and then
order_data_... with the same suffixes.  That begs to be an object
with two attributes.

E.g. like this:

BUCKET_NAME = 'fbprophet'
EVENT_DATA_OBJECT = 'event_data_test.csv'
ORDER_DATA_OBJECT = 'orders_order_test.csv'

class ForecastBuffer:
    def __init__(self, columns):
        # Prepare buffer for csv files
        self.buffer = io.StringIO()
        self.writer = csv.writer(self.buffer)
        self.writer.writerow(columns)

    def write_row(self, row):
        self.writer.writerow(row)

    def upload(self, s3, bucket_name, object_name):
        # Prepare buffer and transform to binary
        to_binary = io.BytesIO(self.buffer.getvalue().encode('utf-8'))
        s3.upload_fileobj(to_binary, bucket_name, object_name)

class Forecast:
    @classmethod
    def export_data_for_forecast(cls):
        event_data = ForecastBuffer(["Event PK", "Name", "Start date"])
        order_data = ForecastBuffer(["Event PK", "Created", "Total Gross"])

        events = Event.objects.filter(status=EventStatus.LIVE).prefetch_related(
            'orders'
        )

        for event in filter(lambda event: not event.is_over, events):
            event_data.write_row([event.pk, event.name, event.start_date])

            for order in event.orders.all():
                order_data.write_row(
                    [order.event.pk, order.created, order.total_gross]
                )

        # Upload to S3
        s3 = boto3.client(
            's3',
            aws_access_key_id=settings.ML_AWS_ACCESS_KEY_ID,
            aws_secret_access_key=settings.ML_AWS_SECRET_ACCESS_KEY,
        )

        event_data.upload(s3, BUCKET_NAME, EVENT_DATA_OBJECT)
        order_data.upload(s3, BUCKET_NAME, ORDER_DATA_OBJECT)

Okay, so, the methods still a bit long in the middle.

One thing that came to my mind was that order.event.pk is probably the
same as event.pk itself, right?  Maybe check and simplify that.

Then, the filter call with the lambda feels a bit weird to me, could
that perhaps already be filtered out in the Event.objects.filter...
chain above it?

You could also move one last bit to make things clearer:  Don't expose
the "raw" writerow call, instead just feed objects to the buffers:

        for event in filter(lambda event: not event.is_over, events):
            event_data.write(event)

            for order in event.orders.all():
                order_data.write(order)

However, that would require to have either a method on the object being
written that specifies the serialisation output (well, which values to
select for the rows), or the same information on the ForecastBuffer
object (you could pass in a function that formats an object for CSV).
Depends entirely on the rest of the code if that's worth it / feasible
at all.

Btw. I just saw that itertools has a complement to filter called
filterfalse (arguably that could be a better name, keep comes to my
mind):

        # from itertools import filterfalse

        for event in filterfalse(Event.is_over, events):
            event_data.write(event)

Assuming that you can get the unbound method Event.is_over that way.

Coming back to that @classmethod, the method here is difficult to test
due to the global variables.  Depending on how it's called it might be
worth to make events a parameter so that the functionality of this
method is simply: format to CSV and upload.  Same goes for settings -
the s3 client most definitely should be passed in so this function
doesn't have to deal with configuration on top of formatting and
uploading.

Actually that's still two things, but it's short enough that that's
probably okay, splitting the formatting into another method might also
be worth it actually:

class Forecast:
    @classmethod
    def format_data_for_forecast(cls, events):
        event_data = ForecastBuffer(["Event PK", "Name", "Start date"])
        order_data = ForecastBuffer(["Event PK", "Created", "Total Gross"])

        for event in filterfalse(Event.is_over, events):
            event_data.write(event)

            for order in event.orders.all():
                order_data.write(order)

        return event_data, order_data

    @classmethod
    def export_data_for_forecast(cls):
        events = Event.objects.filter(status=EventStatus.LIVE).prefetch_related(
            'orders'
        )

        event_data, order_data = cls.format_data_for_forecast(events)

        # Upload to S3
        s3 = boto3.client(
            's3',
            aws_access_key_id=settings.ML_AWS_ACCESS_KEY_ID,
            aws_secret_access_key=settings.ML_AWS_SECRET_ACCESS_KEY,
        )

        event_data.upload(s3, BUCKET_NAME, EVENT_DATA_OBJECT)
        order_data.upload(s3, BUCKET_NAME, ORDER_DATA_OBJECT)


Function which removes a given word from a string

I would suggest renaming your variables. str, ptr, and len don't tell us much about what they're meant to be.

size_t len = strlen(word);

Since this is never going to change (because it's abstractly a property of a const input) you might as well mark it const.

while((ptr = strstr(ptr, word)))

I would put a comment here, not least as a note that the assignment is deliberate. (Because so often a single equals sign in an if or while implies  a bug). Really you could do with a few more comments throughout to say why you're doing things: For example the if(isalnum... could be commented to explain that you only want to remove whole words.

strlen(ptr + len)

This may work fine, but it's a moderately expensive thing to do because it has to run down the length of the remaining list. I would be inclined to measure the length str at the start outside the loop, and track it across updates.

memmove(ptr, ptr + len, strlen(ptr + len) + 1);

Again this works fine, but it has to copy (quite slowly and carefully) the whole remaining string. Because it's in a loop, this becomes an \$ O(n^2) \$ function. One solution would be to only move back the string up to the next time word appears. This would mean a bit more complexity tracking the size of the gap that you're building up, but it would reduce the overall complexity of the function to \$ O(n) \$.


The problems with the first approach

int pos = amount.indexOf(',') == -1 ?
                (amount.indexOf('.') == -1 ? 0 : amount.indexOf('.'))
                : amount.indexOf(',');

are that:

It's not that easily readable; the ternary operator has value when what is tested is simple enough. But when you start nesting them, it often degrades clarity.
The index is calculated two times, one to test whether it is -1 or not, and the second time to return the value.

As such, the second approach

int pos = amount.indexOf(',');
if (pos == -1) pos = amount.indexOf('.');
if (pos == -1) pos = 0;

is the most preferable between the two, mainly for clarity. You should consider putting that into a utility method.

There would be other approaches like using a regular expression, but another good one would to not traverse the string potentially 2 times, and instead of looking whether the string has a certain character, loop through each character and see if it is one of the potential delimiters. With Java 8, you could have

int pos = amount.chars().filter(c -> c == '.' || c == ',').findFirst().orElse(0);

And you could write explicitly the for loop for Java ≤ 7.

Final point: having a position of 0 when neither , nor . are present in the String can be confusing; 0 is a valid index value for a string, and it can imply that the delimiter was the first character of the string. If you consider ".25" (that could be a valid representation of a double number, the 0 before being implied), the code would consider this as if having no delimiter.


JavaScript function to create a duplicate-free copy of an array

Sets are basically like magic for pulling unique values from an array; since, by their very definition, any Set will only hold one copy of any specific value, no matter how many times you try to add it.

That, combined with the ability of Sets to be easily turned back into arrays using the spread operator, makes the overall task rather straight-forward:

function noDuplicates(arr){
  return [...new Set(arr)]
}

It actually makes the task so quick and easy that it begs the question of whether a function is even needed; since anytime you need to pull only the unique values of an array you can simply use:

var unique = [...new Set(arr)]

Both the function-based and non-function-based approaches are fully viable options though, so choose whichever you prefer.  Hope this was helpful!


Implementing a dictionary and thesaurus in Python

I find it really strange that you have a list of definitions, personally. I know that there are often multiple definitions for a word, but given that isn't a requirement I wouldn't include it (but this is a great place to practice asking your interviewer questions!).

If I had to include it, I would also want to provide a way to add multiple definitions at once, e.g.

add_word("cat", ["def1", "def2", "def3"])

Additionally, you don't handle the case of a word not being present or synonym not being present - the user should be informed of this in some way.

Other than that, I think that your code is straightforward and successfully meets all of the requirements except for transitivity (if a=b and b=c then a=c).

Transitivity

The obvious way to implement transitivity is to have every word in your thesaurus map to a set, and when you add a synonym iterate over that set and add the new synonym to every one of those words' sets. At this point you can associate all of the words together, but looking up definitions could be annoying (unless you repeat the trick of adding the definition to every synonym).

This solution is not ideal - if you have n words that are synonyms to one another, then it takes O(n^2) space to hold the synonym list1, and O(n*m) space2 to hold the definitions. Wouldn't it be nice if we used O(n) space for the synonyms and O(m) space for the definition3?

I think the best solution here would be a disjoint-set or union-find data structure. Taken from that Wikipedia article:

  A disjoint-set forest consists of a number of elements each of which
  stores an id, a parent pointer, and, in efficient algorithms, a value
  called the "rank".

  The parent pointers of elements are arranged to form one or more
  trees, each representing a set. If an element's parent pointer points
  to no other element, then the element is the root of a tree and is the
  representative member of its set. A set may consist of only a single
  element. However, if the element has a parent, the element is part of
  whatever set is identified by following the chain of parents upwards
  until a representative element (one without a parent) is reached at
  the root of the tree.

  Forests can be represented compactly in memory as arrays in which
  parents are indicated by their array index.

A cool thing about this data structure is that if implemented efficiently, it takes O(a(n)) time to perform both the search and merge operations, which for any real problem (i.e. numbers which can be written in our physical universe) is O(1). If the two primary optimizations aren't implemented you'll hit O(n).

I'm not going to show a full implementation here - its pretty straightforward, and the Wikipedia link gives a good rundown of how it works. The general process would be as follows:

Add a word. Add it to your set with no parent, and associate the definition with this word
Add a synonym of this word. Add it to your set with the word as a parent
Looking up the definition of a word. Look it up in the set, then find the parent which should have the definition with it.
Looking up the synonyms of a word. This one is a bit hard if you don't have back pointers, which you can add without asymptotically increasing the space taken or time taken
Synonyms are commutative. It doesn't matter which is the synonym of the other with back pointers
Synonyms are transitive. You can follow the pointer to the parent or back-pointers to the child.

One thing that is unclear is what happens if you had two existing words in the dictionary and then decided to make them synonyms - this would be another place for your clarifying questions.

I'm assuming that a set of size n takes n space, which depending on implementation may not be true
Assume m is the length of the definition and is proportional to the space it takes to hold it.
This is just to store the single definition of these n synonyms, not of the whole data structure which may have many groups of synonyms, each with their own definition


Since you seem to want code golf over readable code this may not be the answer you want. All the suggestions I make are things I would prefer, but I don't think it's that uncommon for others to disagree. The outcome either way is still pretty ugly.

Your code isn't PEP 8 compliant, and is generally pretty hard to read.
Your one-line docstrings are quite poor, docstring wise. Contrast with:

"""Compress Brainfuck code to TinyBF"""

Use str.maketrans rather than manually make the translation table.

COMPRESS_TABLE = str.maketrans({'>': '2', '<': '3', '+': '4', '-': '5', '.': '6', ',': '7', '[': '8', ']': '9'})

Alturnately you can define both from a common string.

_COMPRESS_STR = '>2 <3 +4 -5 .6 ,7 [8 ]9'
COMPRESS_TABLE = str.maketrans(dict(_COMPRESS_STR.split()))
DECOMPRESS_TABLE = str.maketrans(dict(_COMPRESS_STR[::-1].split()))

I would prefer itertools.zip_longest over manually zipping and justifying.
You can split decompress over multiple lines to make the code more readable.

import itertools

_COMPRESS_STR = '>2 <3 +4 -5 .6 ,7 [8 ]9'
COMPRESS_TABLE = str.maketrans(dict(_COMPRESS_STR.split()))
DECOMPRESS_TABLE = str.maketrans(dict(_COMPRESS_STR[::-1].split()))

def compress(code: str) -> str:
    """Compress Brainfuck code into TinyBF"""
    return "".join(
        chr(int(a + b))
        for a, b in itertools.zip_longest(
            *2*[iter(code.translate(COMPRESS_TABLE))],
            fillvalue="0",
        )
    )

def decompress(code: str) -> str:
    """Decompress TinyBF into Brainfuck"""
    return (
        "".join(str(ord(c)) for c in code)
            .translate(DECOMPRESS_TABLE)
            .rstrip("0")
    )


I believe the problem is that long mod_pow is very inefficient, as it takes e steps to complete, as compared to Python's approach which likely only takes log(e) steps. To fix this, you should use an algorithm similar to the following

function modular_pow(base, exponent, modulus)
if modulus = 1 then return 0
Assert :: (modulus - 1) * (modulus - 1) does not overflow base
result := 1
base := base mod modulus
while exponent > 0
    if (exponent mod 2 == 1):
       result := (result * base) mod modulus
    exponent := exponent >> 1
    base := (base * base) mod modulus
return result


Merging IEnumerable and removing duplicates

With things like this, it's usually best to look at the documentation.

Is your approach with GroupBy() going to work? Yes:

  Elements in a grouping are yielded in the order they appear in source.

Can you use Distinct() to do the same thing more concisely? No (at least you shouldn't depend on it):

  The Distinct method returns an unordered sequence that contains no duplicate values.

Is there some other way? Yes, you can use Union():

  When the object returned by this method is enumerated, Union enumerates first and second in that order and yields each element that has not already been yielded.

So, I think the best way to do it is:

var result = firstFoos.Union(secondFoos);


Search through server folders and display files that exist

You might want to try using the scandir function to build your arrays of directories and files, makes it a bit more future proof.

$baseDir = ABSPATH."/uploads";
$calendarinfo = cal_info(0); //built-in function to generate calendar info, e.g. month names
$years = scandir($baseDir);

//You might want to ignore certain folders, e.g. on UNIX systems:
$ignore = [".","..",".DS_Store"];

foreach ($years as $year) {

    if (!in_array($year, $ignore)) { //the folder is not in the ignore array

        //then scan the year directory for user folders
        $users = scandir($baseDir."/".$year);
        foreach ($users as $user) {

            if ($user == $username) { //if the year contains a folder belonging to logged in user
                echo "
".$year."
"; //create a year heading
                $months = scandir($baseDir."/".$year."/".$user); //scan it for month folders
                foreach ($months as $month) { //scan for month folders

                if (!in_array($month, $ignore)) { //ignore specified folders

                    echo "
";
                    echo "
".$calendarinfo["months"][$month]."
";

                    $contents = scandir($baseDir."/".$year."/".$user."/".$month); //scan each month folder
                    foreach ($contents as $key=>$item) { //for every item found in the month folder

                        if (!is_dir($baseDir."/".$year."/".$user."/".$month."/".$item)) { //ignore directories
                            //and list out the files
                            echo "Download";
                        }
                    }

                    echo "
";

                }
            }
        }
    }
}
}


Code is fine I think, although according to Robert C. Martin, generally, if you need to add a comment then you have failed to write readable code.

For example, this could be made a little easier to read and understand by extracting the block

else //customer is not the first element in the list

into a separate method.  Also the long tests such as

if ((currentLink.surname).equals(surname) && (currentLink.firstName).equals(firstName))
while (currentLink.next!=null && !((currentLink.surname).equals(surname) && ((currentLink.firstName).equals(firstName)))
if (currentLink.surname).equals(surname) && (currentLink.firstName).equals(firstName))

...contain duplicated code, namely

(currentLink.surname).equals(surname) && (currentLink.firstName).equals(firstName)

which would be better extracted into, say testForMatch()

In Summary

Long methods are frowned upon
Repeated code is hard to understand and harder to maintain
Extracting into well named methods beats good comments any day (comments can be left behind during updates and cause more confusion than is necessary with just code)


The values in your lookup tables are strings of binary digits, for example '111010'. It would be closer to the way that real assemblers work if you represented these as numbers in binary, for example 0b111010. I presume you use string concatenation to assemble the instructions at present:

instruction = '111' + comp + dest + jump

With numeric values for the instruction fields, you'll need to use bitwise operations instead:

instruction = 0b111 << 13 | comp << 6 | dest << 3 | jump

There's no error handling. It's likely that assembly programs will contain mistakes, for example:

M=-1;JGR   // oops: typo for JGT

The user would like to get an error message, preferably one that gives the file and line number and an explanation of what went wrong:

prog.asm(17): bad jump field "JGR"

But as far I can see from the code you posted, what will happen here is that Python will raise a KeyError in jump, which is much less useful.

(Possibly there's error handling in the rest of the code that you didn't show us, but I can only comment on what I see here.)
It's even worse for the dest field: this doesn't seem to produce any errors at all, so if I write:

BAD=1;JEQ     // Oops: typo for MAD

then the assembler goes ahead as if I had written

AD=1;JEQ

and I never get told about my mistake.
The logic for lookup of the comp field is needlessly complex. It would be simplest just to make a 7-bit lookup table (including the a bit). Trying to modify the instruction wastes time, and it makes it harder to produce good error messages (outputting the modified instruction will confuse the user, so you have to hang on to the unmodified instruction for use in error messages).

If you don't want to write out the whole 7-bit lookup table, then write code to generate it:

fullCompTable = compTable.copy()
for k, v in compTable.items():
    if 'A' in k:
        fullCompTable[k.replace('A', 'M')] = 1 << 6 | v

and run this once, when the assembler starts up.
The comment for dest says "No point in a lookup table" but that's not true. A lookup table will be faster than the computation in dest. And it only needs 15 entries. Again, if you don't want to write it out by hand, you could compute it:

from itertools import permutations

destTable = {
    ''.join('MDA'[i] for i in p): sum(1<<i for i in p)
    for n in range(1, 4)
    for p in permutations(range(3), n)
}

but this is longer than writing it out in full:

destTable = {
    'A': 4, 'AD': 6, 'ADM': 7, 'AM': 5, 'AMD': 7, 'D': 2, 'DA': 6, 'DAM': 7,
    'DM': 3, 'DMA': 7, 'M': 1, 'MA': 5, 'MAD': 7, 'MD': 3, 'MDA': 7
}

There's no need to take a copy here:

nStr = srcStr[:]  # non-destructive copy

Just write:

nStr = srcStr


Sorting a PHP array in a discontinuous manner

Maybe this answer is a bit late, but hopefully someone can benefit from it!

First off, very interesting concept... It was a challenge to try and figure this one out! I have come up with another implementation, whether it's truly better or not is for the author to decide. Here it is:

<?php

function discontinuous_sort($input) {
    $new = array();

    while ($input) {
        $curr = current($input);
        if (end($new) == $curr) {
            next($input);
            continue;
        } else {
            $new[] = $curr;
            unset($input[key($input)]);
            reset($input);
        }
    }
    return array_filter($new);
}

$test = array('red', 'red', 'red', 'crimson', 'aqua', 'chartreuse', 'green', 'chartreuse', 'red', 'crimson', 'crimson', 'aqua', 'aqua', 'green', 'crimson');

$test_order = discontinuous_sort($test);

foreach ($test_order as $key) {
    echo '

';
}

I'll see what I can do to explain things.

In all honesty, looking at your algorithm, I knew things could be changed. Sorry for making it so drastic!

The first thing I knew I could do was take away the manual indexing on the input array. It does us no good to do this. This also means I can take away the last two parameters in your function. We shouldn't need to name them or create a  multidimensional array.
You were onto something with the while loop, it just needed something else!
I've taken away the aspect of a "holder". At first I thought I'd need one too, but after more work it became apparent I didn't. I am just utilizing the array positioning functions in a different manner.
My snippet basically works like this:

While the original array exists, begin a check. Check if the last element of the new array is equal to the current element in the original. If it is, move onto the next element so we don't get two identical elements next to each other. If the last element isn't equal to the current, append it to the new array and delete that element from the original. Then go back to the beginning! Lastly, erase any empty values (empties are made when we have lots of reds or whatever).

And that's it! I'm sure mine could be simplified, but we're not Code Golf here! ;)


Find the nearest point of a given set of points

It makes no sense to save the distances to disk (disk i/o is slower than the computation), but it might make sense to "memoize" your function:

distance2_cache = {}
def distance2(p1,p2):
    "Compute the distance squared, using cache."
    try:
        return distance2_cache[(p1,p2)]
    except KeyError:
        distance2_cache[(p1,p2)] = d2 = (p1[0]-p2[0])**2 + (p1[1]-p2[1])**2
        return d2

Note that this might actually be slower than your original function because dictionary lookup may be more expensive than 2 multiplications (which dwarf two subtractions and an addition).

Edit: envelopes

If your pool of points is huge, and you have a stream of point that have to be matched against the pool (i.e., find the pool element which is the closest to input point), you can use lattices/envelopes: suppose your pool points have coordinates from 0 to 1. You can split them into 100 boxes by splitting each coordinate into 10. E.g., the box number 35 will have 0.2<=x<0.3 and 0.4<=y<0.5. Then for each new point you only need to check "very few" boxes (instead of all 100).

Specifically, you need to find the closest point in the box where the point landed, and then compare the distance to that closest point to the distance to the boundary of the box.

If the closest point is closer than the boundary, you are done.

Otherwise you need to check those neighboring boxes that are closer than the closest point (up to 11! if the target point and its closest point are almost in the opposite diagonal nodes). However, this should not happen if the number of points in the box is "large".

A good rule of thumb is that each box should contain as many points as there are boxes, e.g., if you have 10,000 points, there should be 100 boxes.

PS. The further development of this approach results in K-d tree.


Dynamically combine ActiveRecord Relation results

Turns out the last code snippet in my question was close to what I ended up needing:

def self.special_animals_only
  SPECIAL_ANIMAL_TYPES.collect { |types| where(types) }.reduce(:or)
end


cron daily and weekly scripts for a minimal Nginx server environment

As mentioned by cas in the discussion, you can simplify your loops:
for dir in /var/www/html/*/; do
    if pushd "$dir"; then
        /usr/local/bin/wp plugin update --all --allow-root &&
        /usr/local/bin/wp core update --allow-root &&
        /usr/local/bin/wp theme update --all --allow-root
        popd
    fi
done

You can also “simplify” the chmod calls:
find /var/www/html/* -exec chmod a-x,a=rX,u+w {} \+

This processes directories and files in one go, and calls chmod as few times as possible (\+ instead of \;). Using the recursive flag to chmod means you can also drop find:
chmod -R a-x,a=rX,u+w /var/www/html/*

In the weekly job,
for dir in /var/www/html/*/wp-content; do cd "$dir" && cd cache && rm -rf *; done;

should be doable as
for dir in /var/www/html/*/wp-content/cache/; do rm -rf "${dir}/*"; done

instead, or even
rm -rf /var/www/html/*/wp-content/cache/*

The \+ comment regarding find is also relevant here.
I highly recommend using “proper” backup tools instead of ad hoc backups (but it’s great to have backups, whatever they are). In particular, automysqlbackup is packaged in Debian and works great for MySQL backups, with automatic pruning and nice password handling; I find BorgBackup great for file archiving.
As cas also tried to suggest, you could do away with the heredocs and perhaps make life simpler for yourself by retrieving the scripts directly. One way to do this would be to store them separately, alongside nses.sh, and retrieve them either as part of a git clone or using curl.


The ?: is called a ternary operator. It's not specific to Ruby; a lot of languages have it (in fact, I believe I linked you to that wikipedia page in a comment very recently).
Go easy on the newlines; there's a lot of whitespace there (update: question was edited; now it's gone)
Use string interpolation
We've talked about that is_ prefix on ? methods already :)

To answer your question: Ternaries have their use, but like everything else, they can also be abused.

In practice, there's no difference between a ternary and and a good ol' if...else, so you can use either - but that argument goes both ways. Don't use ternaries just because you can.

A good case for a ternary (in my opinion), would be something like this (just as an example):

puts some_boolean_value ? "yes" : "no"

or something like

"You have #{messages.count} new #{messages.one? ? 'message' : 'messages'}"

There's no logic going on in either the if or the else branch, and both are very short, so it's short and sweet to use a ternary.

In Ruby you can also spell the first one out like:

puts if some_boolean_value
  "yes"
else
  "no"
end

It's neat that Ruby treats if...else as an expression, but here it seems like a waste of space for something so simple.

In your case: Your code does have more branching logic, so I'd definitely avoid ternaries, and keep it as-is. Personally, I'd never nest ternary expressions inside each other, just for readability reasons.

Alternatively, you can return early (assuming this code is in a method):

return information unless information.is_empty?

if leader? || possessor?
  link_to("update #{contextual "your"} credentials", edit_user_path)
else
  "#{user.name} hasn't entered this info!"
end

If you wrote it all in ternaries, it'd be pretty ridiculous:

information.is_empty? ? leader? || professor? ? link_to("update #{contextual "your"} credentials", edit_user_path) : "#{user.name} hasn't entered this info!" : information # what?

The middle road would be to use a ternary for the innermost nested branch only

if information.is_empty?
  leader? || professor? ? link_to("update #{contextual "your"} credentials", edit_user_path) : "#{user.name} hasn't entered this info!"
else
  information
end

But, as you can see, that innermost nested branch is also the one with the most going on, so it's still less readable than a normal if...else


Slow Converting from JsonArray to ArrayList

If there really is a performance problem with that code, please back this up with some measurements. Otherwise, read some articles concerning premature optimization and don't bother.

Nevertheless, on micro-level there are a few calls that you don't need:

Get rid of superfluous .toString() calls, e.g. replace

String Filiale = value.getString("Filiale").toString();

with

String Filiale = value.getString("Filiale"); // this already is a string

Similarly, don't parse the integers yourself after converting them to string, but instead call getInt() on the Json object:

int IdCantiere = value.getInt("IdCantiere");

Avoid the repeated call to object.length() by holding the length in a variable:

for(int i = 0, n = object.length(); i < n; i++)

Still, the code should be relatively fast as-is. Naturally, there's no way to be really sure without knowing what the constructors for Cliente and Cantiere actually do. If you have a real performance problem, introduce measurements aroud the parameter extraction and the object construction.

And: measure BEFORE AND AFTER you change the code as shown above so that you actually know what effect it had. See https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java for some advice on how to do this.


There is a bug in the code. If you try to sort

4, 3, 1, 2, 0

you get

0, 2, 1, 3, 4


Depth First Search Using Stack in Python

Lists in Python are already stacks. It would be better if you used a raw list as people are more familiar with lists then a custom Stack class.
When using a plain Python list the while loop can take advantage of lists being truthy if they have items. This allows you to do while stack: instead.
I would prefer this to be a generator function as we likely won't need the entire DFS path. path can then be a set for \$O(1)\$ lookup rather than a list with \$O(n)\$ lookup. ("if vertex in path:")
def depth_first_search(graph, start):
    stack = [start]
    visited = set()
    while stack:
        vertex = stack.pop()
        if vertex in visited:
            continue
        yield vertex
        visited.add(vertex)
        for neighbor in graph[vertex]:
            stack.append(neighbor)


Code review

Peilonrays points out a mixup with the out-of-bounds testing that is valid. The statement if j ... must be within the loop for k .... One of the results is that you add a different number of elements to temp depending on which boundary you're at. But there are better ways to avoid out-of-bounds indexing, see below.

Your biggest bug, however, is that you write the result of the filter into the image you are processing. Median filtering cannot be done in-place. When you update data[i][j], you'll be reading the updated value to compute data[i][j+1]. You need to allocate a new image, and write the result there.

I would suggest not adding zeros for out-of-bounds pixels at all, because it introduces a bias to the output pixels near the boundary. The clearest example is for the pixels close to any of the corners. At the corner pixel, with a 3x3 kernel, you'll have 4 image pixels covered by the kernel. Adding 5 zeros for the out-of-bounds pixels guarantees that the output will be 0. For larger kernels this happens in more pixels of course. Instead, it is easy to simply remove the temp.append(0) statements, leading to a non-biased result. Other options are to read values from elsewhere in the image, for example mirroring the image at the boundary or extending the image by extrapolation. For median filtering this has little effect, IMO.

You set temp = [] at the very beginning of your function, then reset it when you're done using it, in preparation for the next loop. Instead, initialize it once inside the main double-loop over the pixels:

for i in range(len(data)):
   for j in range(len(data[0])):
      temp = []
      # ...

You're looping over i and j as image indices, then over z and c or k for filter kernel indices. c and k have the same function in two different loops, I would suggest using the same variable for that. z doesn't really fit in with either c or k. I would pick two names that are related in the way that i and j are, such as m and n. The choice of variable names is always very limited if it's just one letter. Using longer names would make this code clearer: for example img_column, img_row, kernel_column, kernel_row.

Out-of-bounds checking

This concludes my comments on your code. Now I'd like to offer some alternatives for out-of-bounds checking. These tests are rather expensive when performed for every pixel -- it's a test that is done \$n k\$ times (with \$n\$ pixels in the image and \$k\$ pixels in the kernel). Maybe in Python the added cost is relatively small, it's an interpreted language after all, but for a compiled language these tests can easily amount to doubling processing time. There are 3 common alternatives that I know of. I will use border = filter_size // 2, and presume filter_size is odd. It is possible to adjust all 3 methods to even-sized filters.

Separate loops for image border pixels

The idea here is that the loop over the first and last border pixels along each dimension are handled separately from the loop over the core of the image. This avoids all tests. But it does require some code duplication (all in the name of speed!).

for i in range(border):
   # here we loop over the kernel from -i to border+1
for i in range(border, len(data)-border):
   # here we loop over the full kernel
for i in range(len(data)-border, len(data)):
   # here we loop over the kernel from -border to len(data)-i

Of course, within each of those loops, a similar set of 3 loops is necessary to loop over j. The filter logic is thus repeated 9 times. In a compiled language, where this is the most efficient method, code duplication can be avoided with inlined functions or macros. I don't know how a Python function call compares to a bunch of tests for out-of-bounds access, so can't comment on the usefulness of this method in Python.

A separate code path for border pixels

The idea here is to do out-of-bounds checking only for those pixels that are close to the image boundary. For pixels within the border, you use a version of the filtering logic with out-of-bounds checking. For the pixels in the core of the image (which is the big majority of pixels), you use a second version of the logic without out-of-bounds checking.

for i in range(len(data)):
   i_border = i < border or i >= len(data)-border
   for j in range(len(data[0])):
      j_border = j < border or j >= len(data)-border
      if i_border or j_border:
         # filtering with bounds checking
      else:
         # filtering without bounds checking

Padding the image

The simplest solution, and also the most flexible one, is to create a temporary image that is larger than the input image by 2*border along each dimension, and copy the input image into it. The "new" pixels can be filled with zeros (to replicate what OP intended to do), or with values taken from the input image (for example by mirroring the image at the boundary or extrapolating in some other way).

The filter now never needs to check for out-of-bounds reads. When the filtering kernel is placed over any of the input image pixels, all samples fall within the padded image.

Since for this type of filtering it is necessary to create a new output image anyway (it is not possible to compute it in-place, as I mentioned before), this is not a huge cost: the original input image can now be re-used as output image.

This solution leads to the simplest code, allows for all sorts of boundary extension methods without complicating the filtering code, and often results in the fastest code too.


It looks pretty nice! I can only nitpick.

Instead of:

return "negative " + spell_out(-1 * number)

You could simply:

return "negative " + spell_out(-number)

Some PEP8 recommendations:

Use 2 blank lines before each function definition
Use snake case in function names, _create_number instead of _createNumber


Hacker Rank: Extracting digits from a given number and check for divisibility

I see that I have too many ArrayLists and Arrays here and there throughout the code, maybe that can be replaced to begin with.

Yes, that would probably be a good idea. In findDigits you internally use an ArrayList, I'm guessing because it's a lot easier to use than an array (which is true, a List is the correct collection type here). But then you transform it to an array, which isn't really needed.

Returning lists instead of arrays is perfectly acceptable in Java, and is in fact used in most cases (an exception might be made for fixed length arrays in performance critical code, eg coordinates).

So just change your signature from Long[] findDigits(long num) to List<Long> findDigits(long num), and then use a List in findCount as well.

Misc

declare variables in as small a scope as possible. sc isn't really needed anywhere except in main, so declare it there.
don't use short variables names. sc would be clearer as scanner and al could be results.
findDigits could be getDigits, after all you are not really searching for the digits or computing them (they are right there), just getting them.
findCount could be countDivisors, and then num could be divisor.
the question says that you are given an integer, but you use long instead.
your while loop in findDigits could be simplified to digits.add(num % 10);  num = num / 10;.


Menu traversing on next and prev button click up and down

There's not much in the way of predefined jQuery methods to add. Here's what I came up with though...

$(document).ready(function () {
    var $slides = $('#slides li'); //Save repeated selector result.
    var length = $slides.length - 1; //size is deprecated
    var curren = 0;
    console.log(length);
    // used .click due to personal preference .on('click', does the same thing
    $('.next').click(function () {
        if (curren < length) { //Removed check that will always be true
            curren++;
            changeSelected(curren); //Moved repeated code to function
        }
    });
    $('.prev').click(function () {
        if (curren >= 1) {
            curren--;
            changeSelected(curren);
        }
    });

    function changeSelected(index) {
        $('.selected').removeClass('selected');
        $slides.eq(index).addClass('selected'); //Use previously selected object
    }
});

Here's a link to the doc for .size() where you can find it is deprecated.


Convert #hashtagstylephrases to a proper list of words

At first, let me say that the code is somewhat neat and reads easily. A few nitpicks though, based upon PEP8:

each import statement should stand on its own line;
you should put blank lines before function declarations;
you should improve your naming, first by putting more _ in your variable names to separate the words, and second by choosing more meaningful names.

Debugging

You should not need to keep debugging directive in your code now. Remove the pdb module.

Global variables

And top-level code

You are aware of the if __name__ == '__main__' practice but you still keep code at top-level. Worse, you rely on your top-level code to populate a global variable… What if I want to import your_file and use your_file.check_hashtager with my own dictionary of french words?

Better let your functions accept the dictionary as parameter and let the user provide the filename:

def partition_hashtag(text, dictionary_filename):
    with open(dictionary_filename) as f:
        words = [word.strip() for word in f]
    return re.sub(r'#(\w+)', lambda m: partitioner(m.group(1), words), text)

A note on variable names: check_xxx has a meaning of validation only, leading the user to expect a boolean return value (or an error raised on validation error). I considered split_hashtag but I feel like partition_hashtag works best, since it is associated with a dictionary to partition from. partitioner is just a logical consequence.

Partitioning words

Let's talk about longest_word a bit for starter:

you check words of increasing length so there is no need to keep them all and retrieve the longest afterwards, just return the last one you found ;
you can iterate over the letters of phrase directly instead of retrieving them by indexes; it's faster.

def longest_word(phrase, words):  # accepting the dictionary of words as parameter
    word_found = None
    outer_string = ''
    for letter in phrase:
        outer_string += letter
        if outer_string in words or outer_string.lower() in words:
            word_found = outer_string
    return word_found

You’ll need to change if len(word_found) > 0 in func_replace by if word_found is not None or even if word_found which you should have used from start.

But there still exist issue with that code. Concatenating strings in a for loop is not the fastest thing in the world, you might want to consider using

for i in range(1, len(phrase)):
    outer_string = phrase[:i]

instead. But more importantly, checking existence in a list is an O(n) operation, n being the length of the list; you will have a faster execution if words were a set instead because the same operation runs in O(1).

One last thing to note is that you are checking shorter words before longer ones. If you were to try your phrase by decreasing length, the first matching word would be the one you are looking for:

def longest_word(phrase, words):
    current_try = phrase
    while current_try:
        if current_try in words or current_try.lower() in words:
            return current_try
        current_try = current_try[:-1]

    # if nothing was found, return the original phrase
    return phrase

Now let's tackle how this code is called.

First of, what is this i exactly? It is incremented but never used. Second, you made sure in longest_word to return words of at least 1 letter so you don't need to test the length. Third, you don't need to modify your input string in place but only drop its head corresponding to the word you just found.

def partitioner(hashtag, words):
    extracted_words = []
    while hashtag:
        word_found = longest_word(hashtag, words)
        extracted_words.append(word_found)
        hashtag = hashtag[len(word_found):]
    return ' '.join(extracted_words)

Introducing generators

What if partitioner produced only the list of words? We could call the join operation out of this function, like

lambda m: ' '.join(partitioner(m.group(1), words))

This let us focus on only producing words efficiently inside partioner.

Even though the proposed functions reads clearer and should execute faster, there is that list-building-out-of-a-loop thing that is discouraged in Python. Instead we try to come up with list comprehensions to build it faster (plus it reads better). Meaning we usually turn

a_list = []
for element in an_other_list:
    a_list.append(some_function(element))

into

a_list = [some_function(e) for e in an_other_list]

Here the while loop has side-effects on hashtag so we can not directly use that. But…

We are not actually interested in a list of words. We are only interested in getting words one by one to feed them into join. And Python lets you do exactly that by turning your function into a generator: use the yield keyword instead of return. Each time the control flow reach a yield keyword, a result will be returned to the caller. And if the caller ask for more, the control flow will resume after the exact same yield, remembering its old state.

Proposed improvements

import re

def partitioner(hashtag, words):
    while hashtag:
        word_found = longest_word(hashtag, words)
        yield word_found
        hashtag = hashtag[len(word_found):]

def longest_word(phrase, words):
    current_try = phrase
    while current_try:
        if current_try in words or current_try.lower() in words:
            return current_try
        current_try = current_try[:-1]
    # if nothing was found, return the original phrase
    return phrase

def partition_hashtag(text, words):
    return re.sub(r'#(\w+)', lambda m: ' '.join(partitioner(m.group(1), words)), text)

def read_dictionary_file(filename):
    with open(filename, 'rb') as f:
        return set(word.strip() for word in f)

if __name__ == '__main__':
    words = read_dictionary_file('corncob_lowercase.txt')
    print partition_hashtag("#Whatthehello #goback", words)


Clearing up property and field confusion in C#?

There is a special use case when the (slightly modified) second approach could be beneficial. Namely when you want to create immutable objects.
public sealed class PersonEntity
{
    public string FirstName { get; }
    public string LastName { get; }
    public int Age { get; }

    public PersonEntity(string firstName, string lastName, int age)
    {
        FirstName = firstName;
        LastName = lastName;
        Age = age;
    }
}

By removing the setters you are not allowing the consumer of the class to alter its data after creation. In case of concurrency immutable structures can be shared safely between multiple workers without extra syncronization.
You can define with method(s) to this class as an extension to provide copy with alternative value functionality.
public PersonEntity WithFirstName(string firstName)
{
    return new PersonEntity(firstName, LastName, Age);
}

public PersonEntity WithLastName(string lastName)
{
    return new PersonEntity(FirstName, lastName, Age);
}

public PersonEntity WithAge(int age)
{
    return new PersonEntity(FirstName, LastName, age);
}

Of course you can make it a bit more generic:
public PersonEntity With(string firstname = null, string lastName = null, int? age = null)
{
    return new PersonEntity(
       firstName ?? this.FirstName,
       lastName ?? this.LastName,
       age ?? this.Age);

}

Usage sample:
var xy = new PersonEntity("x", "y", 15);
var xz = xy.With(lastName: "y");
var xz25 = xz.With(age: 25);

UPDATE: C# 9's record
In C# 9 there will be a new construction called record.
Declaration
public record PersonEntity
{
    public string FirstName { get; init; }
    public string LastName { get; init; }
    public int Age { get; init; }
}

Usage
var xy = new PersonEntity { FirstName = "x", LastName = "y", Age = 15 };
var xz = xy with { LastName = "y" };
var xz25 = xz with { Age = 25 };


Bresenham's line algorithm implementation

The least you could do is move if(steep) out of the for loop, saving one conditional in every iteration.

In the initializations, you could use a swap function.

Why is the name of the function getIntersects?

I don't know C#, but if new Coordinate(x,y) is using the heap for every single point, this does not sound very efficient.


Hash table with complex variable-length keys

So I'm looking for the go-to solution for situation like this, if one exists

Big step, small step. Rather than run the snake once, you run it twice in parallel, but the two instances run at different speeds:

snake1 = ...;
snake2 = snake1.clone();
while (true) {
    snake1.step();
    snake2.step();
    snake2.step();
    if (snake1.equals(snake2)) {
       // Loop detected
    }
}

If the cycle is of length \$n\$ and you enter the cycle for the first time at \$t_0\$ then this will detect the cycle as long as there's a number \$t \ge t_0\$ for which \$t \equiv 2t \pmod n\$. But that reduces to \$t \equiv 0 \pmod n\$, so \$t\$ is the first multiple of \$n\$ greater than or equal to \$t_0\$, and it's guaranteed to find the loop.

Essentially you trade memory saving (no history required) for execution time (it takes \$3t\$ calls to step() rather than \$t_0 + n\$).

That renders rather unnecessary the following observation:

    const arr = [this.direction.hash(), this.pallet.hash(), this.head.hash(), ...this.body.map(x => x.hash())];

Most of those don't need to use a Vector2 with a hash: there are 4 possibilities for the direction, and the body can be represented by a series of directions. Using arrays of length 4 might be more efficient than object properties.


Is this Repository Design Pattern Valid and efficient?

I think your abstract class should "implement" the IRepository interface, because otherwise you will always have to put both the interface and the base class in your inheritance list. Also, I think you should name your Repository -> SqlRepository, since all the code in the base class is coupled to Sql. As @Heslacher pointed out, you should inject your connection, because keeping the static connection might cause problems. What would happen if one of my Repository implementation would dispose the connection? All your repositories would be down.

abstract class SqlRepository<T> : IRepository<T>
{
    protected IDbConnection Connection { get; set; }

    protected SqlRepository<T>(string connectionString)
    {
        Connection = new SqlConnection(connectionString);
    }

    abstract IEnumerable<T> GetAll();
    abstract T GetItem(int id);
    abstract T Create(T item);
    abstract bool Update(T item);
    abstract bool Delete(int id);
    abstract void Reset();
}

If your application runs on one instance, your repository would be okay. But since it puts all database entities in cache (your collection) and never returns to the database unless you specify it, you have a problem. Example : Client A (On an X machine) loads the database in cache, Client B (on a Y machine) does the same then adds a State to the repository. Client A calls GetAll, what should be the expected output? Client A wouldn't have the new State. And if Client B calls Reset the new State was never persisted, so it is lost.

I don't think you should use the ICollection<State>, each of your call should go to the database, so you are sure you have the latest version of your data. If you remove it, I don't think you need to handle thread safety anymore.


Python - Iterating over contents of BeautifulSoup element very slow

It seems like you have the following:

a

b

c

d

And you want to extract a list of the headers grouped with the content:

[('a', 'b'), ('c', 'd')]

The slow part of your code is most certainly the if tag in headers. If header is a list of 10k elements, then for each element in .main you are searching through potentially 10k elements. This is horribly inefficient. If headers was a set, this would be more efficient, but there's no need for it to be (or for you to check if tag in headers).

def get_header_content_pairs(doc):
    main = doc.find("div", class_="main")
    headers = main.find_all("div", class_="header")

    for header in headers:
        yield (header, list(get_content(header.nextSibling)))

def get_content(element):
    while element.name == 'p':
        yield element
        element = element.nextSibling

Haven't tested this, but the gist is instead of doing all that work, you take advantage of the fact that each BS element knows about its nextSibling. You find all of the .headers. For each of them, you continue checking nextSibling until you find something that isn't a
. You aggregate these and return them with their header.


Productivity/Timer app that uses twilio to send SMS-reminders

Ways of improving:

work_time and break_time as constant values deserve to be defined as CONSTANTS
_timer function:

workState should be renamed to work_state to follow naming conventions
messageBody = ["Time to work", "Time to break"] is not actually used (can be eliminated)
if workState == True: is just a verbose version of if workState:
both conditional branches if/else have the same common statement _timer(not workState) but differ in action name work/break and delay time work_time/break_time.The whole condition can be restructured to reduce repetitive code and move the common statement(s) out

The final optimized version:

import time
from twilio.rest import Client

client = Client("KEY", "KEY")

WORK_TIME = 20 * 60
BREAK_TIME = 5 * 60

def _timer(work_state=True):
    if work_state:
        action, delay_time = 'work', WORK_TIME
    else:
        action, delay_time = 'break', BREAK_TIME

    client.messages.create(to="MYNUMBER", from_="TWILIONUMBER",
                           body=f"Time To {action.title()}!")
    time.sleep(delay_time)
    _timer(not work_state)

_timer(False)


Project Euler #10 in Swift - Summation of primes

Since we know that primes can be represented by 6x+1 or 6x-1 except for 2,3, we could skip them as follows:

//Handle explicitly for n<5 i.e for n = 0,1,2,3,4 and proceed otherwise.
if n<3 { // n=0,1,2
    return 0
}
if n<5 {// n = 3,4
    return (n==3)?2:5
}

var x = 5
while x <= maxPrime {
    if composite[x] == false {
        for y in stride(from: x * x, through: n - 1, by: x) {
            composite[y] = true
        }
    }
    x+=2
    if x<n && composite[x] == false {
        for y in stride(from: x * x, through: n - 1, by: x) {
            composite[y] = true
        }
    }
    x+=4
}

var result = 5 // 2 + 3
for i in stride(from: 5, through: composite.count - 1, by: 4) {
    if composite[i] == false {
        result += i
    }
    i+=2
    if i<n && composite[i] == false {
        result += i
    }
}

Results: With your code it took me 33ms with mine its down to 23ms.


Clean and tidy Python code for dictionary look up and API interactions

I have a few pointers, a lot of them coming from Python's offical style guide:

ALWAYS use with syntax when dealing with files:

with open('some_file.txt', 'r') as file:
    # Do stuff

# file will be closed by now
foo = 'Hello World!'

This syntax prevents any errant bugs like forgetting to close a file, which you do here:

bio_dict = eval(open('biodict.txt').read())

Use format to create strings with variables. This is the easiest way to create strings without having to use ugly string concatenation:

# This functions...
def data_object_url(line):
    return 'http://eol.org/api/data_objects/1.0/' + line.strip() + '.json'

# But this is better, more Pythonic
def data_object_url(line):
    return 'http://eol.org/api/data_objects/1.0/{}.json'.format(line.strip())

Different module imports should not go on the same line:

import urllib, json

They should have their own line. If you are importing submodules, then you can have multiple imports on the same line:

from my_module import some_func, other_func

Pay attention to function and variable names; make them descriptive.

Function names should start with a verb and describe what they do: instead of data_object_url use something like get_object_url.

Also, make variable names descriptive; erring on the side of being too wordy than not wordy enough: instead of for k, v in bio_dict.iteritems() use for key, value in bio_dict.iteritems().
When writing comments, only say what needs to be explained. Comments should not explain the obvious but instead should explain the complex or the reasons behind the code. A lot of the comments you have would actually be more fitting as docstrings.
Look into list comprehensions. In my code below I was able to take your for loop into a single statement. This also made writing to the output file much more Pythonic.

Here is what your code looks like with my suggestions implemented:

#!/usr/bin/env python
# coding: utf-8

import urllib
import json

with open('biodict.txt', 'r') as file:
    bio_dict = eval(file.read())

in_file_name = "text_object_id1.txt"
out_file_name = "all_uri.txt"

def get_object_url(line):
    return 'http://eol.org/api/data_objects/1.0/{}.json'.format(line)

out_file_text = []
with open(in_file_name, 'r') as file:
    for line in in_file:
        line = line.strip()
        results = urllib.urlopen(get_object_url(line)).read()
        data = json.loads(results)

        descriptions = data['dataObjects'][0]['description'].lower()
        out_file_text += [','.join(line, key, bio_dict[key])
                             for key in bio_dict if key in descriptions]

with open(out_file_name, 'w') as file:
    file.write('\n'.join(out_file_text))


Project Euler #14 (Longest Collatz Sequence) in Haskell

The main reason why this is slow is that every update to your array is making a new copy of it. The version you linked to on the wiki avoids this problem by using a boxed array instead, which allows you to define the array in one go and let lazy evaluation take care of evaluating the elements in an appropriate order and modifying the array behind the scenes.

A boxed array is less memory efficient since it's basically an array of pointers to individually-allocated integers, but for the size of this problem it's not too bad. If you want to use an unboxed array for improved space efficiency, you would probably want to use a mutable one in the ST monad instead. There's an example of how how to do that in an old answer of mine on Stack Overflow.

Regarding your second attempt:

First off, let's get this code to compile.

Since the else branch of this if is returning a statement in the ST monad, so must the then branch. A quick fix is to add return:

v <- if n' > n then return 0 else (readArray seqLengths n')
                    ^^^^^^

And there shouldn't be a $ when passing the comparison function
to maximumBy here:

main = print $ fst $ maximumBy  (comparing snd) $ assocs $ getCollatzSequenceLengthUpto 1000000
                               ^

With those small changes, it compiles and it runs in about 4 seconds on my netbook. Not too bad!

However, it's a bit messy, let's see if we can fix that. First of all, let's reduce that ball of nested if's.

We can get rid of the outermost if by using a separate equation for when n' is 1:

compute l s 1  = return (l+1, reverse s)

The two branches of the innermost if are almost the same. We can move the if inside to the only place they differ. Also do out <- compute ...; return out is the same as just compute ...:

compute l s n' = do
    v <- if n' > n then return 0 else readArray seqLengths n'
    if v > 0
        then return (l+v, reverse s)
        else compute (l+1) (n':s) (if even n' then n' `div` 2 else (3*n'+1))

Here is the full working code after these adjustments. I still think the way
you're using a list to deal with the updates is somewhat complicated, but I think fixing that in a satisfactory way would require more substantial changes to your algorithm, so I've left it the way it is.

import Control.Monad (forM_)
import Control.Monad.ST
import Data.Array.ST
import Data.Array.Unboxed
import Data.Int (Int64)
import Data.List (maximumBy)
import Data.Ord (comparing)

getCollatzSequenceLengthUpto :: Int64 -> (UArray Int64 Int64)
getCollatzSequenceLengthUpto n = runSTUArray $ do
    seqLengths <- newArray (1,n) 0
    forM_ [1..n] $ \i -> do
        let compute l s 1  = return (l+1, reverse s)
            compute l s n' = do
                v <- if n' > n then return 0 else readArray seqLengths n'
                if v > 0
                    then return (l+v, reverse s)
                    else compute (l+1) (n':s) (if even n' then n' `div` 2 else (3*n'+1))
        (l, u) <- compute 0 [] i
        forM_ (filter (\(n',_) -> n' <= n) $ zip u [l,l-1..]) $ \(ix, e) -> do
            writeArray seqLengths ix e
    return seqLengths

main = print $ fst $ maximumBy (comparing snd) $ assocs $ getCollatzSequenceLengthUpto 1000000


Computing the total different between a pixel and its neighborhood

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

Measure your code

Since we don't have your data or your computer or your compiler, we're a little bit hampered in trying to identify things that will speed up your code.  However, you have access to all of those things, so rather than guess that it's the cause of the if-then constructs or anything else, the prudent thing to do would be to measure the code and find out (e.g. with a profiler) where your code is spending most of its time.  Armed with that data, you can begin to effectively target the real bottlenecks.

Think about "locality of reference"

With modern computers, cacheing is often a factor in determining performance.  Generally, data items that are "close together" (that is, items that all fit in the cache at once) will be quicker to access than those that are "far apart" (that is, items that do not all fit in the cache at once).  For this reason, we can think about restructuring the algorithm to try to work on as small a memory footprint as possible.  In this case it's possible you can gain performance by simply rearranging the nested loops.  Right now, it looks like this:

for (int label=2; label <= class_count+1; label++) {
   for (int i=1; i < M-1; i++) {
      for (int j=1; j < N-1; j++) {

But I think I'd try arranging things like this instead:

for (int j=1; j < N-1; j++) {
   for (int i=1; i < M-1; i++) {
      for (int label=2; label <= class_count+1; label++) {

This way, the input data is accessed in a somewhat more sequential manner.  The output data is not, but because it's only accessed once per loop, I'm guessing that it makes less difference.

Simplify your code

One of the things your code does is to either add or subtract an energy value if a particular value is matched.  Because integer math is often faster than floating point, you might benefit from restructuring your code.  Here's one way to do that.  Change the interior of the loop to look like this instead:

int energycount = 8;
if (label == img(i-1,j-1)) energycount -= 2;
if (label == img(i  ,j-1)) energycount -= 2;
if (label == img(i+1,j-1)) energycount -= 2;
if (label == img(i-1,j  )) energycount -= 2;
if (label == img(i+1,j  )) energycount -= 2;
if (label == img(i-1,j+1)) energycount -= 2;
if (label == img(i  ,j+1)) energycount -= 2;
if (label == img(i+1,j+1)) energycount -= 2;
G[(i-1) + (j-1)* (M-2) + (label-2) * (N-2) * (M-2)]=beta*energycount;

Use const where practical

Many of these values are set once and then not changed.  The compiler may be able to find better optimizations if you explicitly tell it which values are const:

const int ndim = 3;
const int N = (int) mxGetN(prhs[0]); //cols
const int M = (int) mxGetM(prhs[0]); //rows
const double *img = (double *)mxGetData(prhs[0]);
const double beta = (double )*mxGetPr(prhs[1]);
const int class_count = (int )*mxGetPr(prhs[2]);
/* Initial zeros matrix*/
const int dims[3] = {M-2, N-2, class_count};
plhs[0] = mxCreateNumericArray(ndim, dims, mxDOUBLE_CLASS, mxREAL);
double *G = (double *) mxGetPr(plhs[0]);

Don't initialize large data items pointlessly

It appears that every member of G is initialized by the loop, so there's no real need to initialize it before that.  For that reason, I'd recommend using mxCreateUninitNumericArray to create an unitialized array rather than mxCreateNumericArray which initializes all values to 0.


Wild and changing business rules implemented with functional programming

The original requirement

  How can you tame these wild business rules? How can you build a system that will be flexible enough to handle both the complexity and the need for change? And how can you do it without condemning yourself to years and years of mindless support?

seems, to me, to insinuate some sort of generic rules engine. This is, I believe, a red herring. The problem with rules engines, in my experience, is that the selling point is always that 'business users' can maintain them without involving developers.

This is a pipe dream, because if business rules can be arbitrarily complex, you're going to need a rules engine that can handle all of this complexity. In other words, you're going to need a programming language, and then it becomes too technical for business users.

This is called the inner platform effect and is, in my opinion, best avoided.

So you might as well use a programming language to implement the rules, and I see no reason you can't use a functional language like F#.

Here's a sketch of some of the rules. Like in the real world, some of the rules are vaguely defined, so I wasn't sure how to interpret them...

type Membership = Basic | Gold

type Good =
| PhysicalProduct of string
| Book of string
| Video of string
| Membership of Membership
| Upgrade

type Command =
| Slip of string * (Good list)
| Activate of Membership
| Upgrade
| PayAgent

These are simply some types, but given these types, you can implement various business rules, e.g.

// Good -> Command list
let slipForShipping = function
| PhysicalProduct name
| Book name
| Video name -> [Slip ("Shipping", [PhysicalProduct name])]
| _ -> []

// Good -> Command list
let slipForRoyalty = function
| Book name -> [Slip ("Royalty", [Book name])]
| _ -> []

// Good -> Command list
let activate = function | Membership x -> [Activate x] | _ -> []

// Good -> Command list
let upgrade = function | Good.Upgrade -> [Upgrade] | _ -> []

You'll notice that all these rules have the same type, which means that you can collect all of them:

// ('a -> 'b list) list -> 'a -> 'b list
let handle handlers good = handlers |> List.collect (fun h -> h good)

// Good -> Command list
let handleAll = handle [slipForShipping; slipForRoyalty; activate; upgrade]

Example:

> handleAll (Book "The Annotated Turing");;
val it : Command list =
  [Slip ("Shipping",[PhysicalProduct "The Annotated Turing"]);
   Slip ("Royalty",[Book "The Annotated Turing"])]

As far as I can tell, this would be fairly maintainable, because if you need to add a new rule, you'll have to add a new function, and add that function to handleAll.


Retrieve unique child objects from an array

Here's a more functional solution, which based on your example is what you're looking for.  It relies on the uniqueness of object keys.  Note it's untested, but the idea should work:

function getMasters() {
  var extended = r => new ExtendedRank(r.master.id r.master.code, r.master.name),
  return Object.values(
    this.ranks.reduce((m,r) => Object.assign(m, {[r.master.id]: extended(r)}), {});
  ).sort(this.sort);
}

If you're looking to go even further in this direction, I recommend checking out ramda as a better, more functional alternative to underscore.


Some notes about your code:

sorted([i for i in words if i[:1] == "s"]): No need to generate an intermediate list, drop those [ ] and you'll get a lazy generator expression instead.
mylist1. This my prefix looks pretty bad. Do other languages use them?
list: Red flag. Don't overshadow a built-in (at least not one so important) with a variable.
return list. You can directly write return mylist1 + mylist2, no gain in naming the value you're about to return (the name of the function should inform about that).
i[:1] == "s" -> i.startswith("s").

Now what I'd write. Using sorted with the argument key (Schwartzian transform) and taking advantage of the lexicographical order defined by tuples:

def mysort(words):
    return sorted(words, key=lambda word: (0 if word.startswith("s") else 1, word))

If you are familiar with the fact that False < True, it can be simplified a bit more:

sorted(words, key=lambda word: (not word.startswith("s"), word))

Here's another way using the abstraction partition:

words_with_s, other_words = partition(words, lambda word: word.startswith("s"))
sorted(words_with_s) + sorted(other_words)

Writing partition is left as an exercise for the reader :-)


This part doesn't make sense to me:

private function crypt_pass($pass)
{
    if (CRYPT_BLOWFISH == 1)
    {
        $salt = SHA1('acssalty457');
        $blowfish_salt = "\$2a\$07\$".substr($salt, 0, CRYPT_SALT_LENGTH);
        return crypt($pass, $blowfish_salt);
    }
}

Functions that only return on condition are a bad idea. You should return something anyway, even if it's false. Now for the specific problem, what if CRYPT_BLOWFISH != 1? It's ok to want to use blowfist, but why cripple the library for everyone else? You could rewrite as:

private function crypt_pass($pass) {
    $salt = "acssalty457";

    if (CRYPT_BLOWFISH == 1) {
        $blowfish_salt = "\$2a\$07\$" . substr($salt, 0, CRYPT_SALT_LENGTH);
        return crypt($pass, $blowfish_salt);
    }

    return sha1($pass . $salt);
}

Notice that I don't hash the salt? That's because security wise that's useless. You can ask around at Cryptography Stack Exchange for more. If you want to make the sha1 crypted pass a little bit harder you could do something weird like:

return sha1(strrev($salt) . $pass . $salt);

I'm using sha1 as an example of a natively included function, you can use any hash algorithm you like.


From the documentation, you can see that a worksheet object has an .append method that let you write a row from an iterable at the bottom of said sheet. Documentation from the builtin help is reproduced here:

Help on method append in module openpyxl.worksheet.worksheet:

append(iterable) method of openpyxl.worksheet.worksheet.Worksheet instance
    Appends a group of values at the bottom of the current sheet.

    * If it's a list: all values are added in order, starting from the first column
    * If it's a dict: values are assigned to the columns indicated by the keys (numbers or letters)

    :param iterable: list, range or generator, or dict containing values to append
    :type iterable: list|tuple|range|generator or dict

    Usage:

    * append(['This is A1', 'This is B1', 'This is C1'])
    * **or** append({'A' : 'This is A1', 'C' : 'This is C1'})
    * **or** append({1 : 'This is A1', 3 : 'This is C1'})

    :raise: TypeError when iterable is neither a list/tuple nor a dict

This means that your can sheet.append(headers) instead of your ugly loop. Similarly, using .values() on your dictionnaries, you can simplify your write_xls function to:

def write_xls(filepath, dictionary):
    wb = load_workbook(filepath)
    sheet = wb.active

    headers = list(dictionary[0])
    sheet.append(headers)

    for x in dictionary:
        sheet.append(list(x.values()))

    wb.save(filepath)

Now, a few more things to consider.

First off, since you are only interested in creating the file and writing in it, you may be interested in the write-only mode provided by openpyxl. This mean you will simplify your code to a single function:

def write_xls(filepath, dictionary):
    wb = Workbook(write_only=True)
    sheet = wb.create_sheet()

    headers = list(dictionary[0])
    sheet.append(headers)

    for x in dictionary:
        sheet.append(list(x.values()))

    wb.save(filepath)

Second, you relly very much on your data being presented well ordered and without flaws. This might bite you at some point. I would:

find all possible headers in your dictionnaries and order them;
use them to recreate each row using the same ordering each time.

This will allow you to have a coherent output, even with inputs such as:

things = [
    {
        "Fruit": "Orange",
        "Flavour": "Good",
        "Expiration": "21May20",
    },
    {
        "Flavour": "Good",
        "Fruit": "Apple",
        "Expiration": "19May20",
    },
    {
        "Flavour": "Regular",
        "Expiration": "16May20",
        "Fruit": "Banana",
    }
]

or even:

things = [
    {
        "Fruit": "Orange",
        "Flavour": "Good",
        "Expiration": "21May20"
    },
    {
        "Fruit": "Apple",
        "Flavour": "Good",
        "Junk": "Spam",
        "Expiration": "19May20"
    },
    {
        "Fruit": "Banana",
        "Flavour": "Regular",
        "Expiration": "16May20"
    }
]

Proposed improvements:

import itertools

from openpyxl import Workbook

def write_xls(filename, data):
    wb = Workbook(write_only=True)
    ws = wb.create_sheet()

    headers = list(set(itertools.chain.from_iterable(data)))
    ws.append(headers)

    for elements in data:
        ws.append([elements.get(h) for h in headers])

    wb.save(filename)


It would be more usual to replace the if null strings... conditional with a case, and concat is more commonly used than fold for lists:

fizzbuzz :: [Fizzrule] -> Int -> String
fizzbuzz rules int
  = case mapMaybe (processrule int) rules of
      [] -> show int
      strings -> concat strings

Similarly, processrule would more commonly be written with guards than an if-then-else:

processrule :: Int -> Fizzrule -> Maybe String
processrule int rule
  | int `mod` (divisor rule) == 0 = Just (yell rule)
  | otherwise                     = Nothing

For simple structures like Fizzrule, it's pretty common to dispense with field selectors and pattern match directly, so this would probably be further rewritten. Also, it's more usual to use single character arguments like n in preference to int, though str and lst are often used for strings and lists:

processrule :: Int -> Fizzrule -> Maybe String
processrule n (Fizzrule d str)
  | n `mod` d == 0 = Just str
  | otherwise      = Nothing

Then the mapMaybe and processRule functions aren't actually doing much, so it would be more usual to replace them with a list comprehension:

fizzbuzz :: [Fizzrule] -> Int -> String
fizzbuzz rules n
  = case [s | Fizzrule d s <- rules, d `divides` n] of
      [] -> show n
      strings -> concat strings
  where d `divides` m = m `rem` d == 0

Arguably, it might be more usual to keep the "map" in main pure and output all the lines at once.  (Even when run as a pure computation, it's all done lazily, so no worry that you need to wait for the computation to complete if you try to FizzBuzz the first billion integers or even run it on an infinite list [1..]).  Also, note the type signature spacing -- it's always IO () and never IO().

main :: IO ()
main = putStr . unlines $ map (fizzbuzz rules) [1..100]

Naming all the rules seems like overkill, and Fizzrule takes forever to type, so maybe:

{-# OPTIONS_GHC -Wall #-}

module Main where

data Rule = Rule Int String

myrules :: [Rule]
myrules =
  [ Rule 3 "Fizz"
  , Rule 5 "Buzz"
  , Rule 7 "Quux"
  ]

fizzbuzz :: [Rule] -> Int -> String
fizzbuzz rules n
  = case [s | Rule d s <- rules, d `divides` n] of
      [] -> show n
      strings -> concat strings
  where d `divides` m = m `rem` d == 0

main :: IO ()
main = putStr . unlines $ map (fizzbuzz myrules) [1..100]

That looks more idiomatic to me.

Writing the Rule as a newtype:

newtype Rule = Rule (Int, String)

would be silly.  The main point of newtype is to introduce a type and associated constructor that's "free" from a performance standpoint because it's erased at compilation time (while also allowing for certain conveniences related to automatically deriving type class instances).  However, in:

newtype Rule = Rule (Int, String)

the Rule constructor can be erased, but the pair constructor (normally written (,)) is still there.  If you just write a data type in the first place:

data Rule = Rule Int String

then that replaces the (,) constructor with the Rule constructor more explicitly.  There's no advantage here to newtype Rule -- it just requires extra typing when constructing or pattern matching values.

The choice between data Rule = ... and type Rule = (Int, String) is more a matter of personal taste.  I'd probably go with the data Rule type.

To summarize some of the principles used above:

if-then-else statements are rare in Haskell and are usually replaced by case constructs (or the implicit case construct of function definitions), possibly with the help of guards.  It's especially rare to see if null lst then... since this is almost always better written as a case.
Haskellers usually inline helper functions like processrule that are only used in one place and have no general applicability.  In constrast, Haskellers often define trivial functions like divides in where clauses where they improve readability.  I'm arguing here that the list comprehension is more directly readable than the function name processrule, but divides is more readable than the m `rem` d == 0 expression.  It's a judgement call.
At least for "small" data structures, pattern matching is usually used in preference to field selectors.
Pure code is often used in preference to impure code, including where you have an action where additional purity can be factored out (e.g., instead of mapM_ over multiple IO actions, map over pure values and pass that to a single IO action).


You could change the close tooltip fade out to use the jquery delay method (assuming you're using jQuery 1.4+).

Instead of this:

if(this.closeTool)
    clearTimeout(this.closeTool);

this.closeTool = setTimeout(function() {
    toolTip.fadeOut(); //Run this timeout to hide tooltip if not clicked
}, 10000);

You can do this:

if (toolTip.queue().length > 0) {
    toolTip.finish();
} else {
    toolTip.delay(10000).fadeOut();
}

When the user clicks the first time, the effects queue will be empty (length will be 0), so we queue up the delay and the fade out.

When the user clicks the second time, the effects queue length will be more than one, so we use finish to stop the current animation (either the delay or the fade out) and to remove all effects in the effects queue (which will be the delay or both the delay and fade out).


Workaround for the precision limitation for Python's round() function

Following ferada's advice I looked up the decimal module and it simplifies things quite a bit.

This is a function that does what format_5() does but much succinctly:

def format_5_dec(f):
    new_float = Decimal.quantize(f, Decimal(str(f)[:-1]), rounding='ROUND_UP')
    return new_float


Card class

Your id does not change after being set once. This makes it perfect for being set inside a constructor. This will also allow you to make it private final int id; . It is a good practice to use final fields whenever possible.

Instead of:

Card c = new Card();
c.setId(val);

Do:

Card c = new Card(val);

Board

selectedCard is only a temporarily-used variable which is set in one method and read directly afterwards in another. It should be passed on to the doTurn method, no need to use it as a class field.

Instead of:

selectedCard = c;
doTurn();

Do:

doTurn(c);

doTurn

As suggested above, this method should take the selectedCard parameter directly.

At the moment, this method does a little bit too much and contains some slight code duplication.

c1.setText(String.valueOf(c1.getId()));
c2.setText(String.valueOf(c2.getId()));

There's no fundamental difference between those two lines, and if asked what those lines do you would probably say something like "it shows the text on the cards". Now let's make that a method in the Card class!

 public void showText() {
      this.setText(String.valueOf(id));
 }

Your doTurn method then becomes:

public void doTurn(Card selectedCard) {
    if (c1 == null && c2 == null) {
        c1 = selectedCard;
        c1.showText();
    }
    else if (c1 != null && c1 != selectedCard && c2 == null) {
        c2 = selectedCard;
        c2.showText();
        t.start();
    }
}

checkCards

if (c1.getId() == c2.getId()){//match condition

Can be extracted to a method and called like:

if (c1.hasSameId(c2)) {

c1.setEnabled(false); //disables the button
c2.setEnabled(false);
c1.setMatched(true); //flags the button as having been matched
c2.setMatched(true);

Code duplication. Can be extracted to c1.matchButton();

System.exit(0);

This is an 'evil' way of exiting your application. It is preferred to close the JFrame instead and shut down the timer. That will exit your application in a more 'friendly' way.

c1.setText(""); //'hides' text
c2.setText("");

Again, method extraction will make this code more self-explanatory, and make the buttons better be responsible for what they should be responsible for.

c1.hideText();
c2.hideText();

Game Won and Streams

In Java 8 (which I believe that you are using) your isGameWon method can be simplified:

public boolean isGameWon(){
    return this.cards.stream().allMatch(c -> c.isMatched());
}

Composition over inheritance

This goes back to the Card class primarily:

public class Card extends JButton

With the above suggestions of extracting methods to make the Card class be responsible for setting text and disabling the buttons and stuff, you can remove the extends JButton and write it more like this:

public class Card {
     private final int id;
     private final Button button = new Button();
     ...

     public Card(int id) {
          this.id = id;
     }

     public Button getButton() {
          return this.button;
     }

     ...
}

And create it like this:

Card c = new Card(val);
c.setId(val);
c.getButton().addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae){
        selectedCard = c;
        doTurn();
    }
});

The extra step

This is a slightly more advanced concept. Use it at your own risk, if you feel that you can understand it.

Side note: It is possible to make this even better, by for example pass on a Consumer<Card> to the Card class and pass on this::doTurn when constructing the cards, and have your Card action listener call this Consumer<Card>.

On the positive side, this will remove the need of exposing the Button in your Card class. On the negative side, this might be a bit "over your head" at the moment.

Card c = new Card(val, this::doTurn);

public class Card {
     private final int id;
     private final Button button = new Button();
     ...

     public Card(int id, Consumer<Card> onClick) {
          this.id = id;
          this.button.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent ae) {
                  onClick.accept(Card.this);
              }
          });
     }

     public Button getButton() {
          return this.button;
     }

     ...
}


Kudos for using list comprehensions. However picked = []; set_trace(k, n, W, items, picked) and picked.append(items[i-1]) doesn't feel as good.

One could expect set_trace to build the list and return it. Even better, would be to picked = list(set_trace(k, n, W, items)), meaning set_trace would be a generator (with a pretty terrible name).

In order to do so, you first have to come to the conclusion that the recursion is really not necessary. All you do, in that recursive call, is continue the iteration at the next step with a different W. And that's it, you break. You could have just replace these two lines with W -= items[i-1][2]. Doing so, you could replace the append with a yield and you have your generator:

def set_trace(k, n, W, items):
    for i in range(n, 0, -1):
        if k[i][W] != k[i-1][W]:
            yield items[i-1]
            W -= items[i-1][2]

this lets you define picked = list(set_trace(k, n, W, items)).

However, n is len(items) so you might as well not pass it as a parameter and compute it at the beginning of the function.

You can also get much better readability by improving your naming. I understand that you named your variables based of the math theory that this problem relly on, but single letter variable names are a poor choice.

Same for using a simple tuple to store your items: it doesn't convey meaning. Use a namedtuple instead.

Last thing, since you are skipping the first row and first column of k, you can use slices and the enumerate builtin to avoid using so much brackets; you can also improve set_trace in such a way by using zip to create pairwise values of potential weights:

from collections import namedtuple

Item = namedtuple('Item', 'name value weight')

def knapsack(allowed_weight, items):
    """
    Given a list of items with name, value and weight.
    Return the optimal value with total weight <= allowed weight and
    list of picked items.
    """
    k = [
        [0 for x in range(allowed_weight + 1)]
        for x in range(len(items) + 1)
    ]

    for next_idx, (item, weights) in enumerate(zip(items, k), 1):
        for w, current_weight in enumerate(weights[1:], 1):
            if item.weight <= w:
                k[next_idx][w] = max(
                    item.value + weights[w - item.weight],
                    current_weight
                )
            else:
                k[next_idx][w] = current_weight

    return k[-1][-1], list(fetch_items(k, allowed_weight, items))

# find which item are picked
def fetch_items(k, allowed_weight, items):
    for item, weights_p, weights_n in zip(items[::-1], k[-2::-1], k[::-1]):
        if weights_n[allowed_weight] != weights_p[allowed_weight]:
            yield item
            allowed_weight -= item.weight

if __name__ == '__main__':
    items = [
        Item('A', 1, 1),
        Item('B', 4, 3),
        Item('C', 5, 4),
        Item('D', 7, 5),
    ]
    max_value, picked = knapsack(7, items)
    print("Maximum value:", max_value)
    print("Name", "Value", "Weight")
    for item in reversed(picked):
        print(item.name, ' '*2, item.value, ' '*3, item.weight)


Inconsistent method naming

Connection connection_db(String username, String password, String dbname, Connection c) {
void viewAll(String tableName, long startDate, long endDate, Connection c, String path) {

These methods have both different naming schemes, the top one uses all_lowercase_with_underscores, while the button user pascalCase. The latter is recommend in Java.

URL Injection using dbname

 c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/"
            + dbname, username, password);

You never check for special characters in the dbname. This can cause databases containing special characters to mess up your function, especially when the database can be edited though config. Escape it using URLEncoder.encode