About rollDice

The name of the function does not follow PEP 8, the Python style guide.

The name of the parameter is not that great.

You don't need 0 as a first parameter of range as it is the default behavior.

The value a_cast is not used. Usually, the name for throw-away values in Python is _.

The loop could be written in a list compregension.

After taking into account these details, your code looks like :

def roll_dice(nb_dice):
    input('> Press Enter to cast dice!')
    time.sleep(1)
    return [randint(1,6) for _ in range(nb_dice)]

About atLeastALetterInput

Here again, the name does not seem correct.

The variable is not required.

After rewriting this, code looks like :

def get_letter_from_user(text_to_display):
    try:
        return input(text_to_display)[0].lower()
    except IndexError:
        print('> Please make sure input is valid before pressing enter...')

About your first while loop

It should probably be put in a function with a signature like def get_nb_from_user(min_val, max_val):.

You could remove the need for a continue by re-organising the conditions :

    num_dice = int(input('> Enter the number of dice you would like to cast! (max 10):'))
    if num_dice in range(0,11):
        break
    else:
        print('> Please enter a value between 1 and 10! ')

Checking if an integer is in an interval by checking if it is in the result from range is not efficient at all : if you were to check if a number is between 1 and 100000000, it would take a very long time even though this should be pretty simple.

Your code becomes :

def get_nb_from_user(min_val, max_val):
    while True:
        try:
            nb = int(input('> Enter the number of dice you would like to cast! (max %s):' % max_val))
            if min_val <= nb <= max_val:
                return nb
            else:
                print('> Please enter a value between %s and %s! ' % (min_val, max_val))
        except ValueError:
            print('> Non-numerical characters detected. Try again!')

num_dice = get_nb_from_user(1, 10)

About your second while loop

To keep things simple, you should try to call get_letter_from_user from a single place.

This is quite easy to do :

while True:
    cast_again = get_letter_from_user(menu_options)
    if cast_again == 'r':
        next_cast = casts + 1
        print('> Here comes cast number {}'.format(next_cast))
        casts +=1
        cast_results_to_stats = roll_dice(num_dice)
        statistics[casts] = cast_results_to_stats
        print('> Here is your result: {}'.format(cast_results_to_stats))
    elif cast_again == 's':
        for key in statistics:
            print('> *** Cast {} resulted in {}'.format(key, statistics[key]))
    elif cast_again == 'e':
        print('> The game finished after {} casts.'.format(casts))
        print('> Good bye! ')
        input()
        break
    else:
        print('> Ups! Available options R(new cast), S(statistics) and E(exit).')

Then again, as explained in a different answer, there is no need for an ordered dictionnary as a list would do the trick.

Then your code begins (variable definition included) :

num_dice = get_nb_from_user(1, 10)
statistics = []

while True:
    cast_again = get_letter_from_user(menu_options)
    if cast_again == 'r':
        print('> Here comes cast number {}'.format(len(statistics)+1))
        cast_results_to_stats = roll_dice(num_dice)
        statistics.append(cast_results_to_stats)
        print('> Here is your result: {}'.format(cast_results_to_stats))
    elif cast_again == 's':
        for i, cast in enumerate(statistics):
            print('> *** Cast {} resulted in {}'.format(i, cast))
    elif cast_again == 'e':
        print('> The game finished after {} casts.'.format(len(statistics)))
        print('> Good bye! ')
        input()
        break
    else:
        print('> Ups! Available options R(new cast), S(statistics) and E(exit).')

Now, in Python, it is usually a good thing to move the part of your code actually doing stuff behind a main guard. Thus, your code begins :

def main():
    """Main function"""
    num_dice = get_nb_from_user(1, 10)
    statistics = []

    while True:
        cast_again = get_letter_from_user(menu_options)
        if cast_again == 'r':
            print('> Here comes cast number {}'.format(len(statistics)+1))
            cast_results_to_stats = roll_dice(num_dice)
            statistics.append(cast_results_to_stats)
            print('> Here is your result: {}'.format(cast_results_to_stats))
        elif cast_again == 's':
            for i, cast in enumerate(statistics):
                print('> *** Cast {} resulted in {}'.format(i, cast))
        elif cast_again == 'e':
            print('> The game finished after {} casts.'.format(len(statistics)))
            print('> Good bye! ')
            input()
            break
        else:
            print('> Ups! Available options R(new cast), S(statistics) and E(exit).')

if __name__ == "__main__":
    main()

Then, on top of this, you should try to add docstrings to your functions.


Python Tkinter countdown app with a freezing GUI

Tkinter is already in a loop. The window handler gets all messed up because of your own loop, which is called synchronously. Effectively you're running a loop in a loop and wonder why the outer loop takes so long to get to the next step. That's because of the inner loop taking so much time.

Long story short, your next window update will only commence once the countdown loop is finished.

There's mainly 2 ways of fixing that.

Don't loop.
Use asynchronous (or threaded) loops instead.

Basically, you'll need a function start_countdown which starts a threaded version of countdown. That would probably look something like this:

import threading

class MyFirstGUI:
    # Init and rest of methods snipped for brevity
    def refresh(self):
        self.root.update()
        self.root.after(1000,self.refresh)

    def start_countdown(self):
        self.refresh()
        threading.Thread(target=countdown).start()

Now, the countdown will be calculated in a thread that doesn't halt the current loop (the Tkinter main window). With that as basis, see if you can rebuild your countdown method. You'll see it becomes more focussed on the actual calculations and less on the screen.

Please see this answer on Stack Overflow for the complete story on how to work with Tkinter and calls that would ordinarily block.


Replacing each string of one or more blanks by a single blank

Looks fine to me.  But I would replace

if (inspace == 0)

with

if (!inspace)

for stylistic reasons. And

if (c != ' ')

with

else

because there is no need to compare c again: you already know it isn't equal to a space because of the first if statement.

Also the code inside {...} after main should be indented over.


Handling multiple try-catches in a for loop

You need anything here but a try catch.
foreach($data as $key => $row) {
    // $row['tower'] = 'Hello World Tower'
    // Try to see if $row['tower'] is present in the $towers data source
    if (isset($towers[$row['tower']])) {
        $data[$key]['tower'] = $towers[$row['tower']];
    } else {
        $error_holder[$key]['tower_error'] = "Tower not found for $key";
    }

    if (isset($departments[$row['department']])) {
        $data[$key]['department'] = $departments[$row['department']];
    } else {
        $error_holder[$key]['tower_error'] = "Department not found for $key";
    }
}

Although you can reduce the duplication by storing sources into array and looping over it but honestly it makes the code so muddled that I don't see the benefit.
foreach (compact('tower','department') as $name => $column)
    foreach($data as $key => $row) {
        if (isset($column[$row[$name]])) {
            $data[$key][$name] = $column[$row[$name]];
        } else {
            $error_holder[$key][$name.'_error'] = "$name not found for $key";
        }
    }
}


This (and reflection in general) completely breaks refactoring, static code analysis and many more things and should therefore be avoided. (Imagine what happens if you find out a better naming for a function or you change the arguments.)

If you really need this behavior, you could use (I assume jUnit 4+) hooks before and after class/test case:

@BeforeClass
public static void setUpBeforeClass() throws Exception {
}

@AfterClass
public static void tearDownAfterClass() throws Exception {
}

@Before
public void setUp() throws Exception {
}

@After
public void tearDown() throws Exception {
}

and do whatever is necessary.
Besides this, as already written, I would suggest to modify your methods, too. It could be a better approach to separate the view (prints) from model/controller (functions doing something).


Divide all elements in the column of a sparse matrix

When trying to speed up Numpy code, it's important to scrutinize every loop. A loop that has to run in the Python interpreter can be hundreds of times slower than a vectorized loop running inside Numpy.

Also, when trying to improve the performance of code, there's no substitute for measurement. So let's set up a test case. The matrix csc here has the same density as yours, but is one-hundredth the size (to make the runtimes tractable):

import numpy as np
from scipy.sparse import csc_matrix
from timeit import timeit

shape = 40000, 50000
density = 0.0005
n = np.prod(shape) * density
rowi, coli = [np.random.randint(s, size=n) for s in shape]
csc = csc_matrix((np.random.rand(n), (rowi, coli)), shape=shape)

Here's your sum-of-squares-by-column algorithm:

def sum_squares_by_column_1():
    maxv = np.zeros((csc.shape[1]))
    for i in range(csc.shape[1]) :
        maxv[i] = sum(np.square(csc[:,i].data))
    return maxv

>>> timeit(sum_squares_by_column_1, number=1)
19.718280024942942

So how can we get rid of that for loop? Well, if this were an ordinary Numpy array then we could write:

np.sum(np.square(csc), axis=1)

but this doesn't work here because scipy.sparse.csc_matrix is a matrix rather than an array (see the answers to this Stack Overflow question) and so np.square doesn't work. That's because np.square(a) just multiplies a by itself (as if you'd written a * a), and this is matrix multiplication when a is a matrix.

So what we need to do instead is to read carefully through the scipy.sparse.csc_matrix documentation to see if there are methods for the operations we need. There's no square method, but there is a multiply method that does "point-wise multiplication" and a sum method that "sums the matrix over the given axis". So, putting these together:

def sum_squares_by_column_2():
    return csc.multiply(csc).sum(1)

>>> timeit(sum_squares_by_column_2, number=1)
0.04036429896950722

which is about 500 times faster.


Validating files and returning errors messages/boolean values

Some notes:

The boolean validate(...) method never returns false so it should be void method.
I'd pass immutable ValidationResult objects to the clients. The clients could check the results and could signal to their clients if there is an error or prints the messages etc.
I'd omit the &= operator, it's really hard to read.
getTotalMaxFilesSize() should be in the FileSystemSettings class. (Feature or data envy smell.)

After a few refactoring steps the following came out:

AttachmentValidatorService.java

import java.util.List;

public interface AttachmentValidatorService {

    ValidationResult validate(List<Attachment> attachments);

    ValidationResult validate(Attachment attachment);

    long getTotalMaxFilesSize();
}

ValidationResult.java

import static com.google.common.base.Preconditions.checkNotNull;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.concurrent.Immutable;

@Immutable
public class ValidationResult {

    private final List<String> errors;

    public ValidationResult(final List<String> errors) {
        checkNotNull(errors, "errors cannot be null");
        this.errors = new ArrayList<String>(errors);
    }

    public boolean isValid() {
        if (errors.isEmpty()) {
            return true;
        }
        return false;
    }

    public List<String> getErrors() {
        return new ArrayList<String>(errors);
    }

    // If lots of the clients use this
    //  public void checkErrors() {
    //      if (!isValid()) {
    //          throw new ...
    //      }
    //  }
}

AttachmentValidatorServiceImpl:

import static com.google.common.base.Preconditions.checkNotNull;

import java.util.Collections;
import java.util.List;

public class AttachmentValidatorServiceImpl implements
        AttachmentValidatorService {
    private final FileSystemSettings messageSettings;

    public AttachmentValidatorServiceImpl(
            final FileSystemSettings messageSettings) {
        this.messageSettings = checkNotNull(messageSettings,
                "messageSettings cannot be null");
    }

    @Override
    public ValidationResult validate(final List<Attachment> attachments) {
        final AttachmentValidator attachmentValidator = new AttachmentValidator(
                messageSettings, attachments);
        return attachmentValidator.getValidationResult();
    }

    @Override
    public ValidationResult validate(final Attachment attachment) {
        return validate(Collections.singletonList(attachment));
    }

    @Override
    public long getTotalMaxFilesSize() {
        return messageSettings.getMaxFilesCount()
                * messageSettings.getMaxFileSize();
    }
}

AttachmentValidator.java

import static com.google.common.base.Preconditions.checkNotNull;

import java.util.ArrayList;
import java.util.List;

public class AttachmentValidator {

    private final List<String> errors = new ArrayList<String>();

    private final FileSystemSettings messageSettings;

    public AttachmentValidator(
            final FileSystemSettings messageSettings,
            final List<Attachment> attachments) {
        this.messageSettings = checkNotNull(messageSettings,
                "messageSettings cannot be null");
        checkNotNull(attachments, "attachments cannot be null");
        for (final Attachment attachment : attachments) {
            validate(attachment);
        }

        validateSize(attachments);
    }

    private void validate(final Attachment attachment) {
        validateNull(attachment);
        validateLimitExceeded(attachment);
    }

    private void validateSize(final List<Attachment> attachments) {
        if (attachments.size() > messageSettings.getMaxFilesCount()) {
            errors.add("Attachments max number exceeded.");
        }
    }

    private void validateLimitExceeded(final Attachment attachment) {
        if (attachment == null) {
            return;
        }
        final int fileSize = attachment.getFileSize();
        final boolean exceeded = fileSize > messageSettings
                .getMaxFileSize();
        if (exceeded) {
            final String fileDisplayName = attachment
                    .getFileDisplayName();
            final int fileSizeInMegaBytes;
            if (fileSize == 0) {
                fileSizeInMegaBytes = 0;
            } else {
                fileSizeInMegaBytes = fileSize / 1024 / 1024;
            }
            final String errorMsg = "Max file size limit exceeded. File: "
                    + fileDisplayName
                    + ". Size: "
                    + fileSizeInMegaBytes + "MB.";
            errors.add(errorMsg);
        }
    }

    private void validateNull(final Attachment attachment) {
        if (attachment == null) {
            errors.add("No attachment.");
        }
    }

    public ValidationResult getValidationResult() {
        return new ValidationResult(errors);
    }

}

Feel free to ask if you have any questions.


Javascript obj assignment/mutation in for-loops

I think this is what you're looking for

const uuidGenerator = () => Math.random();

const message = {
  message: 'hello',
  recipients: ['John', 'Susie', 'Christian'],
};

function split(obj) {
  const { message, recipients, ...remaining } = obj;
  return recipients.map((recipient) => {
    return { id: uuidGenerator(), message, ...remaining, recipient: recipient };
  });
}

const arrOfMessages = split(message);
console.log(arrOfMessages);

if there are too many values that you want to copy from the actual obj, then you can use the spread operator i.e., remaining in this case.

However, I am not sure about how efficient this is. These are possible approaches:
- Object.assign
- Spread Operator
- manually adding keys to base Object
Because, I have seen instances where each of these perform differently based on the sample size.

I remember that last approach is faster if your sample size is huge.


Checking if len(num) >= 5 is redundant because you only call the function with k < 10**5
Instead of sorted([int(x) for x in num]) you could compute just sorted(num) and compare that to a DIGITS = [str(i) for i in range(1, 10)] constant that you can compute outside the function.
Most of the multiples end up longer than 9 digits. Testing len(num) == 9 before sorting the digits should be faster.
You could take advantage of the example 918273645 provided in the problem statement. The number you are looking for must be greater or equal to that. For one thing, the first two digits must be in range 91 to 98, which is a small fraction of all the two-digit numbers you try.


I'm not going to suggest any major Typescript features you aren't using, as it looks like you don't need any here. Additionally, I'm not going to claim any of my following questions / suggestions are "best practices" as "best practices" seem to change annually at a minimum in the web development world.

Why are you defining an interface for a single object? I don't see any reason to burden yourself with maintaining multiple definitions. You can include the method definitions within the module itself to save yourself from scrolling back up to the interface to check what the definition should be.

This is more of a stylistic preference, but I see no need to preface your methods with square. Since you are accessing the method on the squareWidget object it seems redundant to include square a second time.

When squareWidget is created, the list of squares is immediately created. This is a problem as if you include your code before the HTML has finished loading, the squares added before calling squareWidget.init(), but after the code is parsed will be missed.

In your squareSizer function, you use a dataset value which is not set by the init function. If the value is missing, the method won't do anything. When creating a square, should I have to remember to specify if it is enlarged or not every time? Also, is the dataset used in any code not included in your post? If not, you could replace your checks with the built in classList.toggle()

In squareColorChanger, instead of looping through the classes on the element, it might be better to check for and remove the color classes specified by the module. You can even take this a step further and just use el.classList.remove(...squareWidget.squareColors)

In doSquareClick I expected to see code that handled a click. Instead, the method adds an event listener to the element. Perhaps addListener would be more descriptive? In addition to this, your method asks for more arguments than it uses. You can safely remove the index and array arguments with no effect to your code.

In init the Array.from is unnecessary in newer browsers. forEach is included on NodeLists. Despite this, I would leave it as is until IE dies out completely. One concern I have with the current function is that if I call it twice, two event listeners will be added on all elements. If I add squares to the page after it has loaded due to user interaction I need to call the init method again to activate them which then breaks the existing squares. You could solve this problem several ways. My personal choice would likely be defining a single event listener method which is added on all squares. With this change, calling addEventListener again will have no effect.


Detecting a certain amount of violet in an image - follow-up

this.button2.Click += async (sender, e) =>
{
    Task task = Task.Run(() =>
    {
      ProcessImage(pictureBox1.Image);
    });
      Task.WaitAll(task);
      await task;
    };
}

Is the indentation like that in the original, or did it get corrupted by the tab-to-space conversion of StackExchange?

What's going on with the task? I don't know much about async event handlers, but as far as general async/await usage you only need one of Task.WaitAll(task) or await task.

What stops me from mashing the button and spinning off loads of tasks? Normally you would want to prevent a second click by opening a modal dialog (denying access to the button) or disabling the button, and then using ContinueWith to undo the block in the GUI thread when the task finishes.

    private void ProcessImage(Image image)
    {
        if (image == null)
        {
            return;
        }
        using (var selectedImage = new Bitmap(image))

If the image is already a bitmap, this is unnecessary and slow. It's probably worth having two cases and factoring out the code which works with Bitmap to a separate method:

    if (image is Bitmap) Process(image as Bitmap);
    else using (var bitmap = new Bitmap(image)) Process(bitmap);

            double total = 0;
            double infected = 0;

That's an odd choice for counters. Why not use an integer type and coerce to double when dividing?

            for (int x = 0; x < selectedImage.Width; x++)
            {
                for (int y = 0; y < selectedImage.Height; y++)
                {
                    selectedPixel = selectedImage.GetPixel(x, y);

This is slow. A loop over GetPixel is always slow, and it's worse when the outer loop is over x because you lose cache locality. If you care about speed, use LockBits and switch the loops.

                    if (selectedPixel.GetHue() == (violet.GetHue()))

GetHue() returns a float. == comparisons on non-integer numeric types are generally inadvisable. You should almost certainly test whether selectedPixel.GetHue() is within a small distance of violet.GetHue(). How wide a range is a parameter which you may need to tune to get the results you expect.

                if (Double.TryParse(Convert.ToString(percentage).Substring(0, 6), out result))

??! Why? And if the specs require you to round to an exact number of decimal places and that's non-negotiable, why use double instead of decimal?

            catch
            {
                MessageBox.Show("No Violet Pixels Whatsoever were found");
            }

Under what circumstances can this catch anything? The only one I can see is if total == 0, in which case the error message should really be that the image was empty.

            finally
            {
                selectedImage.Dispose();
            }

This is unncessary: it's already in a using statement.


If I had to put a number on your code it would be a 8 out of 10. You did good here. Since it is so good I am going to be nitpicking a few things. First is your test. You are comparing arrays but using assertEquals. Instead you need to change that to assertArrayEquals (providing you are using JUnit 4.0) The other thing I feel you need to test for is no begin and no end delimiters.

The other nitpicking thing I can find is in your split method. I know that you referred to not using the String.split method, but your method does the same thing. For this exercise there is nothing wrong with giving it the same name seeing as it does the same thing. One thing that annoys me a small amount is the making a while or if statement do more than one thing. Are you assigning or are you comparing? The convention for while and if is to compare only. So move your assignment out of those functions. I'm going to paste your code multiple times and I revise it, so here is where I am sitting now on your code.

public static String[] split(String from, char startDelimiter, char endDelimiter)
{
    int startPos = 0;
    ArrayList<String> list = new ArrayList<>();

    int index = from.indexOf(startDelimiter, startPos);

    while (index != -1)
    {
        int endPos = from.indexOf(endDelimiter, index);
        if (endPos != -1)
        {
            list.add(from.substring(index, endPos + 1));
            startPos = endPos;
        }
        else
        {
            break;
        }
        index = from.indexOf(startDelimiter, startPos);
    }
    return list.toArray(new String[list.size()]);
}

Notice that it introduces some duplication with assigning index. Since you have passing tests that means we can refactor a little bit. Now I know you are probably thinking that the reason you put the assignment in the while loop was to remove duplication. Before we address that though lets attack some of your naming. Index. Normally this is a good choice of words to use, but index usually refers to a location in an array. Although a string is an array of characters in this context it is not the exact definition of an index. So I believe a more appropriate name would be startDelimiterLocation , startLocation , or even startLookigFrom this would allow us to make a sentence out of our while and if statments by giving -1 a name such as NotFound or since it is a constant NOTFOUND.

public static String[] split(String from, char startDelimiter, char endDelimiter)
{
    int fromIndex = 0;
    ArrayList<String> list = new ArrayList<>();

    int startPosistion = from.indexOf(startDelimiter, fromIndex);

    while (startPosistion != NOTFOUND)
    {
        int endPosistion = from.indexOf(endDelimiter, startPosistion);
        if (endPosistion != NOTFOUND)
        {
            list.add(from.substring(startPosistion, endPosistion + 1));
            fromIndex = endPosistion;
        }
        else
        {
            break;
        }
        startPosistion = from.indexOf(startDelimiter, fromIndex);
    }
    return list.toArray(new String[list.size()]);
}
private static final int NOTFOUND = -1;

This gives us the ability to read the code outloud if we wanted (while startPosistion is not not found) (yes i know it's a double negative, but well.. this isn't English. Well that gives me an idea.. Lets make that into an actual sentance, and have it return a boolean.

private static boolean stringHasStringBetweenTwoCharacters(String from, char startDelimiter, char endDelimiter)
{
    int startPosistion = from.indexOf(startDelimiter);
    if (startPosistion == NOTFOUND) return false;

    int endPosistion = from.indexOf(endDelimiter, startPosistion);
    return (startPosistion != NOTFOUND && endPosistion != NOTFOUND);
}

this allows me to rewrite my while method to this. while (stringHasStringBetweenTwoCharacters(from, startDelimiter, endDelimiter)) but this makes the tests fail because my method is not looking at where we left off in our string. I removed it on purpose because I wanted this method to only find the first occurrence of a string in between 2 characters. So this means I have to change the logic slightly. Instead of keeping track of where we are in the string, lets just remove up to the endPosistion and leave the rest.

public static String[] split(String from, char startDelimiter, char endDelimiter)
{
    ArrayList<String> list = new ArrayList<>();

    while (stringHasStringBetweenTwoCharacters(from, startDelimiter, endDelimiter))
    {
        int startPosistion = from.indexOf(startDelimiter);
        int endPosistion = from.indexOf(endDelimiter, startPosistion);
        if (endPosistion != NOTFOUND)
        {
            list.add(from.substring(startPosistion, endPosistion + 1));
            from = from.substring(endPosistion + 1);
        }
        else
        {
            break;
        }
    }
    return list.toArray(new String[list.size()]);
}
private static boolean stringHasStringBetweenTwoCharacters(String from, char startDelimiter, char endDelimiter)
{
    int startPosistion = from.indexOf(startDelimiter);
    if (startPosistion == NOTFOUND) return false;

    int endPosistion = from.indexOf(endDelimiter, startPosistion);
    return (startPosistion != NOTFOUND && endPosistion != NOTFOUND);
}
private static final int NOTFOUND = -1;

so now my tests pass again. Oh but I have duplication again, but no longer in the start position, now it is in the end position. Since I know it is there I can remove the check in my while loop and make a slight adjustment in my duplicate change in index. My final outcome is something like this.

public static String[] split(String from, char startDelimiter, char endDelimiter)
{
    ArrayList<String> list = new ArrayList<>();

    while (stringHasStringBetweenTwoCharacters(from, startDelimiter, endDelimiter))
    {
        int startPosistion = from.indexOf(startDelimiter);
        int endPosistion = from.indexOf(endDelimiter, startPosistion) + 1;
        list.add(from.substring(startPosistion, endPosistion));
        from = from.substring(endPosistion);
    }
    return list.toArray(new String[list.size()]);
}
private static boolean stringHasStringBetweenTwoCharacters(String from, char startDelimiter, char endDelimiter)
{
    int startPosistion = from.indexOf(startDelimiter);
    if (startPosistion == NOTFOUND) return false;

    int endPosistion = from.indexOf(endDelimiter, startPosistion);
    return (startPosistion != NOTFOUND && endPosistion != NOTFOUND);
}
private static final int NOTFOUND = -1;

Now my methods only do one thing, and it does them well. I moved the logic of how to check to see if my string still contains a token into its own method which leave only the logic of adding my tokens to my arrayList. It may seem a little more verbose, but in my opinion is easier to read


Map a hierarchy of nested DTO objects to a list of business objects

The first thing you can do is assign all the properties for a thing in one line using an object initializer.  The following:

var cThing = new CThing();
cThing.CID = cThingDto.CID;
cThing.CName = cThingDto.CName;

would become:

var cThing = new CThing {CID = cThingDto.CID, CName = cThingDto.CName};

You can create a list before creating the parent thing so you can assign in the object initializer.  I don't think your code works currently because you're not specifying the DTO in the foreach loops and not getting the values from the dictionary that's passed in.  If the object initializer is too long, you can expand it to multiple lines or create and use a constructor for each class.

public List<AThing> MapFromDTO(Dictionary<int, AThingDTO> dtoThingsHierarchy)
{
    var mappedThings = new List<AThing>();

    foreach (var aThingDto in dtoThingsHierarchy.Values)
    {
        var aThing = new AThing {AID = aThingDto.AID, AName = aThingDto.AName};
        foreach (var bThingDto in aThingDto.BThingsColl.Values)
        {
            var bThing = new BThing {BID = bThingDto.BID, BName = bThingDto.BName};
            foreach (var cThingDto in bThingDto.CThingsColl)
            {
                var cThing = new CThing {CID = cThingDto.CID, CName = cThingDto.CName};
                bThing.CThingsColl.Add(cThing);
            }
            aThing.BThingsColl.Add(bThing);
        }
        mappedThings.Add(aThing);
    }
    return mappedThings;
}

Here's one way to rewrite your code using LINQ's method syntax:

public List<AThing> MapFromDTO(Dictionary<int, AThingDTO> dtoThingsHierarchy)
{
    return dtoThingsHierarchy.Values
        .Select(a => new AThing {AID = a.AID, AName = a.AName, BThingsColl = a.BThingsColl.Values
            .Select(b => new BThing{ BID = b.BID, BName = b.BName, CThingsColl = b.CThingsColl
                .Select(c => new CThing {CID = c.CID, CName = c.CName}).ToList()}).ToList()}).ToList();
}

Here's LINQ's query syntax:

public List<AThing> MapFromDTO(Dictionary<int, AThingDTO> dtoThingsHierarchy)
{
    return
       (from a in dtoThingsHierarchy.Values
        let bThings =
           (from b in a.BThingsColl.Values
            let cThings = b.CThingsColl.Select(c => new CThing {CID = c.CID, CName = c.CName}).ToList()
            select new BThing{ BID = b.BID, BName = b.BName, CThingsColl = cThings }).ToList()
        select new AThing {AID = a.AID, AName = a.AName, BThingsColl = bThings}).ToList();
}

Both LINQ methods are quite a bit shorter, but the tradeoff in this case is they're kind of tough to read.  Moving logic to the constructors could help.


Codility MaxCounters peformance in Python capping out at 77% performance

What hurts your performance is filling the array with max_count. So don't do it. Imply it. The trick is all there, and it makes this slightly different from trying to execute a literal transcription of the problem.

Spelling out the details would rob pundits of the enjoyment of puzzling...

I don't know about Codility, but elsewhere the tasks can often be solved with efficient coding of a naive algorithm (especially in C/C++) instead of solving the puzzle algorithmically. Sometimes I try the 'raw firepower' solution as well, if it promises an interesting challenge. But only after finding the real solution, since each puzzle is basically about finding a specific trick that goes beyond the naive algorithm.

Given that people do these challenges for the puzzle value I think it would defeat their purpose if we posted complete solutions.

P.S.: the sketched solution reduces runtime only to M * log(M) + N or M * C + N but that should be sufficient (and enough of a hint).


__iter__ and __next__
Instead of re-opening the file each time and seeking to the previous position, you could write __iter__ as a generator function by using yield instead of needing to define __next__. Something like:
def __iter__(self):
    with open(file) as f:
        yield from f

Error handling
In case of error, you're returning a string 'Cant read next line'.
What if you have a file that contains text 'Cant read next line'? How do you differentiate between these?
Well... you can't.
Instead of returning a string, throw an exception on error - that's what exceptions are meant for.
Also, this error message of yours isn't really correct. You most likely get IOError when opening a file... before even attempting to read first line from it.
It seems like your error handling code doesn't really do anything very useful with the IOError. So why not instead just let it bubble upwards and drop the try-catch block completely.
Duplication
You can define your own open method, so you don't have to repeat passing the file_path to it:
def open(self, mode='r'):
    open(self.file_path, mode)

You could also investigate writing you own context manager for opening the file with your custom error handling.


"Digit Queries" CSES Solution giving TLE

Building or iterating the whole string takes far too long. Instead group the numbers by length:
length 1 digit:  1 to 9 -> 9 numbers => 9 digits total
length 2 digits: 10 to 99 -> 90 numbers => 180 digits total
length 3 digits: 100 to 999 -> 900 numbers => 2700 digits total
length 4 digits: 1000 to 9999 -> 9000 numbers => 36000 digits total
etc

The number of digits per group (9, 180, 2700, 36000, etc) are easy to compute. Skip these groups of equal-length numbers until you reach the right group (the remaining k falls into it). Then just compute the right number inside the group and get the right digit from it.
for _ in range(int(input())):
    k = int(input())

    length = 1
    while k > 9 * 10**(length-1) * length:
        k -= 9 * 10**(length-1) * length
        length += 1
    q, r = divmod(k-1, length)
    print(str(10**(length-1) + q)[r])

Takes about 0.03 seconds of the allowed 1 second.
Or keeping 10**(length-1) in a variable for less duplication:
for _ in range(int(input())):
    k = int(input())

    length = first = 1
    while k > 9 * first * length:
        k -= 9 * first * length
        length += 1
        first *= 10
    q, r = divmod(k-1, length)
    print(str(first + q)[r])


First off, make it more maintainable: break out that long list comprehension into a for loop so it's clearer where line is coming from.

As for optimization, since size_list_situation_ids doesn't change through the loop, you can refactor those trinary ops into functions and then set them just once at the beginning:

if size_list_situation_ids:
    prev_amount_ht = lambda l: l.cumulative_amount_ht
    amount_net_ht = lambda l, l1: l.cumulative_amount_ht - l1.cumulative_amount_ht
else:
    prev_amount_ht = lambda l: 0
    amount_net_ht = lambda l, l1: l.cumulative_amount_ht

and then do:

...
'previous_amount_ht': prev_amount_ht(line1),
'amount_net_ht': amount_net_ht(line, line1),
...

which saves a couple of comparisons every time through the loop.

Much more than that is difficult to suss out, since the code looks non-functional overall: where does situation_orders come from? Why is the initial task_lines even being loaded, as it doesn't seem to be used?


Strings in Python are immutable, and so 'string a' + 'string b' has to make a third string to combine them. Say you want to clone a string, by adding each item to the string will get \$O(n^2)\$ time, as opposed to \$O(n)\$ as you would get if it were a list.

And so, the best way to join an iterable by a separator is to use str.join.

>>> ','.join('abcdef')
'a,b,c,d,e,f'

If you want to do this manually, then I'd accept the \$O(n^2)\$ performance, and write something easy to understand. One way to do this is to take the first item, and add a separator and an item every time after, such as:

def join(iterator, seperator):
    it = map(str, iterator)
    seperator = str(seperator)
    string = next(it, '')
    for s in it:
        string += seperator + s
    return string


First, I don't think the close() method is following the contract, from the javadoc:

  It is a programming error to append to a closed appender.

Therefore, your close() method should be implemented like this:

@Override
public void close() {
    this.closed = true;
}

Note that closed is a protected field in AppenderSkeleton.

Then, change append to something like (add the @Override as well):

@Override
public void append(LoggingEvent event) {
    if (!this.closed) {
        ArrayList<LoggingEvent> buffer = new ArrayList<LoggingEvent>();
        buffer.add(event);
        flushBuffer(buffer);
    } else {
        // It is a programming error to append to a closed appender.
        throw new RuntimeException("Attempting to append to a closed Appender.");
    }
}

Next, does flushBuffer need to be public? It should probably be private.

Finally—and this is more of a nitpick—you don't need to declare the default constructor since it's empty and the compiler will create one for you. It'll make your code a little cleaner as well.


First thoughts:

The user is prompted to enter the class number after taking the test, and if it's not a valid number the program exits. This means they lose the results of the test. You could ask that question up front.

There's a large gap between the check to see if status is '1' and to see if status is '2'. I'd put the code for the student and teacher in functions, so that the result looks more readable:

def student_questions():
    pass

def teacher_questions():
    pass

if status == "1":
     student_questions()
elif status == "2":
     teacher_questions()

There's a lot of prompting the user for input and then checking to see if it's valid - that could easily be a function.

def ask_question(question, valid_answers):
    while ...
         print ...
         input ...
         if input is valid: return input

The only other comment I'd make straight away is that while choosing the operation at random works, it does mean that one student might get all divisions, others get a broad selection, and so on. Perhaps there needs to be a check to make sure that each student gets at least one of every type? Or a non-random selection?


Is the goal to get a string containing the content of the file? or to add the content of a file to an existing StringBuilder?

if it's the former then Option 1 can drop the string builder altogether ... or better yet.

string value = File.ReadAllText("C:\A big file.txt");

if it's the latter then you might want to think about using StringBuilder.EnsureCapacity() to avoid the overhead of resizing the buffer more then it needs to.


You say you need the extra class, "due to how __sub__() was implemented"; because it returns a vanilla list, with a list comprehension. However, note:

If you replace e.g.

return [elem - value for elem in self]

with:

return _BaseList(elem - value for elem in self)

__sub__ will return a _BaseList instead; and
If you put those four methods in one class calling normalize would still work anyway, because you do convert to _BaseList after the subtraction.

In fact, three methods, because the __init__ is redundant - if all your subclass method does is call the superclass version, you can just let Python handle that for you.

The Zen of Python states that

  Errors should never pass silently.

However, in both __truediv__ and __sub__, if value is not one of the three specified types (or it's a list of the wrong length), they quietly return None. Instead, you should raise TypeError if the user passes a value that can't be handled.

Speaking of specified types, don't write things like:

if type(value) in (int, float)

If you need to check types, use isinstance - this supports inheritance better:

if isinstance(value, (int, float)):

This is particularly important when you're using inheritance yourself - what happens if you try to subtract a _BaseList from another _BaseList? Python supplies abstract base classes that can help make this usage more generic.

Also note that there is another numeric type: complex - as Mathias Ettinger pointed out in the comments you can use Number when you want to cover all three cases.

There's a lot of duplication between the __sub__ and __truediv__ implementations; you could factor this out by extracting to a method that also takes the operator to apply, then use the operators defined in operator.

from collections.abc import Sequence
from operators import sub, trudiv

class Array(list):

    def normalize(self):
        min_ = min(self)  # calculate this once
        return (self - min_) / (max(self) - min_)

    def __sub__(self, other):
       return self._process(other, sub)

    def __truediv__(self, other):
       return self._process(other, truediv)

    def _process(self, other, op):
        if isinstance(other, Sequence):
            if len(other) == len(self):
                return Array(op(a, b) for a, b in zip(self, other))
            raise ValueError('cannot operate on a sequence of unequal length')
        return Array(op(a, other) for a in self)

In use:

>>> a = Array((7, 8, 9))
>>> a
[7, 8, 9]
>>> a - 2
[5, 6, 7]
>>> a - [1, 2, 3]
[6, 6, 6]
>>> a.normalize()
[0.0, 0.5, 1.0]
>>> a - 'abc'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in __sub__
  File "<stdin>", line 12, in _process
  File "<stdin>", line 12, in <genexpr>
TypeError: unsupported operand type(s) for -: 'int' and 'str'
>>> a - [1, 2, 3, 4]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in __sub__
  File "<stdin>", line 13, in _process
ValueError: cannot operate on a sequence of unequal length

It might also be worth implementing __repr__, so you can tell more easily when you have a vanilla list and when you have an Array.


This is the real bad practice.

The Ajax is Asynchronous, you never know how the response will back.
Javascript is the single thread language, so that means in one time period just can run one function. in your repeatUseAjax function, you try to loop send ajax. the result will be you will send 5 times ajax call every time when the ajax response failure.And you will never know when the response suceess. what about first failure other success? what about always failure?loop forever?


Initialize various commands for the SqlDataAdapter

With the following, you'll only add each parameter a single time and just change the command text before assigning it to the adapter command, allowing you to reuse the existing cmd object.

using (SqlDataAdapter birdDataAdapter = new SqlDataAdapter())
{
    SqlCommand cmd = new SqlCommand("DELETE FROM [dbo].[BirdCount] WHERE [BirdID] = @BirdID; DELETE FROM[dbo].[Bird] WHERE[BirdID] = @BirdID",conn);
    cmd.Parameters.Add("@BirdID", SqlDbType.NVarChar, 10, "BirdID");

    birdDataAdapter.DeleteCommand = cmd;

    cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 50, "Name");
    cmd.Parameters.Add("@Description", SqlDbType.NVarChar, 200, "Description");

    cmd.CommandText="INSERT INTO [dbo].[Bird] ([BirdID], [Name], [Description]) VALUES (@BirdID, @Name, @Description)";
    birdDataAdapter.InsertCommand = cmd;

    cmd.CommandText= "UPDATE [dbo].[Bird] SET [BirdID] = @BirdID, [Name] = @Name, [Description] = @Description WHERE [BirdID] = @BirdID";
    birdDataAdapter.UpdateCommand = cmd;

    rowsAffected = birdDataAdapter.Update(pDataSet, "Bird");

    return rowsAffected;
}


You should definitely separate the calculation from formatting the output. One of Haskell's key strengths is being able to compose functions. By confounding the definition of your function with the presentation of it's return value, you lose the ability to reuse it elsewhere. For instance, if you wanted to use my_sum to sum all of the numbers you were given, and then find the factorial of the sum, you couldn't with your code as-is without reimplementing both functions! Here's a composable definition of my_sum.

my_sum xs = foldr (+) 0 xs

Now when you want to write out to the command line what operation your program has performed, you can format the output in IO, or call a formatting operation (that's what show is).

main = do
    ...
    putStrLn $ "The sum of the numbers you entered is " ++ show (sum numList)
    ...

Now more general advice, you should include a type signature for all of your top-level definitions. This is important for a few reasons. One, it acts as a check on your understanding of what your functions are doing, the compiler will complain if your signature doesn't match what your function really does. Two, it serves as a surprisingly powerful form of documentation for readers of your code. And three, it can help the compiler infer more of the types you use within functions without needing annotations.

As an example of that last point, look at how you had to annotate the line let n = read number with :: Int. If you had given the compiler enough information to go on elsewhere in your program, it would have been able to deduce that on its own. Here's how.

getNumbers :: IO [Int] -- 1) Type signature for the IO action
getNumbers = do
  number <- getLine
  let n = read number -- 3) The type checker sees that n is a part of the returned list, so it must be an Int
  if n == 0
    then do
      return []
    else do
      numList <- getNumbers
      return (n : numList) -- 2) Here's the list of Ints we're returning per the type signature

You shouldn't have to set stdin to LineBuffering mode at the start of main. getLine will work correctly by default.

getNumbers isn't properly tail-recursive, the recursive call to getNumbers is followed by that return action. In this example it won't make much of a difference, but in a real program where you can expect a large amount of data this would end up blowing up the stack.

Here's the version I ended up producing taking all of the above into account. Read closely and try to make note of all the differences between both versions!

module Main where

main :: IO ()
main = do
    putStrLn "Enter one number per line, or 0 to stop: "
    numbers <- getNumbers
    putStrLn "The sum of your numbers is " ++ show (my_sum numbers)
    putStrLn "The product of your numbers is " ++ show (my_sum numbers)
    forM_ numbers $ \n -> putStrLn "The factorial of " ++ show n ++ " is " ++ show (fac n)

getNumbers :: IO [Int]
getNumbers = do
    number <- getLine
    let n = read number
    if n == 0
        then return []
        else fmap (n:) getNumbers

my_sum :: [Int] -> Int
my_sum = foldr (+) 0

my_product :: [Int] -> Int
my_product = foldr (*) 1

fac :: Int -> Int
fac 1 = 1
fac n = n * fac (n - 1)


Idea seems nice but for me it's quite hard to follow. Don't get me wrong, it might just be me!

But could you achieve the same functionality A proceeds when B has done it's thing just by passing a callback function in your broadcasted/emitted event?

angular.module('moduleA', ['moduleB'])
  .controller('OneCtrl', function($scope, $rootScope) {
    // broadcast event
    $scope.send = function() {
      console.log('broadcast event');
      $rootScope.$broadcast('event:my-event', callback);
    };

    // event callback
    var callback = function(result) {
      console.log('callback', result);
    };
  });

angular.module('moduleB',[])
  .controller('TheOtherCtrl', function($scope, $q, $timeout) {
    // receive event
    $scope.$on('event:my-event', function(event, callback) {
      console.log('received', event.name);
      // execute callback with process result
      process(true).then(callback, callback);
    });

    // some async processing
    function process(success) {
      return  $timeout(function() {
        return success ? $q.when(true) : $q.reject(false);
      }, 800);
    }
  });

  broadcast event
  received event:my-event
  callback true


Cleaner way to handle double pointer in C++ BST?

If you're trying to learn C++, you should get comfortable with constructors and destructors — they're what C++ is all about!

struct Node
{
    int data;
    Node *left, *right;
};

// A utility function to create a new BST node
Node* newNode(int data)
{
    Node *temp =  new Node();
    temp->data = data;
    temp->left = NULL;
    temp->right = NULL;
    return temp;
}

That's C style. C++ style would be:

struct Node {
    int data_;
    Node *left_ = nullptr;
    Node *right_ = nullptr;

    explicit Node(int data) : data_(data) {}
};

Then when you want a new heap-allocated node, you don't call newNode(42) — you call new Node(42)! Or, a good habit you should get into: call std::make_unique<Node>(42) to get back a smart pointer.

Notice that I added sigils to your data members (data_ etc) to distinguish them from non-member variables; and I declared no more than one variable per line to reduce reader confusion.

void inorder(Node *&root)
{
    if (root != NULL)
    {
        inorder(((root)->left));
        printf("%d \n", (root)->data);
        inorder(((root)->right));
    }
}

Several things weird here. First, you have a bunch of unnecessary parentheses. (root) is the same thing as root. Second, you're passing root by non-const reference, even though you don't intend to modify it. Third, very minor nit, you're using C-style NULL instead of nullptr. Fourth, why do you print a space before the newline? Fixed up:

void inorder(const Node *root)
{
    if (root != nullptr) {
        inorder(root->left);
        printf("%d\n", root->data);
        inorder(root->right);
    }
}

Remember to remove the redundant parentheses in places like insert(((node)->right),value). It's much easier to read as insert(node->right, value).


Function that returns the earliest time point when a worker is allowed to start duty

Why not just use <stdbool.h> instead of defining your own enum for it?  If it has to do with the standard being used, then make sure you're compiling under C99 or GNU99.
It looks like t and t2 are for testing and more could be added at some point.  If so, you could have an array of TimeStamps to help make the code more concise.
isNeededLocalNightsInTheRange() can be simplified as such:

return 2 <= neededLocalNights && neededLocalNights <= 5;

This will automatically return the appropriate condition.
Try to avoid magic numbers by instead making them into constants.  This would apply to the 2, 8, 6, 5, and 0 (the -1 indicates an error and doesn't apply here).  Comments aren't always helpful enough and don't explain each of these anyway.
Error messages should be printed to fprintf() with its first argument as stderr to indicate this.  printf only prints to standard output.


You should change searchRange to search_range as per PEP8, Python's style guide.
If this is Python2 then you should use Solution(object). (This is why we have version tags).
res should go in the function. As per RobertB's comment.
Just call searchRange twice and you will clearly see why.
root, k1 and k2 are all bad names.
Rename them to better ones.
E.G. node, minimum and maximum, respectively.
You should use k1 <= root.val <= k2 instead of root.val >= k1 and root.val <= k2.
There is currently no need to return []. return None or any return work as well.
If you wrap searchRange in another function, it can be much simpler.

If I were to do most of the above. (I didn't put it in a class.)

def search_range(root, minimum, maximum):
    nodes = []

    def recursive_search(node):
        if node is None:
            return None

        if node.val > minimum:
            recursive_search(node.left)
        if minimum <= node.val <= maximum:
            nodes.append(node.val)
        if node.val < maximum:
            recursive_search(node.right)

    recursive_search(root)
    return nodes


Shell script to sync dotfiles repository

Consider putting the following at the beginning of every script:

set -e
set -u

The first makes your script abort as soon as the first command exits with an error. This ensures that your script doesn’t try to operate after it’s failed. The second yields an error whenever you try to access an empty variable.
I’m not sure why you’re using arrays for dotFiles and toArchives here. Using plain variables should work just as well.
Instead of `…` it’s generally advised to use $(…). This makes the expressions nestable and arguably more readable. Well …

This leaves us with:

set -e
set -u

dotFiles=$(ls -da .* | grep -Pxv '\.git|\.+')

# Existing dot files to archive
toArchive=''

cd ~

# Archive: Find clashes and tarball+gzip them
for i in $dotFiles; do
  toArchive=$toArchive $(ls -d $i)
done
if [ "$toArchive" != "" ]; then
  archiveFile="dotfiles"$(date +%Y%m%d)".tar.gz"
  tar czf $archiveFile $toArchive --remove-files
fi

# Create symlinks
for i in $dotFiles; do
  dotFileLink="dotfiles/"$i
  ln -s $dotFileLink $i
done


Median solving from Interview street in Python

def main():
    N = int(raw_input())
    if(0<=N<=100000):

There really isn't much point in checking this. Your code works regardless of the value, and you don't need to worry about whether the contest will feed you larger values

        x = []
        ans=[]
        l=[]
        m=[]

I suggest using longer names even in a contest scenario

        for i in xrange(0, N):
            tmp = raw_input()
            a, b = [xx for xx in tmp.split(' ')]

Actually this line is the same as a, b = tmp.split(' ') The list comphrension just wastes processing power. Since there isn't going to be any unusual whitespcae, you can skip the parameter to split as well

            l.append(a)
            m.append(int(b))

Its not clear why you store this in a list. Just perform the operation as soon as you read it. No need to store things into the lists just to read them in another loop.

        for i in xrange(0, N):

Here you should have used something like for action, number in zip(l,m):

            if l[i]=='r':
                if len(x)<1 or m[i] not in x:

There isn't really a point to checking for len < 1, since the second condition will fail in that case anyways

                        ans.append('Wrong!')

Just print out the output, don't store it up

                elif m[i] in x:

You should be able to just make this an else

                    x.remove(m[i])

This is going to be slow. The checks for m[i] in x and the call to remove have to scan over the whole list to find the elements. But the list is sorted, which means you should be able to find elements faster. Check out the bisect module which enables provides binary search to make finding elements faster in sorted lists.

                    q=len(x)
                    if q%2==1:
                        ans.append(x[(q/2)])
                    elif q%2==0:
                        if q==0:
                            ans.append('Wrong!')

This case is somewhat odd here, it'd make more sense to check for this on level out, before checking for odd and even

                        else:
                            k=x[q/2]+x[(q/2)-1]
                            if k%2==0:
                                ans.append(int(k)/2)
                            else:
                                ans.append(k/2.0)
            elif l[i]=='a':
                x.append(m[i])
                x=sorted(x)

This is better written as x.sort() so as to sort in place. However, its going to be slow constantly resorting the list. Before adding the element, the list is almost sorted, so you can use that to your advantage. The bisect module has operations to make that easy

                p=len(x)
                if p%2==1:
                    ans.append(x[(p/2)])
                else:
                    k=x[p/2]+x[(p/2)-1]
                    if k%2==0:
                        ans.append(int(k)/2)
                    else:
                        ans.append(k/2.0)

Ok, you're doing this again. You should have put this in a function or something

        for i in ans:
            print i

if __name__ == "__main__":
    main()

Maintaining a sorted list is too expensive. Everytime you insert or remove elements, the computer has to shift the whole array in memory. Knowing this the contest site will devise questions to give you the worst case scenario. You are going to have to do something else.

One possibility to explore would be to use a binary tree. Binary trees have faster insertion/removal times, and a reasonably fast way to calculate the median. Their disadvantage here is the complexity required to implement it. A binary tree itself isn't that complicated, but the problem is in a balancing strategy.

A second possibility is to try and use heaps implemented in the heapq module. The idea would be that at any point in time, you maintain two heaps. One has the element less then the median and the other has the elements greater then the median. There is some trickiness there in how you would handle deletions, but I think it could be done.


Analyzer for compression algorithms (or tools)

MAGIC NUMBERS
The number 256 is used in multiple places as an array size. Rather than using the raw number
256, it would be better to use a symbolic constant. Raw numbers in code are sometimes referred to as magic numbers, because it isn't clear what they mean.
There are at least two reasons for this,

It identifies what the number means.
If at some point in the future the number has to be changed for all uses, the code only  needs to be changed in one place.

An Example in C:

#define ARRAY_SIZE 256

void stat(char * file, double vector[ARRAY_SIZE])
{
    int c;
    FILE * ftopen = fopen(file, "r");
    while ((c = getc(ftopen)) != EOF)
      {
        if (c >= 0 && c <= ARRAY_SIZE)
            vector[c]++;
      }

      fclose(ftopen);
}

An Example in C++:

constexpr int ARRAY_SIZE = 256;

Use Meaningful Variable and Function Names
The code contains foo and bar in a number of places. These are not meaningful names.
The names should indicate what the variables are, so that if you or someone else needs
to change the code 2 years in the future it is an easy task rather than having to go
through all the code to see what needs to be changed.

Another exmaple of this is the function ccount(), which could be renamed file_size().

A third example is the array vector. Other than array if doubles it is not clear what
this array is used for.

Inconsistent Coding Style
In a professional setting where multiple people may have to maintain the code it is best
to be as consistent as possible.

The else clauses almost always have { block}` but the if statements do not.
This is true whether or not the block contains multiple statement or not.
You should choose one way or the other.

In the for loops the { is immediately under the for, but in the else clauses it
is indented. Choose one or the other. The most common usage is how you do the for loops.

This is partially a matter of choice, I use { block } on all control statements:

if ()
{
}
else
{
}

for ()
{
}

while ()
{
}

do
{
} while ();

I do this even for single statements because if the code needs to be updated by adding a statement
to a block it is easier for anyone to see where the line of code should be inserted. This was
also required as part of a coding standard at a company where I worked.

Empty Clauses in IF/ELSE
In the function shannon() the code contains:

    if (vector[i] == 0.0)
      continue;
    else
      {
        shan = shan + (log2(pow(vector[i], vector[i])));
      }

This would be clearer if it was written

    if (vector[i] != 0.0)
      {
        shan = shan + (log2(pow(vector[i], vector[i])));
      }

An else clause can be added at a later time if it is needed. The if portion of the current
implementation is meaningless and would be optimized out by the compiler.


Looping Strategy: Change behaviour after first iteration

One elegant way to handle this is to parse the input into a more usable structure before transforming it to HTML. For example, each section could be represented as:

private class Section {
  final String headline;
  final List<String> contents = new ArrayList<String>();

  Section(String headline) {
    this.headline = headline;
  }

  String asHtml() {
    StringBuilder sb = new StringBuilde();

    sb.append("
").append(headline).append("
");
    sb.append("
");
    for (String item : contents) {
      sb.append("
").append(item).append("
");
    }
    sb.append("
");

    return sb.toString();
  }
}

Note how the code clearly shows the structure of the resulting HTML.

The parsing code now has a more focused responsibility: parsing and validating the input. It has nothing to do with the output format any more.

private Iterable
 parseList(String fileContents) {
  List
 sections = new LinkedList
();

  for (String line : fileContents.split("\n")) {
    String[] fields = line.split(":");
    if (fields.length != 2) {
      // throw some exception
    }

    if ("headline".equals(fields[0])) {
      sections.add(new Section(fields[1]));
      continue;
    }

    if (sections.isEmpty()) {
      // throw some error because "content" came before "headline"
    }

    sections.getLast().contents.add(fields[1]);
  }

  return sections;
}

I pointed out some lines with comments where you should do input validation. If you don't do this, you might get surprised by  ArrayIndexOutOfBoundsExceptions if the input string is invalid.

Building an object that represents each section has the advantage that invalid HTML cannot be produces – your current code could emit a
 outside of an
.

Then in your main code, the sections are simply concatenated together:

StringBuilder output = new StringBuilder();
for (Sections section : parseList(...)) {
  output.append(section.asHtml());
}

The advantage of separating the responsibilities of parsing and formatting is that it is now much easier to adapt a single part (e.g. to a new input or output format). My suggestion for the Section class has to be criticized here, because it does not follow the Single Responsibility Principle: it both represents a section, and formats the output. Those should ideally be separated into two different classes, so that the formatting can vary without Section having to change.


Returning interfaces in Java without significant casting

Let me clarify something fist

It gives the caller the ability to use the preferred implementation class.

Even if we return interface from method, that doesn't mean that that caller can choose implementation.'

So if the caller of op wanted to use a LinkedList they could through simple casting.

If you mean something like (LinkedList<Integer>) op(nums), then this wont work and will throw java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.LinkedList.
When method returns interface, in general, you shouldn't assume specific implementation, and thus should avoid such castings. Having interface here, for example, will give more freedom to the author of this method for future changes: imagine someone will write SuperPerfectList which works better than any other list and author decides to use it. In this case even if method changes, we won't need to refactor every place in our code where we call this method, because signature of this method hasn't changed.
If we talk about the situation where we want another implementation of this interface, then, in case of list, we can do new LinkedList(result) and get what we want.


Aggregate summary counts for an array of error objects

Here’s another one towards functional using es6 syntax additions:

const predSeverity = severity => err => err.severity == severity
const byCode = (acc, {errorCode: code}) =>
  acc.set(code, (acc.get(code) || 0) + 1)

errorLog.filter(predSeverity("H")).reduce(byCode, new Map())

It has a bit different result data format (and type, if only for the receiver-as-return-value of Map::set), since the filtering already tells us the severity.


Increase efficiency of card-ordering program

Here is a good opportunity to break out a couple of tools from the standard library.

collections.deque offers fast appends and pops on both ends and is thus perfect to represent your deck of cards, when you take cards from the top and put some back to the bottom.

itertools.cycle can be used to switch between the two destinations of the cards: the top of the pile (table_list.appendleft) and the bottom of the deck (card_list.append). Using appendleft there avoids the need to reverse the pile each round.

Also, a while True loop with a round += 1 inside could be a for round ... loop instead.

from collections import deque
from itertools import cycle, count

def num_of_round(num_cards):
    orig_order = deque(xrange(num_cards))
    card_list  = deque(orig_order)
    table_list = deque()

    for rounds in count(1):
        appendfunc = cycle((table_list.appendleft, card_list.append))
        while card_list:
            append = next(appendfunc)
            append(card_list.popleft())
        card_list, table_list = table_list, card_list
        if card_list == orig_order:
            return rounds


I'm not familiar with that framework, so I can only provide some general points:

You can rewrite the if statement to subject = ad.title or 'Reminder' (see here).
You are a bit inconsistent with spacings (before and after =, ,, (), etc.), and string formatting (your second and third logging.info)
I'd recomment spreading both those chained filters and overly long strings over multiple lines.
Maybe you could use some helper method to derive the HTML version of the message from the plain-text version or vice versa?


Kadane's Algorithm, finding maximum contiguous array

Ok, let's take a look:

Kadane Kadane = new Kadane();

If there is no need for it, I would use static methods and avoid object creation:

public static int localMax(int[] full, int sublength) {...}
public static int splitArr(int[] full) {...}
int max = splitArr(full);
//(+ next point)

int sum = 0;
int max = 0;

I do not see the reason why they are class variables? You could use them in the method scope and have 2 benefits:

You do not have any state inside your class, which makes the methods recallable.
You can be sure nobody starts to modify it somewhere.

public int localMax(int[] full, int sublength) {
    final int sum = 0;
    final int max = 0;
    //...
}

public int splitArr(int[] full)

This is a bad name. If someone reads only the method name, it is impossible to figure out what this is doing. You would expect to split an array? Then you would expect to get back one or multiple arrays. But you get an int.
A better method name could be:

public int getMaximumSumOfAllSubarraysFromArray(final int[] array)

(same goes for localMax)

Instead of:

if (sum > max) {
    max = sum;
}
//...
if (sum_final > max_final) {
    max_final = sum_final;
}

You could write:

max = Math.max(max, sum);
max_final = Math.max(max_final, sum_final);

Which makes the intention directly clear.

If we take this line:

sum_final = localMax(full, j);

You could inline the function localMax:

public int splitArr(final int[] full) {
    int sum_final = 0;
    int max_final = 0;
    for (int j = 0; j < full.length; j++) {
        int sum = 0;
        for (int i = j; i >= 0; i--) {
            sum = sum + full[i];
            sum_final = Math.max(sum_final, sum);
        }
        max_final = Math.max(max_final, sum_final);
    }

    return max_final;
}

Then we look what is happening here:

In the 1. loop iteration, we check calculate the sum from index 0 to index 0
In the 2. loop iteration, we check calculate the sum from index 1 to index 0
In the 3. loop iteration, we check calculate the sum from index 2 to index 0

We can see a pattern here. We do not have to do all the calculations from previous sums, we just use the previous result and add the new current element:

int sum = 0;
for (int j = 0; j < full.length; j++) {
    sum = sum_final + full[i];
    sum_final = Math.max(0, sum);
    max_final = Math.max(max_final, sum_final);
}

Good thing: We got rid of the O(n^2) complexity back to O(n).
Good thing: we can simplify it even more. The variable sum is not necessary and we can use a foreach:

public int splitArr(final int[] full) {
    int sum_final = 0;
    int max_final = 0;
    for (final int element : full) {
        sum_final = Math.max(0, sum_final + element);
        max_final = Math.max(max_final, sum_final);
    }
    return max_final;
}

We can choose some better names for all the variables and if we apply all the mentioned things we could end up with:

public static int getMaximumSumOfAllSubarraysFromArray(final int[] array) {
    int currentMaximum = 0;
    int overallMaximum = 0;
    for (final int arrayItem : array) {
        currentMaximum = Math.max(0, currentMaximum + arrayItem);
        overallMaximum = Math.max(overallMaximum, currentMaximum);
    }
    return overallMaximum;
}

(which is by the way the same algorithm as mentioned from the Wikipedia link, and I think the best one for single thread, typical environments. It could be improved by removing the first Math.max, merging the branches and saving a little part of branching, but this would reduce readability):

public int getMaximumSumOfAllSubarraysFromArray(final int[] array) {
    int currentMaximum = 0;
    int overallMaximum = 0;
    for (final int arrayItem : array) {
        currentMaximum = currentMaximum + arrayItem;
        if (currentMaximum > 0)
            overallMaximum = Math.max(overallMaximum, currentMaximum);
        else
            currentMaximum = 0;
    }
    return overallMaximum;
}

One last piece of advice: If you develop such algorithms and refactor them, you should always have some unit tests for this. Better more than less.

I hope you can combine this hints to a full working approach. If not, just mention the flaws in my descriptions.


I've discovered that node.js v10 supports .finally() for promises (or you could employ a polyfill) so it could be slightly improved by moving the close() logic into a .finally() handler.

function getBlocked(data) {
    let openDb;

    return MongoClient.connect(url).then(db => {
        openDb = db;
        const blQ = {blocked_user:data.tag_search_mail};
        return db.collection("block_list").find(blQ,{"_id":0}).toArray();
    }).then(results => {
        let blocked = results.map(item => item.blocker);
        return blocked;     // make this the resolved value of the promise
    }).finally(() => {
        if (openDb) {
            openDb.close().catch(err => {
                console.log("Error closing db: ", err);
            })
        }
    });
}

Now, it seems as an additional improvement for this particular usage, you can move the .finally() clause to a place where you don't have to save the db variable to the higher scope because all paths with a successfully open db go through one promise chain (assuming no exception in the .then() handler is thrown before db.collection() is called:

function getBlocked(data) {
    return MongoClient.connect(url).then(db => {
        const blQ = {blocked_user:data.tag_search_mail};
        return db.collection("block_list").find(blQ,{"_id":0}).toArray().finally(() => {
            db.close().catch(err => {
                console.log("Error closing db: ", err);
            });
        });
    }).then(results => {
        let blocked = results.map(item => item.blocker);
        return blocked;     // make this the resolved value of the promise
    });
}


Calculating the sum, of the mod Q, position multiplied, sort sequence, of Fibonacci numbers

Complexity

The main issue with your application is the calculation of the "Fibonacci" number.

Here you are looping over the range [0,n). Each time you are calling fib() it recalculates the Fib values from scratch.

        for (int i = 0; i < n; i++)
            S1[i] = fib(i+1);

The complexity of fib is O(k^n) (Approx). You put this in a loop so your complexity is O(n^n). Which is fine for small fixed amount of numbers (fib is simple and usually n is small (less than 100)). But when n is unbound like your problem this becomes a problem.

Fib is also relatively simple and can be done in O(n).

        S[0] = 1;
        S[1] = 1;
        for (int i = 2; i < n; i++)
            S1[i] = S[i - 1] + S[i - 2];

That's it. Complexity now O(n).

Range

You don't address the problem with range. Thee Fibonacci sequence generates numbers that exceed 64 bits in less than 100 iterations. You don't address this in your code.

Now if we look at the problem statement we modulus everything by Q. So we only need the part of number below Q and thus overflow does not matter.

Now you are thinking I am saying it is a problem but then I say its not a problem. What gives. The problem is that this is not expressed in the code. Somebody reading the code at a later time is going to say this is wrong because you overflow the integers. What you need to to do is explain what you are doing in the code so that a reader knows that overflow is not an issue.

        S[0] = 1;
        S[1] = 1;
        // Note n can be large.
        // And this will can potentially overflow
        // But this is not an issue in this case because .....
        // Place explanation of why it works.
        for (int i = 2; i < n; i++)
            S1[i] = S[i - 1] + S[i - 2];

Separation of concerns

Your code should be divided into parts that do business logic and those that do resource management. These two parts of the code should be separated otherwise things become very complicated quickly.

In your code you are doing both in the main loop. You are doing the calculations and performing all the memory management in the same place.

Your code has STUFF (the business logic) intertwined with the resource management. This is bad design.

// STUFF

    int *tmp = new int[n];
    int *count = new int[10];

    // STUFF

    delete[]tmp;
    delete[]count;

// STUFF

Also this is really a very C way of writting the code. In modern C++ we practically never need to deal with pointers as these are handeled by other higher level constructs for us (usually a container or a smart pointer).

In this case we can replace this memory management with a std::vector and achieve the same result.

// STUFF

    std::vector<int> tmp(n);
    std::vector<int> count(10);

    // STUFF

// STUFF

Sorting (using radex)

The radix sort is fun. If the number of buckets is the same as the range of your elements then you don't actually need to do any sorting.

In your case the range is [0,Q) if Q is a reasonable number you can create Q different buckets. Then you just count the number of each element (rather than tracking each one). This makes the sort O(n).

 std::vector<int>   count(Q);
 for(int loop = 0;loop < n; ++loop) {
     ++count[calcNextFib(loop) % Q];
 }

Naming

You use some very short names for variables.

    int i, j, k;

This makes reading the code very hard. The current best practice is called self documenting code. This is where you use variables names to explain what you are doing thus making the code self documenting without the need for extra variables.

Also don't declare the variables at the top of the function declare them at the point where they are about to be used. This becomes more important when you start using complex objects that have constructors but is a good habit to get into with all variables.

Code Review

Stop doing this.

using namespace std;

Its a bad habbit that will get you in trouble latter in life. Always use the std:: prefix in your code.

(Why is “using namespace std” considered bad practice?)[https://stackoverflow.com/q/1452721/14065)

Passing C-Arrays is frowned upon.

int maxbit(int data[], int n)

The more standard way is to use `iterators. Pass the begin and end of a section as the parameters. Remember that iterators behave like pointers so it is still relatively easy to write your code with them.

You don't need to write everything from scratch:

    int maxData = data[0];

    for (int i = 1; i < n; ++i)
    {
        if (maxData < data[i])
            maxData = data[i];
    }

We have a whole library of algorithms that do this:

    auto maxIter = std::max_element(begin , end);
    int maxData  = *maxIter;

A bit of white space vertically to help logically break up the code would be nice:

int main() {
    int T,n,Q;
    cin >> T;
    while (T--) {
        cin >> n >> Q;
        int* S1 = new int[n];
        int* A = new int[n];
        for (int i = 0; i < n; i++)
            S1[i] = fib(i+1);
        for (int i = 0; i < n; i++)
            A[i] = S1[i] % Q;


Dijkstra's implementation in c++ with STL priority_queue

Ohhh. Don't do this:

using EdgeNodes = vector<EdgeNode *>;
unordered_map<char, EdgeNodes *> adj;

Now you need to manage the memory of the EdgeNodes. Simply declare it as a value type:

using EdgeNodes = vector<EdgeNode>;      // Remove the star
unordered_map<char, EdgeNodes>      adj; // Remove the star.

To make the rest of your code simpler I would define a way to compare the EdgeNodes.

class EdgeNode
{
  public:
  char label;
  int weight;
  EdgeNode(char l = 0, int w = 0) : label(l), weight(w) {}

  // Compare a Node against a label
  bool operator==(char l) {return label == l;}
};

This makes your add functions simpler:

  void addNode(char node)
  {
      adj.insert({node, EdgeNodes{}});
  }
  void addEdge(char start, char end, int weight)
  {
      auto& dest = adj[node].second;

      // See if there is already a link to the destination.
      // This uses the `operator==` we defined above to compare
      // each node against `end`.
      auto  find = std::find(std::begin(dest), std::end(dest), end);

      if (find != std::end(dest)) {
          // If we already have it update the weight.
          find->weight = weight;
      }
      else {
          // otherwise add it to the end.
          dest.emplace_back(end, weight);
      }
  }

Don't be lazy:

  Pair front = pq.top(); pq.pop();

Split it over two lines. Its easy to write new code. Its hard to read other people's code. Don't make it difficult for them.

  Pair front = pq.top();   // Get the top item
  pq.pop();                // Pop it from the queue.

The dijkstras algorithm looks ok.

Things to look at:

I find it a bit dense to read and it took me a while to understand it but nothing technically wrong with it.
I might have used a single map for parent/distance calculations rather than two distinct structures.
Checking inclusion in the visited list is usually done on the node as it is popped of the dq not when pushing it onto the list. This may be a bug.
Normall you pass start and end as parameters to djikstras

Let me re-try a refactor:

void djikstras(char snode, char end)
{
    using ParentEdge = std::pair<char, EdgeNode>;
    auto  comp = [](ParentEdge const& l, ParentEdge const& r){return l.second.weight < r.second.weight;};

    unordered_map<char, EdgeNode>                        retrace;
    priority_queue<ParentEdge, vector<ParentEdge>, comp> pq;

    // special case the snode is its own parent.
    retrace[snode]   = EdgeNode(snode, 0);
    pq.push(ParentEdge(snode, EdgeNode(snode, 0)));

    while(!pq.empty()) {
        // Get details of next node.
        ParentEdge front   = pq.top();
        char&      parent  = front.first;
        char&      current = front.second.label;
        int&       weight  = front.second.weight;
        pq.pop();

        if (current === end) {
            // Did we find the destination.
            printRoute(retrace, end);
            return;
        }

        if (retrace.find(current) != retrace.end()) {
            // Already found cheapest route to here.
            continue;
        }

        // Found cheapest route to this point. Add info to the structures.
        retrace[current]  = EdgeNode(parent, retrace[parent].weight + weight);

        // Add children to the frontier list
        for(EdgeNode edge : adj[current]) {
            pq.push(ParentEdge(current, edge));
        }
    }
    std::cout << "Failed to find route from start to finish\n";
}


Validating email addresses through temporary mail message

Well, it really depends on why addressesIn is a string. If it's input from the user, as I suspect, it is a fine method.
If I was to be a harsh critic I would ask why a method named "Validate" returns a string.
I think if you rename the method to like "ScrubEmailAddresses" or "SanitizeEmailAddresses" and envision it in an app that lets a user input email addresses to send an email to, it's kind of nifty. Basically instead of a roll-your-own-validations approach this says "hey, let the framework do it for me!" by taking advantage of the fact that .NET will just throw a FormatException if you try to add an invalid address. It's a fairly decent server-side equivalent to a RegularExpressionValidator using the predefined email regex. I also agree with Mike McCaughan's comment mentioning there is a resource hit when having the framework throw an exception.


You don't need to build this as one line. You could try splitting it out into multiple lines and add some comments to describe what you are doing.

I think the below example does what you want.

I have removed the anonymous RequestMatcher class. RegexRequestMatcher implements the RequestMatcher interface.
I have removed the second csrf() method call as it isn't needed.

@Override
protected void configure(final HttpSecurity http) throws Exception {

    // Enable csrf for login form
    http.csrf().requireCsrfProtectionMatcher(new RegexRequestMatcher("/login/*", null));
    // Configure login page
    http.formLogin().loginPage("/login").failureUrl("/login?error").usernameParameter("username").passwordParameter("password");
    // Configure logout redirect
    http.logout().logoutSuccessUrl("/");
    // Ensure admin pages have correct role
    http.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN");
    // Configure access denied exception redirect
    http.exceptionHandling().accessDeniedPage("/403");

}


Leaving aside the problem of deeply nested code for now, I think readability is greatly improved by the use of LINQ syntax:

var sourceFiles = from file in list
                  from invocation in file.getInvocations()
                  group invocation by (SourceFile)null into groupedByInvoker
                  select groupedByInvoker;

for (var currentDepth = 0; currentDepth < depth; currentDepth++)
{
    foreach (var invokerGroup in sourceFiles)
    {
        int sourceFileCount = currentGroup.Count();
        int counter = 0;

        foreach (var invocation in invokerGroup) {
            // Do stuff
            counter++;
        }
    }

    sourceFiles = from invokerGroup in sourceFiles
                  from file in invokerGroup
                  from invocation in file.getInvocations()
                  group invocation by file into groupedByInvoker
                  select groupedByInvoker;
}

For me, this makes the SelectMany a lot easier to follow. There are some other tweaks to the queries too:

You can just group by null directly, rather than projecting to an anonymous type and selecting that back out as the key.
You don't need to convert to a list if you follow it by a groupby. The groupby traverses and stores the result of the enumerable anyway. You can test this by removing the ToList and adding a break point/debug output inside getInvocations.
By forcing it to evaluate to to a list instead of allowing deferred execution you are actually calling getInvocation too many times. When currentDepth == depth - 1, you don't need to evaluate sourceFiles again and so you don't need to call getInvocations. With deferred execution, because the final sourceFiles is never read getInvocations is never called and everything is fine and dandy.


Your solution looks nice and compact, but it's not necessarily how I would go about it. I come from a background where you have to anticipate faulty input, and so I raise my eyebrows at the first two lines of your method where you blindly start replacing the input.

What happens if you read a line of characters like A B 3 D 5 1? Do you still get A as a result? Numeric characters are still characters. Also, \n is char. The class is much more than what is captured by your [^a-zA-Z] pattern.

The problem specification is straightforward, but you're trying to attack it with regexes instead of something more appropriate. As soon as you transform your input, you are working with data that is manipulated based on your assumptions. This will lead to strange bugs later on that are hard to track down.

I would also suggest changed the method from returning void to char, then let whatever calling method take care of the output.

Finally, make sure you're testing all the bases. What happens when there's an empty string? A string with just one character, or just one integer. What if the last integer is less than 0?


using a cast in an overriden equals method should I use generics and if so, how?

You could try something like the following in The Animal Class:

 @Override
   public boolean equals(Object obj) {
      Animal animal = null;
      if(obj == null || this ==null) {
         return false;
      }
      if(obj instanceof Animal) {
         animal = (Animal) obj;
      }
      if(this.name.equals(animal.getName())) {
         return true;
      }

      return super.equals(obj);
   }

Now if you have a Cat and a Dog which extend Animal
and you check

private Cat cat = new Cat("Pipsy");
private Dog dog = new Dog("Pupsy");

if(cat.equals(dog)) will return false because you check the name, and they have a different one.

I do not think you have to use Generics, Object is generic enough :). Hope this helped


Handling `IO Bool` and `IO (Either a b)` inside `IO (Maybe b)`

Since you need to abort your computation early and return a value different from the final output, the ExceptT transformer would be useful.

import Control.Monad (unless)
import Control.Monad.IO.Class
import Control.Monad.Trans.Except

data E a
  = E1
  | E2
  | E3 a

data L
data R

f :: ExceptT (E L) IO ()
f = do
  liftIO (undefined :: IO Bool) >>= flip unless (throwE E1)
  liftIO (undefined :: IO Bool) >>= flip unless (throwE E2)
  liftIO (undefined :: IO (Either L R)) >>=
    either (throwE . E3) (liftIO . (undefined :: R -> IO ()))

If we want, we can then convert ExceptT (E L) IO () to IO (Maybe (E L)):

f' :: IO (Maybe (E L))
f' = either Just (const Nothing) <$> runExceptT f

If could be further polished by using helper functions from Control.Conditional or a similar library, and by extending the functions, for which undefined fills in, to work within any MonadIO (if that's possible).


Partial application

One way to simplify the code is to eliminate the lambda/anonymous functions using Function.bind() to create Partially applied functions. For instance:

router.get('/online-buyer-count', utils.mcache(15), (req, res, next) => {
    realTime(DB.onlinebuyerNumQuery, 'onlinebuyerNum', req, res, next);
});

can be simplified to

router.get('/online-buyer-count', realTime.bind(null, DB.onlinebuyerNumQuery, 'onlinebuyerNum'));

And similarly for the other three routes, which reduces 12 lines to 4.

looping over the routes

The redundancy could also be simplified using Array.forEach()

['online', 'offline'].forEach(mode => {
    ['buyer', 'seller'].forEach(role => {
        router.get('/'+mode+'-'+role+'-count', realTime.bind(null, DB[mode+role+'NumQuery'], mode+role+'Num'));
    });
});

Taking that one step further using more partially-applied functions, the callback function of the inner forEach can be pulled out to a separate function:

const addRoute = (mode, role) => router.get('/'+mode+'-'+role+'-count', realTime.bind(null, DB[mode+role+'NumQuery'], mode+role+'Num'));

And then that function can be made into a partial and used within the nested forEach:

['online', 'offline'].forEach(mode => ['buyer', 'seller'].forEach(addRoute.bind(null, mode)));

So that can reduce those 4 lines to 2. It may be desirable to break those up into multiple lines for readability.


Powershell for syncing Minecraft save files

Looks fine for me. As a note - instead of using Write-Output for display purposes use Write-Host cmdlet.

In a nutshell, Write-Host writes to the console itself. Think of it as a MsgBox in VBScript. Write-Output, on the other hand, writes to the pipeline, so the next command can accept it as its input. You are not required to use Write-Output in order to write objects, as Write-Output is implicitly called for you.


Most efficient way to populate a vector of integers with no duplicates

Your solution as it stands currently is going to be incredibly slow - it's complexity is O(n^2), so you're looking at roughly 10^18 "operations" for a billion numbers. This is because you need to search through the vector as it grows to see if you have a duplicate, which will go through the vector (on average) (1 + 2 + ... + 999,999,999) / 2 times over the course of the algorithm.

Edit: In fact, it's actually slightly worse than this, since as you generate more numbers, the probability that you generate something you've already "seen" increases.

I'd suggest the following: since an int on most platforms is still 4 bytes, this still has a maximum value of a bit over 2 billion. Hence create a vector with the first billion values in order, and use std::shuffle. This will give you a billion "random" values, with the constraint that nothing will be selected from the upper range [1e9, INT_MAX].

int main()
{
    constexpr int num_values = 1000000000;
    std::vector<int> rand_values(num_values);
    std::mt19937 eng{std::random_device{}()};

    for(int i = 0; i < num_values; ++i) {
        rand_values[i] = i;
    }

    std::shuffle(rand_values.begin(), rand_values.end(), eng);
}


I get a warning from g++ -Weffc++:

144018.cpp: In instantiation of ‘link<T>::link(T) [with T = int]’:
144018.cpp:39:20:   required from ‘void linked_list<T>::push(T) [with T = int]’
144018.cpp:78:16:   required from here
144018.cpp:10:5: warning: ‘link<int>::next’ should be initialized in the member initialization list [-Weffc++]
     link(T value) : data(value) {}
     ^~~~

It's worth building with all the warnings you can stand.  This one is easily fixed by declaring it as

std::shared_ptr<link> next = {};

I found it easier to experiment with your code by encapsulating the specific pointer type within the classes:

template<typename T>
struct link
{
    using pointer = std::shared_ptr<link>;

    T data;
    pointer next = {};
};

template<typename T>
class linked_list
{
    using link_pointer = typename link<T>::pointer;

private:
    link_pointer head = {};
};

Then you can use pointer or link_pointer anywhere that auto won't do.

If I change link::pointer to be a std::unique_ptr, the errors I get are all within reverse() and show() (both of which I would implement outside of the class - the first as a specialization of std::reverse).  But I'm guessing you implemented them as members for the educational value, so I'll continue.  For show, you want to traverse the pointers without transferring ownership, so you can't use unique pointers for your traversal.  But you know you can safely use raw pointers as long as you don't let them leak outside the objects' lifetimes:

template<typename T>
void linked_list<T>::show()
{
    auto current = head.get();
    while (current)
    {
        std::cout << current->data << std::endl;
        current = current->next.get();
    }
}

Your reverse() method does want to take ownership, and can use std::move() to do so:

template<typename T>
void linked_list<T>::reverse()
{
    if (!head) return;

    link_pointer prev;
    link_pointer next;

    while (head->next)
    {
        next = std::move(head->next);
        head->next = std::move(prev);
        prev = std::move(head);
        head = std::move(next);
    }
    head->next = std::move(prev);
}

To add elements in O(1) time rather than O(n) time, maintain a (non-owning) pointer to the tail of the list:

template<typename T>
class linked_list
{
    using link_pointer = typename link<T>::pointer;

private:
    link_pointer head = {};
    link<T> *tail = nullptr;
};

template<typename T>
void linked_list<T>::push(T elem)
{
    auto new_link = new link<T>(std::move(elem));

    if (tail)
        tail->next.reset(new_link);
    else
        head.reset(new_link);
    tail = new_link;
}

Minor style points:

You can write empty argument lists as () rather than C-style (void).
The show() method can be const.
It's a bit more idiomatic to allow (raw or smart) pointer types to convert to bool than to test against nullptr:

{
    if (head)
        head->add_to_end(elem);
    else
        head.reset(new link<T>(elem));
}

Constructors that immediately store their arguments can move from the argument:

link(T value) : data{std::move(value)} {}

This reduces copying (which may become more important when T is bigger than the int used in the test program).

Putting it all together, I get:

#include <iostream>
#include <memory>

template<typename T>
struct link
{
    using pointer = std::unique_ptr<link>;

    T data;
    pointer next = {};

    link(T value) : data{std::move(value)} {}
};

template<typename T>
class linked_list
{
    using link_pointer = typename link<T>::pointer;

public:
    linked_list() = default;
    ~linked_list() = default;

    void push(T elem);
    void show() const;
    void reverse();
private:
    link_pointer head = {};
    link<T> *tail = nullptr;
};

template<typename T>
void linked_list<T>::push(T elem)
{
    auto new_link = new link<T>(std::move(elem));

    if (tail)
        tail->next.reset(new_link);
    else
        head.reset(new_link);
    tail = new_link;
}

template<typename T>
void linked_list<T>::reverse()
{
    if (!head) return;

    link_pointer prev;
    link_pointer next;

    while (head->next)
    {
        next = std::move(head->next);
        head->next = std::move(prev);
        prev = std::move(head);
        head = std::move(next);
    }
    head->next = std::move(prev);
}

template<typename T>
void linked_list<T>::show() const
{
    auto current = head.get();
    while (current)
    {
        std::cout << current->data << std::endl;
        current = current->next.get();
    }
}

int main()
{
    linked_list<int> list;

    list.push(1);
    list.push(2);
    list.push(3);

    list.show();
    list.reverse();
    list.show();
}

For your next steps, I think you'll want to add an iterator type and suitable begin() and end().  Then you'll be able to remove show() and replace it with a simple for (const auto& e: list) std::cout << e;

P.S. Thank you for providing the test program with the code - that certainly makes trying out changes easier!